diff options
author | Thomas Duval <thomas.duval@orange.com> | 2020-06-03 10:06:52 +0200 |
---|---|---|
committer | Thomas Duval <thomas.duval@orange.com> | 2020-06-03 10:06:52 +0200 |
commit | 7bb53c64da2dcf88894bfd31503accdd81498f3d (patch) | |
tree | 4310e12366818af27947b5e2c80cb162da93a4b5 /moon_manager/tests | |
parent | cbea4e360e9bfaa9698cf7c61c83c96a1ba89b8c (diff) |
Update to new version 5.4HEADstable/jermamaster
Signed-off-by: Thomas Duval <thomas.duval@orange.com>
Change-Id: Idcd868133d75928a1ffd74d749ce98503e0555ea
Diffstat (limited to 'moon_manager/tests')
92 files changed, 17469 insertions, 3756 deletions
diff --git a/moon_manager/tests/command_lines/test_complete.py b/moon_manager/tests/command_lines/test_complete.py new file mode 100644 index 00000000..f2d2cdf2 --- /dev/null +++ b/moon_manager/tests/command_lines/test_complete.py @@ -0,0 +1,764 @@ +# Software Name: MOON: + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +import pytest +import os +import yaml + +pytest_plugins = ["pytester"] +CONF = """ +debug: true + +database: + # url: mysql+pymysql://moon:p4sswOrd1@db/moon + url: sqlite:////tmp/database.db + driver: moon_manager.plugins.sql + migration_dir: moon_manager.api.db.migrations + # migration_dir: /home/tom/projets/moon/moon_manager/moon_manager/api/db/migrations/ + +management: + url: http://127.0.0.1:8000 + user: admin + password: admin + token_file: moon.pwd + +orchestration: + driver: moon_manager.plugins.pyorchestrator + connection: local + # driver: moon_manager.plugins.docker_compose + # connection: ssh://admin:admin@1.1.1.1 + # driver: moon_manager.plugins.kubernetes + # connection: ~/.kube/config + port: 10000...10100 + config_dir: /tmp + +information: +# driver: moon_manager.plugins.moon_openstack_plugin +# subjects: +# driver: +# - moon_manager.plugins.openstack +# objects: +# driver: +# - moon_manager.plugins.openstack +# actions: +# driver: +# - moon_manager.plugins.openstack + openstack: + driver: moon_manager.plugins.moon_openstack_plugin + url: http://keystone:5000/v3 + user: admin + password: p4ssw0rd + domain: default + project: admin + check_token: false + certificate: false + global_attrs: + driver: moon_manager.plugins.global_attrs + attributes: + +plugins: + directory: /var/moon/plugins + +components: + manager: + port: 8080 + bind: 0.0.0.0 + hostname: manager + +logging: + version: 1 + + formatters: + brief: + format: "%(levelname)s %(name)s %(message)-30s" + custom: + format: "%(asctime)-15s %(levelname)s %(name)s %(message)s" + + handlers: + console: + class : logging.StreamHandler + formatter: custom + level : INFO + stream : ext://sys.stdout + file: + class : logging.handlers.RotatingFileHandler + formatter: custom + level : DEBUG + filename: /tmp/moon.log + maxBytes: 1048576 + backupCount: 3 + + loggers: + moon: + level: DEBUG + handlers: [console, file] + propagate: no + + root: + level: ERROR + handlers: [console] + +""" +POLICY = """ +{ + "policies": [ + { + "name": "MLS Policy", + "genre": "authz", + "description": "MLS policy", + "model": { + "name": "MLS" + }, + "mandatory": true, + "override": true + } + ], + "models": [ + { + "name": "MLS", + "description": "", + "meta_rules": [ + { + "name": "mls" + } + ], + "override": true + } + ], + "subjects": [ + { + "name": "admin", + "description": "", + "extra": {}, + "policies": [ + { + "name": "MLS Policy" + } + ] + }, + { + "name": "demo", + "description": "", + "extra": {}, + "policies": [ + { + "name": "MLS Policy" + } + ] + } + ], + "subject_categories": [ + { + "name": "level", + "description": "subject level" + } + ], + "subject_data": [ + { + "name": "high", + "description": "", + "policies": [], + "category": { + "name": "level" + } + }, + { + "name": "medium", + "description": "", + "policies": [], + "category": { + "name": "level" + } + }, + { + "name": "low", + "description": "", + "policies": [], + "category": { + "name": "level" + } + } + ], + "subject_assignments": [ + { + "subject": {"name": "admin"}, + "category": {"name": "level"}, + "assignments": [{"name": "high"}] + } + ], + "objects": [ + { + "name": "vm1", + "description": "", + "extra": {}, + "policies": [ + { + "name": "MLS Policy" + } + ] + }, + { + "name": "vm2", + "description": "", + "extra": {}, + "policies": [ + { + "name": "MLS Policy" + } + ] + }, + { + "name": "vm3", + "description": "", + "extra": {}, + "policies": [ + { + "name": "MLS Policy" + } + ] + } + ], + "object_categories": [ + { + "name": "level", + "description": "object level" + } + ], + "object_data": [ + { + "name": "high", + "description": "", + "policies": [], + "category": { + "name": "level" + } + }, + { + "name": "medium", + "description": "", + "policies": [], + "category": { + "name": "level" + } + }, + { + "name": "low", + "description": "", + "policies": [], + "category": { + "name": "level" + } + } + ], + "object_assignments": [ + { + "object": {"name": "vm1"}, + "category": {"name": "level"}, + "assignments": [{"name": "high"}] + }, + { + "object": {"name": "vm2"}, + "category": {"name": "level"}, + "assignments": [{"name": "medium"}] + } + ], + "actions": [ + { + "name": "use_image", + "description": "use_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [] + }, + { + "name": "get_images", + "description": "get_images action for glance", + "extra": { + "component": "glance" + }, + "policies": [] + }, + { + "name": "update_image", + "description": "update_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [] + }, + { + "name": "set_image", + "description": "set_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [] + } + ], + "action_categories": [ + { + "name": "type", + "description": "" + } + ], + "action_data": [ + { + "name": "read", + "description": "read action", + "policies": [], + "category": { + "name": "type" + } + }, + { + "name": "write", + "description": "write action", + "policies": [], + "category": { + "name": "type" + } + }, + { + "name": "execute", + "description": "execute action", + "policies": [], + "category": { + "name": "type" + } + } + ], + "action_assignments": [ + { + "action": {"name": "use_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "read"}, {"name": "execute"}] + }, + { + "action": {"name": "update_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "read"}, {"name": "write"}] + }, + { + "action": {"name": "set_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "write"}] + } + ], + "meta_rules": [ + { + "name": "mls", + "description": "", + "subject_categories": [{"name": "level"}], + "object_categories": [{"name": "level"}], + "action_categories": [{"name": "type"}] + } + ], + "rules": [ + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "high"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "low"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "high"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "low"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "high"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "high"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "medium"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "medium"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "mls"}, + "rule": { + "subject_data": [{"name": "low"}], + "object_data": [{"name": "low"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "MLS Policy"}, + "instructions": [{"decision": "grant"}], + "enabled": true + } + ] +} +""" +PWD = '{"_default": {"1": {"username": "admin", "password": ' \ + '"d2eeefe5df3be1d96c102bc91bd2b3c3a93d58f6c9949b91e4a478135f' \ + '383efcd66af2ede09aff03d579f44e4b6a0bd4e9d9de3dc28222fda7a70f34045fe777", ' \ + '"salt": "37df3e00b84ea5d1d5b17868b588e8c7a32fa2a18d031828ac2b6fd3c37687a2c0105' \ + '2a9c395a32b441bac2034dca1966e88039a1e83aac80795bac9c3fa92bf", "api_key": "4ec3' \ + 'babcdfc765e81e099a29b9d69bb7dbe38b8f226663c09bf79061d3d97d87e30fc5e83a90557313' \ + 'd4fc471d8ea4eecb4faabc9773594dc63018f503e36a22"}}}' + +try: + PWD = open("moon.pwd").read() +except FileNotFoundError: + PWD = open("/etc/moon/moon.pwd").read() + +os.environ["MOON_USERNAME"] = "admin" +os.environ["MOON_PASSWORD"] = "admin" + + +def get_policy_id(policies, name="MLS Policy"): + for policy_id, policy_value in policies.get("policies").items(): + if policy_value.get("name") == name: + return policy_id + + +@pytest.fixture +def run(testdir): + open(os.path.join(str(testdir), "moon.yaml"), "w").write(CONF) + open(os.path.join(str(testdir), "policy_example.json"), "w").write(POLICY) + open(os.path.join(str(testdir), "moon.pwd"), "w").write(PWD) + + def do_run(*args): + args = ["moon_manager"] + list(args) + ret = testdir.run(*args) + print(testdir) + try: + return yaml.safe_load(ret.stdout.lines[-1]) + except Exception as e: + print(e) + return ret.stdout + return do_run + + +@pytest.fixture +def import_policy(run): + if not get_policy_id(run("policies", "list")): + run("import", "policy_example.json") + assert get_policy_id(run("policies", "list")) + return get_policy_id(run("policies", "list")) + + +# def test_import(run): +# ret = run("import", "policy_example.json") +# assert ret +# # TODO: check if policy, meta-rule, ... have been created. + + +def test_slaves(run): + ret = run("slaves", "list") + assert "slaves" in ret + + +def test_pdp(run): + ret = run("pdp", "list") + assert "pdps" in ret + + +def test_policies(run): + ret = run("policies", "list") + assert "policies" in ret + + +def test_subjects(run): + ret = run("subjects", "list") + assert "subjects" in ret + + +def test_objects(run): + ret = run("objects", "list") + assert "objects" in ret + + +def test_actions(run): + ret = run("actions", "list") + assert "actions" in ret + + +def test_subject_categories(run): + ret = run("subject_categories", "list") + assert "subject_categories" in ret + + +def test_object_categories(run): + ret = run("object_categories", "list") + assert "object_categories" in ret + + +def test_action_categories(run): + ret = run("action_categories", "list") + assert "action_categories" in ret + + +# def test_subject_data(run): +# ret = run("subject_data", "get") +# assert "subject_data" in ret +# +# +# def test_object_data(run): +# ret = run("object_data", "get") +# assert "object_data" in ret +# +# +# def test_action_data(run): +# ret = run("action_data", "get") +# assert "action_data" in ret + + +def test_rules(run, import_policy): + ret = run("rules", "list", import_policy) + assert "rules" in ret + + +def test_meta_rules(run): + ret = run("meta_rules", "list") + assert "meta_rules" in ret + + +def test_models(run): + ret = run("models", "list") + print(ret) + assert "models" in ret + + +def test_subject_assignments(run, import_policy): + ret = run("subject_assignments", "list", "MLS Policy") + assert "subject_assignments" in ret + ret = run("subject_assignments", "add", "MLS Policy", "demo", "level", "low") + assert "subject_assignments" in ret + ret = run("subject_assignments", "delete", "MLS Policy", "demo", "level", "low") + assert ret + + +def test_object_assignments(run, import_policy): + ret = run("object_assignments", "list", "MLS Policy") + assert "object_assignments" in ret + ret = run("object_assignments", "add", "MLS Policy", "vm3", "level", "low") + assert "object_assignments" in ret + ret = run("object_assignments", "delete", "MLS Policy", "vm3", "level", "low") + assert ret + + +def test_action_assignments(run, import_policy): + ret = run("action_assignments", "list", "MLS Policy") + assert "action_assignments" in ret + ret = run("action_assignments", "add", "MLS Policy", "get_images", "type", "read") + assert "action_assignments" in ret + ret = run("action_assignments", "delete", "MLS Policy", "get_images", "type", "read") + assert ret + + +# def test_complete(run, import_policy): +# slaves = run("slaves", "get").get("slaves") +# if not slaves: +# ret = run("slaves", "create") +# assert "slaves" in ret +# if not get_policy_id(run("policies", "get")): +# ret = run("import", "policy_example.json") +# assert ret +# +# ret = run("subject_assignments", "create", "MLS Policy", "admin", "level", "high") +# assert "subject_assignments" in ret +# +# subjects = run("subjects", "get", "-n", "admin").get("subjects") +# subject_id = subjects +# +# ret = run("slaves", "delete", "-n", "default") +# assert ret + +def test_users(run): + ret = run("users", "add", "bob", "-p password_bob") + if ret != {'error': 'User bob already exists'}: + assert ret['user_created']['username'] == 'bob' + + ret = run("users", "key", "bob", "-p password_bob") + assert ret + + ret = run("users", "list") + assert "users" in ret + + ret = run("users", "change_password", "bob", "-p passwordbob", "-n new_password") + assert ret == "Wrong password" + + ret = run("users", "change_password", "bob", "-p password_bob", "-n new_password") + assert ret['result'] == "success" + + ret = run("users", "key", "bob", "-p password_bob") + assert not ret + + ret = run("users", "key", "bob", "-p new_password") + assert ret diff --git a/moon_manager/tests/func_postman/Import tests.postman_collection.json b/moon_manager/tests/func_postman/Import tests.postman_collection.json new file mode 100644 index 00000000..93d44e62 --- /dev/null +++ b/moon_manager/tests/func_postman/Import tests.postman_collection.json @@ -0,0 +1,1476 @@ +{ + "info": { + "_postman_id": "86591644-ffdd-4b59-87c1-64221dfa6deb", + "name": "Import tests", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Import", + "event": [ + { + "listen": "test", + "script": { + "id": "b2ac03b5-4862-46f0-8c04-a2b491d5534a", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "pm.test(\"Body matches string\", function () {", + " pm.expect(pm.response.text()).to.include(\"Import ok !\");", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "X-Api-Key", + "value": "{{X-Api-Key}}", + "type": "text" + }, + { + "key": "Content-Type", + "name": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"policies\": [\n {\n \"name\": \"MLS Policy\",\n \"genre\": \"authz\",\n \"description\": \"MLS policy\",\n \"model\": {\n \"name\": \"MLS\"\n },\n \"mandatory\": true,\n \"override\": true\n }\n ],\n \"models\": [\n {\n \"name\": \"MLS\",\n \"description\": \"\",\n \"meta_rules\": [\n {\n \"name\": \"mls\"\n }\n ],\n \"override\": true\n }\n ],\n \"subjects\": [\n {\n \"name\": \"admin\",\n \"description\": \"\",\n \"extra\": {},\n \"policies\": [\n {\n \"name\": \"MLS Policy\"\n }\n ]\n },\n {\n \"name\": \"demo\",\n \"description\": \"\",\n \"extra\": {},\n \"policies\": [\n {\n \"name\": \"MLS Policy\"\n }\n ]\n }\n ],\n \"subject_categories\": [\n {\n \"name\": \"level\",\n \"description\": \"subject level\"\n }\n ],\n \"subject_data\": [\n {\n \"name\": \"high\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n },\n {\n \"name\": \"medium\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n },\n {\n \"name\": \"low\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n }\n ],\n \"subject_assignments\": [\n {\n \"subject\": {\"name\": \"admin\"},\n \"category\": {\"name\": \"level\"},\n \"assignments\": [{\"name\": \"high\"}]\n },\n {\n \"subject\": {\"name\": \"demo\"},\n \"category\": {\"name\": \"level\"},\n \"assignments\": [{\"name\": \"low\"}]\n }\n ],\n \"objects\": [\n {\n \"name\": \"vm1\",\n \"description\": \"\",\n \"extra\": {},\n \"policies\": [\n {\n \"name\": \"MLS Policy\"\n }\n ]\n },\n {\n \"name\": \"vm2\",\n \"description\": \"\",\n \"extra\": {},\n \"policies\": [\n {\n \"name\": \"MLS Policy\"\n }\n ]\n },\n {\n \"name\": \"vm3\",\n \"description\": \"\",\n \"extra\": {},\n \"policies\": [\n {\n \"name\": \"MLS Policy\"\n }\n ]\n }\n ],\n \"object_categories\": [\n {\n \"name\": \"level\",\n \"description\": \"object level\"\n }\n ],\n \"object_data\": [\n {\n \"name\": \"high\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n },\n {\n \"name\": \"medium\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n },\n {\n \"name\": \"low\",\n \"description\": \"\",\n \"policies\": [],\n \"category\": {\n \"name\": \"level\"\n }\n }\n ],\n \"object_assignments\": [\n {\n \"object\": {\"name\": \"vm1\"},\n \"category\": {\"name\": \"level\"},\n \"assignments\": [{\"name\": \"high\"}]\n },\n {\n \"object\": {\"name\": \"vm2\"},\n \"category\": {\"name\": \"level\"},\n \"assignments\": [{\"name\": \"medium\"}]\n },\n {\n \"object\": {\"name\": \"vm3\"},\n \"category\": {\"name\": \"level\"},\n \"assignments\": [{\"name\": \"low\"}]\n }\n ],\n \"actions\": [\n {\n \"name\": \"use_image\",\n \"description\": \"use_image action for glance\",\n \"extra\": {\n \"component\": \"glance\"\n },\n \"policies\": []\n },\n {\n \"name\": \"get_images\",\n \"description\": \"get_images action for glance\",\n \"extra\": {\n \"component\": \"glance\"\n },\n \"policies\": []\n },\n {\n \"name\": \"update_image\",\n \"description\": \"update_image action for glance\",\n \"extra\": {\n \"component\": \"glance\"\n },\n \"policies\": []\n },\n {\n \"name\": \"set_image\",\n \"description\": \"set_image action for glance\",\n \"extra\": {\n \"component\": \"glance\"\n },\n \"policies\": []\n }\n ],\n \"action_categories\": [\n {\n \"name\": \"type\",\n \"description\": \"\"\n }\n ],\n \"action_data\": [\n {\n \"name\": \"read\",\n \"description\": \"read action\",\n \"policies\": [],\n \"category\": {\n \"name\": \"type\"\n }\n },\n {\n \"name\": \"write\",\n \"description\": \"write action\",\n \"policies\": [],\n \"category\": {\n \"name\": \"type\"\n }\n },\n {\n \"name\": \"execute\",\n \"description\": \"execute action\",\n \"policies\": [],\n \"category\": {\n \"name\": \"type\"\n }\n }\n ],\n \"action_assignments\": [\n {\n \"action\": {\"name\": \"use_image\"},\n \"category\": {\"name\": \"type\"},\n \"assignments\": [{\"name\": \"read\"}, {\"name\": \"execute\"}]\n },\n {\n \"action\": {\"name\": \"update_image\"},\n \"category\": {\"name\": \"type\"},\n \"assignments\": [{\"name\": \"read\"}, {\"name\": \"write\"}]\n },\n {\n \"action\": {\"name\": \"set_image\"},\n \"category\": {\"name\": \"type\"},\n \"assignments\": [{\"name\": \"write\"}]\n },\n {\n \"action\": {\"name\": \"get_images\"},\n \"category\": {\"name\": \"type\"},\n \"assignments\": [{\"name\": \"read\"}]\n }\n ],\n \"meta_rules\": [\n {\n \"name\": \"mls\",\n \"description\": \"\",\n \"subject_categories\": [{\"name\": \"level\"}],\n \"object_categories\": [{\"name\": \"level\"}],\n \"action_categories\": [{\"name\": \"type\"}]\n }\n ],\n \"rules\": [\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"high\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"low\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"read\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"high\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"low\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"write\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"high\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"high\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"medium\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"medium\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n },\n {\n \"meta_rule\": {\"name\": \"mls\"},\n \"rule\": {\n \"subject_data\": [{\"name\": \"low\"}],\n \"object_data\": [{\"name\": \"low\"}],\n \"action_data\": [{\"name\": \"execute\"}]\n },\n \"policy\": {\"name\": \"MLS Policy\"},\n \"instructions\": [{\"decision\": \"grant\"}],\n \"enabled\": true\n }\n ]\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/import", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "import" + ] + } + }, + "response": [] + }, + { + "name": "Get Policies", + "event": [ + { + "listen": "test", + "script": { + "id": "7a625729-6d09-4932-97ea-e7e5d8a2f2a7", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "var policy_id = Object.keys(jsonData.policies)[0]", + "pm.globals.set(\"policy_id\", policy_id);", + "", + "pm.test(\"Get policy name\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.policies[policy_id].name).to.eql(\"MLS Policy\");", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies" + ] + } + }, + "response": [] + }, + { + "name": "Get Models", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "var model_id = Object.keys(jsonData.models)[0]", + "pm.globals.set(\"model_id\", model_id);", + "", + "pm.test(\"Get model name\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.models[model_id].name).to.eql(\"MLS\");", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/models", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "models" + ] + } + }, + "response": [] + }, + { + "name": "Get PDP", + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Get subjects", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "var subject_id0 = Object.keys(jsonData.subjects)[0]", + "var subject_id1 = Object.keys(jsonData.subjects)[1]", + "", + "pm.test(\"Check subject name 1\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.subjects[subject_id0].name).to.be.oneOf([\"admin\", \"demo\"]);", + "});", + "", + "pm.test(\"Check subject name 2\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.subjects[subject_id1].name).to.be.oneOf([\"admin\", \"demo\"]);", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/subjects", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "subjects" + ] + } + }, + "response": [] + }, + { + "name": "Get objects", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "var object_id0 = Object.keys(jsonData.objects)[0]", + "var object_id1 = Object.keys(jsonData.objects)[1]", + "var object_id2 = Object.keys(jsonData.objects)[2]", + "", + "pm.test(\"Check object name 1\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.objects[object_id0].name).to.be.oneOf([\"vm1\", \"vm2\", \"vm3\"]);", + "});", + "", + "pm.test(\"Check object name 2\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.objects[object_id1].name).to.be.oneOf([\"vm1\", \"vm2\", \"vm3\"]);", + "});", + "", + "pm.test(\"Check object name 3\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.objects[object_id2].name).to.be.oneOf([\"vm1\", \"vm2\", \"vm3\"]);", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/objects", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "objects" + ] + } + }, + "response": [] + }, + { + "name": "Get actions", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "var action_id0 = Object.keys(jsonData.actions)[0]", + "var action_id1 = Object.keys(jsonData.actions)[1]", + "var action_id2 = Object.keys(jsonData.actions)[2]", + "var action_id3 = Object.keys(jsonData.actions)[3]", + "", + "pm.test(\"Check action name 1\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.actions[action_id0].name).to.be.oneOf([\"use_image\", \"update_image\", \"get_images\", \"set_image\"]);", + "});", + "", + "pm.test(\"Check action name 2\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.actions[action_id1].name).to.be.oneOf([\"use_image\", \"update_image\", \"get_images\", \"set_image\"]);", + "});", + "", + "pm.test(\"Check action name 3\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.actions[action_id2].name).to.be.oneOf([\"use_image\", \"update_image\", \"get_images\", \"set_image\"]);", + "});", + "", + "pm.test(\"Check action name 4\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.actions[action_id3].name).to.be.oneOf([\"use_image\", \"update_image\", \"get_images\", \"set_image\"]);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/actions", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "actions" + ] + } + }, + "response": [] + }, + { + "name": "Get subjects Assignments", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies/{{policy_id}}/subject_assignments", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies", + "{{policy_id}}", + "subject_assignments" + ] + } + }, + "response": [] + }, + { + "name": "Get objects Assignments", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies/{{policy_id}}/object_assignments", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies", + "{{policy_id}}", + "object_assignments" + ] + } + }, + "response": [] + }, + { + "name": "Get actions Assignments", + "event": [ + { + "listen": "test", + "script": { + "id": "0d55b7e8-434a-4715-9966-866282b0d120", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies/{{policy_id}}/action_assignments", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies", + "{{policy_id}}", + "action_assignments" + ] + } + }, + "response": [] + }, + { + "name": "Create Slave", + "event": [ + { + "listen": "test", + "script": { + "id": "93584814-9658-421c-abd8-7f9169eba774", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"slave_port\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].extra.port);", + "pm.globals.set(\"engine_api_key\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].extra.api_key);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"slave_test\",\n\t\"description\": \"...\",\n\t\"address\": \"local\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/slave", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slave" + ] + } + }, + "response": [] + }, + { + "name": "Get Slaves", + "event": [ + { + "listen": "test", + "script": { + "id": "93584814-9658-421c-abd8-7f9169eba774", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"slave_port\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].extra.port);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/slaves", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slaves" + ] + } + }, + "response": [ + { + "name": "Get Slaves", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/slaves", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slaves" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Date", + "value": "Tue, 27 Nov 2018 10:52:13 GMT" + }, + { + "key": "Server", + "value": "WSGIServer/0.2 CPython/3.6.6" + }, + { + "key": "content-type", + "value": "application/json; charset=utf-8" + }, + { + "key": "content-length", + "value": "14" + } + ], + "cookie": [], + "body": "{\n \"slaves\": {}\n}" + } + ] + }, + { + "name": "Create PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"pdp_id\", Object.keys(jsonData.pdps)[0]);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Get PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "pm.test(\"Check PDP name\", function () {", + " var jsonData = pm.response.json();", + " pm.expect(jsonData.pdps[Object.keys(jsonData.pdps)[0]].name).is.eq(\"pdp_1\");", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Add pipeline on slave1", + "event": [ + { + "listen": "prerequest", + "script": { + "id": "ce404af6-6555-43a1-aed4-3d21f9562d24", + "exec": [ + "setTimeout(function(){}, 1000);" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "id": "1cd0f94e-8ced-4f0a-97fa-23e74e59a63f", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "X-Api-key", + "type": "text", + "value": "{{engine_api_key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/pipeline/{{pdp_id}}", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "pipeline", + "{{pdp_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Test authz admin 1", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/admin/vm1/get_images", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "admin", + "vm1", + "get_images" + ] + } + }, + "response": [] + }, + { + "name": "Test authz admin 2", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/admin/vm1/use_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "admin", + "vm1", + "use_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz admin 3", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/admin/vm1/update_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "admin", + "vm1", + "update_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz admin 4", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/admin/vm1/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "admin", + "vm1", + "set_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 1", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm3/get_images", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm3", + "get_images" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 2", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm3/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm3", + "set_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 3", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 204\", function () {", + " pm.response.to.have.status(204);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm3/use_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm3", + "use_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 4", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm2/get_images", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm2", + "get_images" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 5", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm2/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm2", + "set_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 6", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm2/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm2", + "set_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 7", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm1/get_images", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm1", + "get_images" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 8", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm1/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm1", + "set_image" + ] + } + }, + "response": [] + }, + { + "name": "Test authz demo 9", + "event": [ + { + "listen": "test", + "script": { + "id": "a44804be-c5ae-440c-a4fb-b32cb522673b", + "exec": [ + "pm.test(\"Status code is 403\", function () {", + " pm.response.to.have.status(403);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/authz/123456789/demo/vm1/set_image", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "authz", + "123456789", + "demo", + "vm1", + "set_image" + ] + } + }, + "response": [] + } + ] +}
\ No newline at end of file diff --git a/moon_manager/tests/func_postman/Test Manager.postman_collection.json b/moon_manager/tests/func_postman/Test Manager.postman_collection.json new file mode 100644 index 00000000..8d74ce83 --- /dev/null +++ b/moon_manager/tests/func_postman/Test Manager.postman_collection.json @@ -0,0 +1,916 @@ +{ + "info": { + "_postman_id": "b08759d2-c727-4dec-bff2-3858a28c6c5b", + "name": "Test Manager", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Auth error", + "event": [ + { + "listen": "test", + "script": { + "id": "ec805426-ec88-4416-baed-992f3d2ffdfe", + "exec": [ + "pm.test(\"Status code is 401\", function () {", + " pm.response.to.have.status(401);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "000000000000000000000000000000000000000000000000000" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": {}, + "url": { + "raw": "http://127.0.0.1:8000/status", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "status" + ] + } + }, + "response": [] + }, + { + "name": "Create Slave", + "event": [ + { + "listen": "test", + "script": { + "id": "93584814-9658-421c-abd8-7f9169eba774", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"slave_port\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].extra.port);", + "pm.globals.set(\"engine_api_key\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].extra.api_key);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"slave_test\",\n\t\"description\": \"...\",\n\t\"address\": \"local\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/slave", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slave" + ] + } + }, + "response": [] + }, + { + "name": "Get Slaves", + "event": [ + { + "listen": "test", + "script": { + "id": "93584814-9658-421c-abd8-7f9169eba774", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"slave_port\", jsonData.slaves[Object.keys(jsonData.slaves)[0]].port);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"test\",\n\t\"description\": \"...\",\n\t\"address\": \"local\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/slaves", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slaves" + ] + } + }, + "response": [ + { + "name": "Get Slaves", + "originalRequest": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"test\",\n\t\"description\": \"...\",\n\t\"address\": \"local\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/slaves", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "slaves" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Date", + "value": "Tue, 27 Nov 2018 10:52:13 GMT" + }, + { + "key": "Server", + "value": "WSGIServer/0.2 CPython/3.6.6" + }, + { + "key": "content-type", + "value": "application/json; charset=utf-8" + }, + { + "key": "content-length", + "value": "14" + } + ], + "cookie": [], + "body": "{\n \"slaves\": {}\n}" + } + ] + }, + { + "name": "Status on slave", + "event": [ + { + "listen": "prerequest", + "script": { + "id": "ce404af6-6555-43a1-aed4-3d21f9562d24", + "exec": [ + "setTimeout(function(){}, 2000);" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "id": "1cd0f94e-8ced-4f0a-97fa-23e74e59a63f", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/status", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "status" + ] + } + }, + "response": [] + }, + { + "name": "Get Status", + "event": [ + { + "listen": "test", + "script": { + "id": "5cf62b3c-e6f3-4499-b87e-d34e37052e88", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": {}, + "url": { + "raw": "http://127.0.0.1:8000/status", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "status" + ] + } + }, + "response": [] + }, + { + "name": "Create Policy", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"policy_id\", Object.keys(jsonData.policies)[0]);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"policy_1\",\n\t\"description\": \"...\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies" + ] + } + }, + "response": [] + }, + { + "name": "Get Policy", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"policy_1\",\n\t\"description\": \"...\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies/{{policy_id}}", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies", + "{{policy_id}}" + ] + } + }, + "response": [] + }, + { + "name": "Get Policies", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"policy_1\",\n\t\"description\": \"...\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/policies", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "policies" + ] + } + }, + "response": [] + }, + { + "name": "Get PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"policy_1\",\n\t\"description\": \"...\"\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Create PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "", + "var jsonData = JSON.parse(responseBody);", + "pm.globals.set(\"pdp_id\", Object.keys(jsonData.pdps)[0]);", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Get PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp" + ] + } + }, + "response": [] + }, + { + "name": "Get rules", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:8000/rules", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "rules" + ] + } + }, + "response": [] + }, + { + "name": "Get Subject Categories", + "event": [ + { + "listen": "test", + "script": { + "id": "bf2e2194-92e9-4e6f-8930-db19e42fb213", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-Key", + "type": "text", + "value": "{{X-Api-Key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": {}, + "url": { + "raw": "http://127.0.0.1:8000/subject_categories", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "subject_categories" + ] + } + }, + "response": [] + }, + { + "name": "Add pipeline on slave1", + "event": [ + { + "listen": "prerequest", + "script": { + "id": "ce404af6-6555-43a1-aed4-3d21f9562d24", + "exec": [ + "setTimeout(function(){}, 1000);" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "id": "1cd0f94e-8ced-4f0a-97fa-23e74e59a63f", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "X-Api-key", + "value": "{{engine_api_key}}", + "type": "text" + }, + { + "key": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:{{slave_port}}/pipeline/ad7c3600d32c477f8b24dae62333bb5b", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "{{slave_port}}", + "path": [ + "pipeline", + "ad7c3600d32c477f8b24dae62333bb5b" + ] + } + }, + "response": [] + }, + { + "name": "Get pipeline status", + "event": [ + { + "listen": "prerequest", + "script": { + "id": "ce404af6-6555-43a1-aed4-3d21f9562d24", + "exec": [ + "setTimeout(function(){}, 1000);" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "id": "1cd0f94e-8ced-4f0a-97fa-23e74e59a63f", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "X-Api-key", + "type": "text", + "value": "{{engine_api_key}}" + }, + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n\t\"name\": \"pdp_1\",\n\t\"description\": \"...\",\n\t\"vim_project_id\": \"123456789\",\n\t\"security_pipeline\": [\"{{policy_id}}\"]\n}" + }, + "url": { + "raw": "http://127.0.0.1:20000/status", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "20000", + "path": [ + "status" + ] + } + }, + "response": [] + }, + { + "name": "Delete PDP", + "event": [ + { + "listen": "test", + "script": { + "id": "d069a3e9-2497-40ab-99db-f2775eaf8c6d", + "exec": [ + "pm.test(\"Status code is 200\", function () {", + " pm.response.to.have.status(200);", + "});", + "" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "type": "text", + "value": "application/json" + }, + { + "key": "x-api-key", + "value": "{{X-Api-Key}}", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://127.0.0.1:8000/pdp/{{pdp_id}}", + "protocol": "http", + "host": [ + "127", + "0", + "0", + "1" + ], + "port": "8000", + "path": [ + "pdp", + "{{pdp_id}}" + ] + } + }, + "response": [] + } + ] +}
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/Logs/test.txt b/moon_manager/tests/func_tests/Logs/test.txt new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/moon_manager/tests/func_tests/Logs/test.txt diff --git a/moon_manager/tests/func_tests/__init__.py b/moon_manager/tests/func_tests/__init__.py new file mode 100644 index 00000000..1fc53954 --- /dev/null +++ b/moon_manager/tests/func_tests/__init__.py @@ -0,0 +1,11 @@ +# Copyright 2019 Orange 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 logging
+logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(message)s', filename='C:/Users/nzpb1414/PycharmProjects/meta_data_log.log')
+logger = logging.getLogger(__name__)
+
+logger.info('heelloo: Starts')
+logger.debug('Meta-Data Test: Starts')
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/README.md b/moon_manager/tests/func_tests/features/README.md new file mode 100644 index 00000000..ae7fc240 --- /dev/null +++ b/moon_manager/tests/func_tests/features/README.md @@ -0,0 +1,11 @@ +# Installation + +```bash +pip install behave + +pip install paramiko + +pip install numpy + +pip install astropy +```
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/__init__.py b/moon_manager/tests/func_tests/features/__init__.py new file mode 100644 index 00000000..582be686 --- /dev/null +++ b/moon_manager/tests/func_tests/features/__init__.py @@ -0,0 +1,11 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + diff --git a/moon_manager/tests/func_tests/features/assignments.feature b/moon_manager/tests/func_tests/features/assignments.feature new file mode 100644 index 00000000..543eaba2 --- /dev/null +++ b/moon_manager/tests/func_tests/features/assignments.feature @@ -0,0 +1,290 @@ +Feature: Assignments + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1,metarule9 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel3 | Education | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Cambridge Policy | + | WilliamsGeorge | Thisdatahasthevalueofsubjectperimeter | gwilliams@orange.com | abc1234 | | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Cambridge Policy | + | Vacations | Thisistherequesttoaccessfile | | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Cambridge Policy | + | Edit | Thisistheactionrequired | | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + | Stanford Policy | Authorization-Level: | Professor | This data has the value of subject category | + | Cambridge Policy | Affiliation: | University-of-Cambridge | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Professor | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Lecturer | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Stanford Policy | Type: | Adminstrative | This data has the value of object category | + | Stanford Policy | Type: | Staff | This data has the value of object category | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | Cambridge Policy | Type: | Teaching-Staff | This data has the value of object category | + | Cambridge Policy | Clearance: | Confidential | This data has the value of object category | + | Cambridge Policy | Clearance: | Access-with-permission | This data has the value of object category | + | Cambridge Policy | Clearance: | Public | This data has the value of object category | + + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Stanford Policy | Action-Priority: | Low | This data has the value of action category | + | Cambridge Policy | Action-Priority: | High | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Low | This data has the value of action category | + | Cambridge Policy | Action-Class: | Severe | This data has the value of action category | + | Cambridge Policy | Action-Class: | Intermediate | This data has the value of action category | + | Cambridge Policy | Action-Class: | Low | This data has the value of action category | + + + Scenario: Add subject assignment + When the user sets to add the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | University-of-Cambridge | Cambridge Policy | + | WilliamsJoeseph | Authorization-Level: | Lecturer | Cambridge Policy | + Then the following subject assignment should be existed in the system + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | University-of-Cambridge | Cambridge Policy | + | WilliamsJoeseph | Authorization-Level: | Lecturer | Cambridge Policy | + + + Scenario Outline: Add subject assignment validations + When the user sets to add the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | <subjectperimetername> | <subjectcategory> | <subjectdata> | <policyname> | + + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectperimetername | subjectcategory | subjectdata | policyname | flag | + | | Affiliation: | University-of-Stanford | Stanford Policy | False | + | 000000000000000000000000000000000000000000000000000 | Affiliation: | University-of-Stanford | Stanford Policy | False | + | GeorgeWilliams | Affiliation: | University-of-Cambridge | Cambridge Policy | False | + | WilliamsGeorge | Authorization-Level: | Professor | Cambridge Policy | False | + | JohnLewis | | University-of-Stanford | Stanford Policy | False | + | JohnLewis | 000000000000000000000000000000000000000000000000000 | University-of-Stanford | Stanford Policy | False | + | WilliamsJoeseph | Authorization-Level: | | Cambridge Policy | False | + | WilliamsJoeseph | Authorization-Level: | 000000000000000000000000000000000000000000000000000 | Cambridge Policy | False | + | WilliamsJoeseph | Authorization-Level: | Admin | | False | + | WilliamsJoeseph | Authorization-Level: | Admin | 000000000000000000000000000000000000000000000000000 | False | + + Scenario Outline: Add an existing subject assignment + Given the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | WilliamsJoeseph | Authorization-Level: | Lecturer | Cambridge Policy | + When the user sets to add the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | <subjectperimetername> | <subjectcategory> | <subjectdata> | <policyname> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectperimetername | subjectcategory | subjectdata | policyname | flag | + | WilliamsJoeseph | Authorization-Level: | Lecturer | Cambridge Policy | False | + | WilliamsJoeseph | Authorization-Level: | Professor | Cambridge Policy | True | + + Scenario: Delete subject assignments + Given the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | JohnLewis | Affiliation: | Stanford | Stanford Policy | + When the user sets to delete the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + Then the following subject assignment should be existed in the system + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | Stanford | Stanford Policy | + + + Scenario: Add object assignments + When the user sets to add the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + | ProfessorsPromotionDocument | Clearance: | Public | Stanford Policy | + | StudentsGradesSheet | Clearance: | Top-Secret | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + | StudentsGradesSheet | Clearance: | Public | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Cambridge Policy | + | StudentsGradesSheet | Clearance: | Public | Cambridge Policy | + Then the following object assignment should be existed in the system + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential,Public | Stanford Policy | + | StudentsGradesSheet | Clearance: | Top-Secret,Confidential,Public | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential,Public | Cambridge Policy | + + + Scenario Outline: Add object assignment validations + When the user sets to add the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | <objectperimetername> | <objectcategory> | <objectdata> | <policyname> | + + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectperimetername | objectcategory | objectdata | policyname | flag | + | | Clearance: | Confidential | Cambridge Policy | False | + | Vacations | Clearance: | Confidential | Stanford Policy | False | + | 000000000000000000000000000000000000000000000000000 | Clearance: | Confidential | Stanford Policy | False | + | StudentsGradesSheet | | Confidential | Cambridge Policy | False | + | StudentsGradesSheet | 000000000000000000000000000000000000000000000000000 | Confidential | Cambridge Policy | False | + | StudentsGradesSheet | Clearance: | | Cambridge Policy | False | + | StudentsGradesSheet | Clearance: | 000000000000000000000000000000000000000000000000000 | Stanford Policy | False | + | StudentsGradesSheet | Clearance: | Confidential | | False | + | StudentsGradesSheet | Clearance: | Confidential | 000000000000000000000000000000000000000000000000000 | False | + + Scenario Outline: Add an existing object assignment + Given the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + When the user sets to add the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | <objectperimetername> | <objectcategory> | <objectdata> | <policyname> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectperimetername | objectcategory | objectdata | policyname | flag | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | False | + + Scenario: Delete object assignment + Given the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Public | Stanford Policy | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + When the user sets to delete the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + Then the following object assignment should be existed in the system + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Public | Stanford Policy | + + Scenario: Add action assignment + When the user sets to add the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Delete | Action-Priority: | Medium | Cambridge Policy | + | Read | Action-Class: | Low | Stanford Policy | + Then the following action assignment should be existed in the system + | actionperimetername | actioncategory | actiondata | policyname | + | Delete | Action-Priority: | Medium | Cambridge Policy | + | Read | Action-Class: | Low | Stanford Policy | + + Scenario Outline: Add action assignment validations + When the user sets to add the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | <actionperimetername> | <actioncategory> | <actiondata> | <policyname> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionperimetername | actioncategory | actiondata | policyname | flag | + | | Action-Class: | Severe | Stanford Policy | False | + | Edit | Action-Class: | Severe | Stanford Policy | False | + | 000000000000000000000000000000000000000000000000000 | Action-Class: | Severe | Stanford Policy | False | + | Read | | Severe | Stanford Policy | False | + | Read | Action-Priority: | Severe | Stanford Policy | False | + | Read | 000000000000000000000000000000000000000000000000000 | Severe | Stanford Policy | False | + | Read | Action-Class: | | Stanford Policy | False | + | Read | Action-Class: | 000000000000000000000000000000000000000000000000000 | Stanford Policy | False | + | Read | Action-Class: | high | | False | + | Delete | Action-Class: | high | 000000000000000000000000000000000000000000000000000 | False | + | Delete | Action-Class: | high | Stanford Policy | False | + + Scenario Outline: Add an existing action assignment + Given the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + When the user sets to add the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | <actionperimetername> | <actioncategory> | <actiondata> | <policyname> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionperimetername | actioncategory | actiondata | policyname | flag | + | Read | Action-Class: | Severe | Stanford Policy | False | + + Scenario: Delete action assignments + Given the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + | Read | Action-Class: | Low | Stanford Policy | + When the user sets to delete the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + Then the following action assignment should be existed in the system + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Low | Stanford Policy |
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/authorization_pipeline.feature b/moon_manager/tests/func_tests/features/authorization_pipeline.feature new file mode 100644 index 00000000..8a175915 --- /dev/null +++ b/moon_manager/tests/func_tests/features/authorization_pipeline.feature @@ -0,0 +1,388 @@ +Feature: Authorization Pipeline + + Background: + + #Given the manager is configured + Given no slave is created + And the slave is created + And the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel3 | Education | + And the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Stanford Policy | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Cambridge Policy | + #| WilliamsGeorge | Thisdatahasthevalueofsubjectperimeter | gwilliams@orange.com | abc1234 | | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Cambridge Policy | + #| Vacations | Thisistherequesttoaccessfile | | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Cambridge Policy | + #| Edit | Thisistheactionrequired | | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + | Cambridge Policy | Affiliation: | University-of-Cambridge | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Professor | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Lecturer | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | Cambridge Policy | Type: | Teaching-Staff | This data has the value of object category | + | Cambridge Policy | Clearance: | Confidential | This data has the value of object category | + | Cambridge Policy | Clearance: | Access-with-permission | This data has the value of object category | + | Cambridge Policy | Clearance: | Public | This data has the value of object category | + + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Cambridge Policy | Action-Priority: | High | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Low | This data has the value of action category | + | Cambridge Policy | Action-Class: | Severe | This data has the value of action category | + | Cambridge Policy | Action-Class: | Intermediate | This data has the value of action category | + | Cambridge Policy | Action-Class: | Low | This data has the value of action category | + + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | Stanford | Stanford Policy | + + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | StudentsGradesSheet | Clearance: | Access-with-permission | Cambridge Policy | + | StudentsGradesSheet | Clearance: | Public | Cambridge Policy | + #| StudentsGradesSheet | Clearance: | Top-Secret | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + #| StudentsGradesSheet | Clearance: | Public | Stanford Policy | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + #| Read | Action-Class: | Low | Stanford Policy | + | Delete | Action-Priority: | High | Cambridge Policy | + | Delete | Action-Priority: | Medium | Cambridge Policy | + | Delete | Action-Priority: | Low | Cambridge Policy | + And the following rule exists + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + #| University-of-Stanford,Professor,Public,Adminstrative,Low,Low | metarule9 | grant | Stanford Policy | + And the pipeline is running + And the following authorization request is granted through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | StudentsGradesSheet | Read | + + Scenario: Check authorization response after rule deletion + When the user sets to delete the following rules + | rule | metarulename | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after rule deletion then addition + When the user sets to delete the following rules + | rule | metarulename | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | Stanford Policy | + And the user sets to add the following rules + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + +Scenario: Check authorization response after subject assignment deletion + When the user sets to delete the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject assignment deletion then addition + When the user sets to delete the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the user sets to add the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object assignment deletion + When the user sets to delete the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object assignment deletion then addition + When the user sets to delete the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + And the user sets to add the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action assignment deletion + When When the user sets to delete the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action assignment deletion then addition + When the user sets to delete the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + And the user sets to add the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Low | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + + Scenario: Check authorization response after subject data deletion + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject data deletion then addition + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + And the user sets to add the following subject data + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object data deletion + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object data deletion then addition + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + And the user sets to add the following object data + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action data deletion + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action data deletion then addition + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + And the user sets to add the following action data + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + + Scenario: Check authorization response after subject perimeter deletion + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject perimeter deletion then addition + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + And the user sets to add the following subject perimeter + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object perimeter deletion + When the user sets to delete the following object perimeter + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object perimeter deletion then addition + When the user sets to delete the following object perimeter + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + And the user sets to add the following object perimeter + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action perimeter deletion + When the user sets to delete the following action perimeter + | actionperimetername | policies | + | Read | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action perimeter deletion then addition + When the user sets to delete the following action perimeter + | actionperimetername | policies | + | Read | Stanford Policy | + And the user sets to add the following action perimeter + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + And the following authorization request is sent through pipeline + | subjectperimetername | objectperimetername | actionperimetername | + | JohnLewis | ProfessorsPromotionDocument | Read | + Then the authorization response should be the following + | auth_response | + | grant | diff --git a/moon_manager/tests/func_tests/features/authorization_wrapper.feature b/moon_manager/tests/func_tests/features/authorization_wrapper.feature new file mode 100644 index 00000000..43fdb519 --- /dev/null +++ b/moon_manager/tests/func_tests/features/authorization_wrapper.feature @@ -0,0 +1,386 @@ +Feature: Authorization Wrapper + + Background: + + Given no slave is created + And the slave is created + And the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel3 | Education | + And the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Stanford Policy | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Cambridge Policy | + #| WilliamsGeorge | Thisdatahasthevalueofsubjectperimeter | gwilliams@orange.com | abc1234 | | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Cambridge Policy | + #| Vacations | Thisistherequesttoaccessfile | | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Cambridge Policy | + #| Edit | Thisistheactionrequired | | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + | Cambridge Policy | Affiliation: | University-of-Cambridge | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Professor | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Lecturer | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | Cambridge Policy | Type: | Teaching-Staff | This data has the value of object category | + | Cambridge Policy | Clearance: | Confidential | This data has the value of object category | + | Cambridge Policy | Clearance: | Access-with-permission | This data has the value of object category | + | Cambridge Policy | Clearance: | Public | This data has the value of object category | + + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Cambridge Policy | Action-Priority: | High | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Low | This data has the value of action category | + | Cambridge Policy | Action-Class: | Severe | This data has the value of action category | + | Cambridge Policy | Action-Class: | Intermediate | This data has the value of action category | + | Cambridge Policy | Action-Class: | Low | This data has the value of action category | + + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | Stanford | Stanford Policy | + + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | StudentsGradesSheet | Clearance: | Access-with-permission | Cambridge Policy | + | StudentsGradesSheet | Clearance: | Public | Cambridge Policy | + #| StudentsGradesSheet | Clearance: | Top-Secret | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + #| StudentsGradesSheet | Clearance: | Public | Stanford Policy | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + #| Read | Action-Class: | Low | Stanford Policy | + | Delete | Action-Priority: | High | Cambridge Policy | + | Delete | Action-Priority: | Medium | Cambridge Policy | + | Delete | Action-Priority: | Low | Cambridge Policy | + And the following rule exists + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + #| University-of-Stanford,Professor,Public,Adminstrative,Low,Low | metarule9 | grant | Stanford Policy | + And the following authorization request is granted through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + + Scenario: Check authorization response after rule deletion + When the user sets to delete the following rules + | rule | metarulename | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after rule deletion then addition + When the user sets to delete the following rules + | rule | metarulename | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | Stanford Policy | + And the user sets to add the following rules + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after subject assignment deletion + When the user sets to delete the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject assignment deletion then addition + When the user sets to delete the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the user sets to add the following subject assignment + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object assignment deletion + When the user sets to delete the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object assignment deletion then addition + When the user sets to delete the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + And the user sets to add the following object assignment + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action assignment deletion + When When the user sets to delete the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action assignment deletion then addition + When the user sets to delete the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + And the user sets to add the following action assignment + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Low | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + + Scenario: Check authorization response after subject data deletion + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject data deletion then addition + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + And the user sets to add the following subject data + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object data deletion + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object data deletion then addition + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + And the user sets to add the following object data + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action data deletion + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action data deletion then addition + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + And the user sets to add the following action data + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + + Scenario: Check authorization response after subject perimeter deletion + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after subject perimeter deletion then addition + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + And the user sets to add the following subject perimeter + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after object perimeter deletion + When the user sets to delete the following object perimeter + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after object perimeter deletion then addition + When the user sets to delete the following object perimeter + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + And the user sets to add the following object perimeter + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | + + Scenario: Check authorization response after action perimeter deletion + When the user sets to delete the following action perimeter + | actionperimetername | policies | + | Read | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | denied | + + Scenario: Check authorization response after action perimeter deletion then addition + When the user sets to delete the following action perimeter + | actionperimetername | policies | + | Read | Stanford Policy | + And the user sets to add the following action perimeter + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + And the following authorization request is sent through wrapper + | keystone_project_id | subjectperimetername | objectperimetername | actionperimetername | + | 0000000000000000000000000000000000000000000000000000000000000000 | JohnLewis | StudentsGradesSheet | Read | + Then the authorization response should be the following + | auth_response | + | grant | diff --git a/moon_manager/tests/func_tests/features/data.feature b/moon_manager/tests/func_tests/features/data.feature new file mode 100644 index 00000000..1edb4098 --- /dev/null +++ b/moon_manager/tests/func_tests/features/data.feature @@ -0,0 +1,330 @@ +Feature: Data + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule8 | + | universitymodel4 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel3 | Education | + | MIT Policy | This is a basic policy | universitymodel2 | Education | + | Oxford Policy | This is a basic policy | universitymodel4 | Education | + + + Scenario: Add subject data + When the user sets to add the following subject data + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Cambridge Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | MIT Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | MIT Policy | Affiliation: | University-of-MIT | This data has the value of subject category | + | Oxford Policy | Affiliation: | University-of-Oxford | This data has the value of subject category | + | Oxford Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + Then the following subject data should be existed in the system + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Cambridge Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | MIT Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | MIT Policy | Affiliation: | University-of-MIT | This data has the value of subject category | + | Oxford Policy | Affiliation: | University-of-Oxford | This data has the value of subject category | + | Oxford Policy | Authorization-Level: | Teaching-staff | This data has the value of subject category | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + + Scenario Outline: Add subject data validations + When the user sets to add the following subject data + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | <policyname> | <subjectcategory> | <subjectdataname> | <subjectdatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | subjectcategory | subjectdataname | subjectdatadescription | flag | + | | Affiliation: | University-of-Stanford | This data has the value of subject category | False | + | 000000000000000000000000000000000000000000000000000000000 | Affiliation: | University-of-Stanford | This data has the value of subject category | False | + | 0000000000000000000000000000000000000000000000000000000000000000 | Affiliation: | University-of-Stanford | This data has the value of subject category | False | + | 0000000000000000000000000000000000000000000000000000000000000000000 | Affiliation: | University-of-Stanford | This data has the value of subject category | False | + | Cambridge Policy | Affiliation: | University-of-Cambridge | This data has the value of subject category | False | + | Stanford Policy | | University-of-Stanford | This data has the value of subject category | False | + | Stanford Policy | 000000000000000000000000000000000000000000000000000000000 | University-of-Stanford | This data has the value of subject category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000 | University-of-Stanford | This data has the value of subject category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000000 | University-of-Stanford | This data has the value of subject category | False | + | Stanford Policy | Affiliation: | | This data has the value of subject category | False | + | Stanford Policy | Affiliation: | _%University-of-Stanford%_ | This data has the value of subject category | True | + | Stanford Policy | Affiliation: | 1 | This data has the value of subject category | True | + | Stanford Policy | Affiliation: | University-of-Stanford | | True | + | Stanford Policy | Affiliation: | University-of-Stanford | _%This data has the value of subject category%_ | True | + + Scenario Outline: Add an existing subject data + Given the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + When the user sets to add the following subject data + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | <policyname> | <subjectcategory> | <subjectdataname> | <subjectdatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | subjectcategory | subjectdataname | subjectdatadescription | flag | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | False | + | Stanford Policy | Affiliation: | University-of-Stanford,Faculty-of-Computer-Science | This data has the value of subject category | True | + + Scenario: Delete subject data + Given the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + Then the following subject data should be existed in the system + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | | | | | + + Scenario: Delete subject data that has a recorded assignment dependency + Given the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + And the following subject perimeter exists + | policies | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | + | Stanford Policy | JohnLewis | This data has the value of subject perimeter | jlewis@orange.com | abc1234 | + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | John Lewis | Affiliation: | University-of-Stanford | Stanford Policy | + When the user sets to delete the following subject data + | policyname | subjectcategory | subjectdataname | + | Stanford Policy | Affiliation: | University-of-Stanford | + Then the system should reply the following + | flag | + | True | + And the following subject data should be existed in the system + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | | | | | + + + Scenario: Add object data + When the user sets to add the following object data + | policyname | objectcategory | objectdataname | objectdatadescription | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | MIT Policy | Type: | Adminstrative | This data has the value of object category | + | MIT Policy | Clearance: | Confidential | This data has the value of object category | + | Oxford Policy | Type: | Adminstrative | This data has the value of object category | + | Oxford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + + Then the following object data should be existed in the system + | policyname | objectcategory | objectdataname | objectdatadescription | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | MIT Policy | Type: | Adminstrative | This data has the value of object category | + | MIT Policy | Clearance: | Confidential | This data has the value of object category | + | Oxford Policy | Type: | Adminstrative | This data has the value of object category | + | Oxford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + + Scenario Outline: Add object data validations + When the user sets to add the following object data + | policyname | objectcategory | objectdataname | objectdatadescription | + | <policyname> | <objectcategory> | <objectdataname> | <objectdatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | objectcategory | objectdataname | objectdatadescription | flag | + | | Clearance: | Confidential | This data has the value of object category | False | + | 000000000000000000000000000000000000000000000000000000000 | Clearance: | Confidential | This data has the value of object category | False | + | 0000000000000000000000000000000000000000000000000000000000000000 | Clearance: | Confidential | This data has the value of object category | False | + | 0000000000000000000000000000000000000000000000000000000000000000000 | Clearance: | Confidential | This data has the value of object category | False | + #| Cambridge Policy | Clearance: | Confidential | This data has the value of object category | False | + | Stanford Policy | | Confidential | This data has the value of object category | False | + #| Stanford Policy | Type: | Confidential | This data has the value of object category | False | + | Stanford Policy | 000000000000000000000000000000000000000000000000000000000 | Confidential | This data has the value of object category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000 | Confidential | This data has the value of object category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000000 | Confidential | This data has the value of object category | False | + | Stanford Policy | Clearance: | | This data has the value of object category | False | + | Stanford Policy | Clearance: | _%Confidential%_ | This data has the value of object category | True | + | Stanford Policy | Clearance: | 1 | This data has the value of object category | True | + | Stanford Policy | Clearance: | Confidential | | True | + | Stanford Policy | Clearance: | Confidential | _%This data has the value of object category%_ | True | + + Scenario Outline: Add an existing object data + Given the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + When the user sets to add the following object data + | policyname | objectcategory | objectdataname | objectdatadescription | + | <policyname> | <objectcategory> | <objectdataname> | <objectdatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | objectcategory | objectdataname | objectdatadescription | flag | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | False | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | True | + + Scenario: Delete object data + Given the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + Then the following object data should be existed in the system + | policyname | objectcategory | objectdataname | objectdatadescription | + | | | | | + + Scenario: Delete object data that has a recorded assignment dependency + Given the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Cambridge Policy | Type: | Top-Secret | This data has the value of object category | + And the following object perimeter exists + | policies | objectperimetername | objectperimeterdescription | + | Stanford Policy | ProfessorsPromotionDocument | This data has the value of object perimeter | + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Top-Secret | Stanford Policy | + When the user sets to delete the following object data + | policyname | objectcategory | objectdataname | + | Stanford Policy | Clearance: | Top-Secret | + Then the system should reply the following + | flag | + | True | + And the following object data should be existed in the system + | policyname | objectcategory | objectdataname | objectdatadescription | + | Cambridge Policy | Type: | Top-Secret | This data has the value of object category | + + + Scenario: Add action data + When the user sets to add the following action data + | policyname | actioncategory | actiondataname | actiondatadescription | + | Cambridge Policy | Action-Priority: | high | This data has the value of action category | + | MIT Policy | Action-Priority: | high | This data has the value of action category | + | MIT Policy | Action-Class: | Severe | This data has the value of action category | + | Oxford Policy | Action-Priority: | high | This data has the value of action category | + | Oxford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + + Then the following action data should be existed in the system + | policyname | actioncategory | actiondataname | actiondatadescription | + | Cambridge Policy | Action-Priority: | high | This data has the value of action category | + | MIT Policy | Action-Priority: | high | This data has the value of action category | + | MIT Policy | Action-Class: | Severe | This data has the value of action category | + | Oxford Policy | Action-Priority: | high | This data has the value of action category | + | Oxford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + + Scenario Outline: Add action data validations + When the user sets to add the following action data + | policyname | actioncategory | actiondataname | actiondatadescription | + | <policyname> | <actioncategory> | <actiondataname> | <actiondatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | actioncategory | actiondataname | actiondatadescription | flag | + | | Action-Class: | Severe | This data has the value of action category | False | + | 000000000000000000000000000000000000000000000000000000000 | Action-Class: | Severe | This data has the value of action category | False | + | 0000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Severe | This data has the value of action category | False | + | 0000000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Severe | This data has the value of action category | False | + #| Cambridge Policy | Action-Class: | Severe | This data has the value of action category | False | + | Stanford Policy | | Severe | This data has the value of action category | False | + | Stanford Policy | 000000000000000000000000000000000000000000000000000000000 | Severe | This data has the value of action category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000 | Severe | This data has the value of action category | False | + | Stanford Policy | 0000000000000000000000000000000000000000000000000000000000000000000 | Severe | This data has the value of action category | False | + | Stanford Policy | Action-Class: | | This data has the value of action category | False | + | Stanford Policy | Action-Class: | _%Severe%_ | This data has the value of action category | True | + | Stanford Policy | Action-Class: | 1 | This data has the value of action category | True | + | Stanford Policy | Action-Class: | Severe | | True | + | Stanford Policy | Action-Class: | Severe | _%This data has the value of action category%_ | True | + + Scenario Outline: Add an existing action data + Given the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + When the user sets to add the following action data + | policyname | actioncategory | actiondataname | actiondatadescription | + | <policyname> | <actioncategory> | <actiondataname> | <actiondatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | actioncategory | actiondataname | actiondatadescription | flag | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | False | + | Stanford Policy | Action-Class: | high | This data has the value of action category | True | + + Scenario: Delete action data + Given the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + Then the following action data should be existed in the system + | policyname | actioncategory | actiondataname | actiondatadescription | + | | | | | + + Scenario: Delete action data that has a recorded assignment dependency + Given the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | + And the following action perimeter exists + | policies | actionperimetername | actionperimeterdescription | + | Stanford Policy | Read | This data has the value of action perimeter | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + When the user sets to delete the following action data + | policyname | actioncategory | actiondataname | + | Stanford Policy | Action-Class: | Severe | + Then the system should reply the following + | flag | + | True | + And the following action data should be existed in the system + | policyname | actioncategory | actiondataname | actiondatadescription | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | diff --git a/moon_manager/tests/func_tests/features/environment.py b/moon_manager/tests/func_tests/features/environment.py new file mode 100644 index 00000000..b65c292d --- /dev/null +++ b/moon_manager/tests/func_tests/features/environment.py @@ -0,0 +1,27 @@ +# Software Name: MOON: + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +from __future__ import print_function +import logging + +logger = logging.getLogger(__name__) + +def before_feature(context, feature): + handler = logging.FileHandler(filename='Logs/'+"Automation Testing Log- "+ feature.name + ".log") + formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s') + handler.setFormatter(formatter) + handler.setLevel(logging.INFO) + logger.addHandler(handler) + + +def before_all(context): + logging.getLogger("requests").setLevel(logging.WARN) + diff --git a/moon_manager/tests/func_tests/features/meta_data.feature b/moon_manager/tests/func_tests/features/meta_data.feature new file mode 100644 index 00000000..18817e2e --- /dev/null +++ b/moon_manager/tests/func_tests/features/meta_data.feature @@ -0,0 +1,295 @@ +Feature: Meta Data ( Category ) + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + + + + Scenario: Add subject category + When the user sets to add the following meta data subject category + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + Then the following meta data subject category should be existed in the system + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + + Scenario Outline: Add meta data subject validations + When the user sets to add the following meta data subject category + | subjectmetadataname | subjectmetadatadescription | + | <subjectmetadataname> | <subjectmetadatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectmetadataname | subjectmetadatadescription | flag | + | | This meta data has the categorical information about a subject | False | + | Affiliation: | | True | + | 1 | This meta data has the categorical information about a subject% | True | + | _%Affiliation:%_ | This meta data has the categorical information about a subject | True | + + Scenario: Add an existing meta data subject + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about an subject1 | + When the user sets to add the following meta data subject category + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about an subject1 | + Then the system should reply the following + | flag | + | False | + + Scenario: Delete subject category + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + When the user sets to delete the following meta data subject category + | subjectmetadataname | + | Affiliation: | + Then the following meta data subject category should be existed in the system + | subjectmetadataname | subjectmetadatadescription | + | | | + + Scenario: Delete subject category that has a recorded meta-rule dependency + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta data subject category + | subjectmetadataname | + | Affiliation: | + Then the system should reply the following + | flag | + | False | + And the following meta data subject category should be existed in the system + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + + Scenario: Delete subject category after deleting the recorded meta-rule dependency + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + And the user sets to delete the following meta data subject category + | subjectmetadataname | + | Affiliation: | + Then the following meta data subject category should be existed in the system + | subjectmetadataname | subjectmetadatadescription | + | | | + + + Scenario: Add object category + When the user sets to add the following meta data object category + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + Then the following meta data object category should be existed in the system + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + + Scenario Outline: Add meta data object validations + When the user sets to add the following meta data object category + | objectmetadataname | objectmetadatadescription | + | <objectmetadataname> | <objectmetadatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectmetadataname | objectmetadatadescription | flag | + | | This meta data has the categorical information about an object | False | + | Clearance: | | True | + | 1 | This meta data has the categorical information about an object % | True | + | _%Clearance:%_ | This meta data has the categorical information about an object | True | + + Scenario: Add an existing meta data object + Given the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + When the user sets to add the following meta data object category + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + Then the system should reply the following + | flag | + | False | + + Scenario: Delete object category + Given the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object1 | + When the user sets to delete the following meta data object category + | objectmetadataname | + | Clearance: | + Then the following meta data object category should be existed in the system + | objectmetadataname | objectmetadatadescription | + | | | + + Scenario: Delete object category that has a recorded meta-rule dependency + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta data object category + | objectmetadataname | + | Clearance: | + Then the system should reply the following + | flag | + | False | + And the following meta data object category should be existed in the system + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + + Scenario: Delete object category after deleting the recorded meta-rule dependency + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + And the user sets to delete the following meta data object category + | objectmetadataname | + | Clearance: | + Then the following meta data object category should be existed in the system + | objectmetadataname | objectmetadatadescription | + | | | + + + Scenario: Add action category + When the user sets to add the following meta data action category + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + Then the following meta data action category should be existed in the system + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + + Scenario Outline: Add meta data action validations + When the user sets to add the following meta data action category + | actionmetadataname | actionmetadatadescription | + | <actionmetadataname> | <actionmetadatadescription> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionmetadataname | actionmetadatadescription | flag | + | | This meta data has the categorical information about the action | False | + | Action-Class: | | True | + | 1 | This meta data has the categorical information about the action% | True | + | _%Action-Class:%_ | This meta data has the categorical information about the action | True | + + Scenario: Add an existing meta data action + Given the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + When the user sets to add the following meta data action category + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + Then the system should reply the following + | flag | + | False | + + Scenario: Delete action category + Given the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + When the user sets to delete the following meta data action category + | actionmetadataname | + | Action-Class: | + Then the following meta data action category should be existed in the system + | actionmetadataname | actionmetadatadescription | + | | | + + Scenario: Delete action category that has a recorded meta-rule + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta data action category + | actionmetadataname | + | Action-Class: | + Then the system should reply the following + | flag | + | False | + And the following meta data action category should be existed in the system + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + + Scenario: Delete action Category after deleting the recorded meta-rule dependency + Given the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic meta rule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + And the user sets to delete the following meta data action category + | actionmetadataname | + | Action-Class: | + Then the following meta data action category should be existed in the system + | actionmetadataname | actionmetadatadescription | + | | | + diff --git a/moon_manager/tests/func_tests/features/meta_rules.feature b/moon_manager/tests/func_tests/features/meta_rules.feature new file mode 100644 index 00000000..2941d1f3 --- /dev/null +++ b/moon_manager/tests/func_tests/features/meta_rules.feature @@ -0,0 +1,234 @@ +Feature: Meta Rule + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + + + Scenario: Add meta rules + When the user sets to add the following meta-rule + | metarulename | subjectmetadata | actionmetadata | objectmetadata | metaruledescription | + | A-rule | Affiliation: | Action-Class: | Clearance: | AThisisabasicmetarule | + | Z-rule | Authorization-Level:,Affiliation: | Action-Priority:,Action-Class: | Type:,Clearance: | ZThisisabasicmetarule | + Then the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | A-rule | AThisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | Z-rule | ZThisisabasicmetarule | Authorization-Level:,Affiliation: | Action-Priority:,Action-Class: | Type:,Clearance: | + + Scenario Outline: Add meta-rule validations + When the user sets to add the following meta-rule + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | <metarulename> | <metaruledescription> | <subjectmetadata> | <actionmetadata> | <objectmetadata> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | flag | + | | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | False | + | metarule1 | | Affiliation: | Action-Class: | Clearance: | True | + | 1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | True | + | _%metarule%_ | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | True | + | metarule1 | Thisisabasicmetarule | | Action-Class: | Clearance: | True | + | metarule1 | Thisisabasicmetarule | 00000000000000000000000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | Thisisabasicmetarule | 0000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | Thisisabasicmetarule | 0000000000000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation:,,Authorization-Level: | Action-Class: | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | | Clearance: | True | + | metarule1 | Thisisabasicmetarule | Affiliation: | 00000000000000000000000000000000000000000 | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | 0000000000000000000000000000000000000000000000000000000000000000 | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | 0000000000000000000000000000000000000000000000000000000000000000000000000 | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class:,,Action-Priority: | Clearance: | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | | True | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 00000000000000000000000000000000000000000 | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 0000000000000000000000000000000000000000000000000000000000000000 | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 0000000000000000000000000000000000000000000000000000000000000000000000000 | False | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance:,,Type: | False | + + Scenario Outline: Add an existing meta-rule + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + When the user sets to add the following meta-rule + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | <metarulename> | <metaruledescription> | <subjectmetadata> | <actionmetadata> | <objectmetadata> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | flag | + | metarule1 | Thisisabasicmetarule | Service | Action-Priority: | Service | False | + | metarule2 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | False | + + Scenario: Update meta rules + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + When the user sets to update the following meta-rule + | metarulename | updatedmetarulename | updatedmetaruledescription | updatedsubjectmetadata | updatedactionmetadata | updatedobjectmetadata | + | metarule1 | 1-MR-% | Thisisabasicmetarule% | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + Then the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | 1-MR-% | Thisisabasicmetarule% | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + + Scenario Outline: Update meta rules validations + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + When the user sets to update the following meta-rule + | metarulename | updatedmetarulename | updatedmetaruledescription | updatedsubjectmetadata | updatedactionmetadata | updatedobjectmetadata | + | <metarulename> | <updatedmetarulename> | <updatedmetaruledescription> | <updatedsubjectmetadata> | <updatedactionmetadata> | <updatedobjectmetadata> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | metarulename | updatedmetarulename | updatedmetaruledescription | updatedsubjectmetadata | updatedactionmetadata | updatedobjectmetadata | flag | + | metarule1 | | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | False | + | metarule1 | metaruleX | | Affiliation: | Action-Class: | Clearance: | True | + | metarule1 | 1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | True | + | metarule1 | _%metarule%_ | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | True | +# | metarule1 | metarule1 | Thisisabasicmetarule | 0000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | 0000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | 0000000000000000000000000000000000000000000000000000000000000000000000000 | Action-Class: | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation:,,Authorization-Level: | Action-Class: | Clearance: | False | +# | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | 0000000000000000000000 | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | 0000000000000000000000000000000000000000000000000000000000000000 | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | 0000000000000000000000000000000000000000000000000000000000000000000000000 | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class:,,Action-Priority: | Clearance: | False | +# | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 0000000000000000000000 | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 0000000000000000000000000000000000000000000000000000000000000000 | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | 0000000000000000000000000000000000000000000000000000000000000000000000000 | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance:,,Type: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | | Action-Class: | Clearance: | True | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | | Clearance: | True | + | metarule1 | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | | True | + | metarule1 | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | False | + | metarule1 | metarule1 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | False | + + Scenario: Update a meta rule that has a recorded rule dependency + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford-Policy | Thisisabasicpolicy | universitymodel | Education | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford-Policy | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford-Policy | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford-Policy | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford-Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford-Policy | Clearance: | Top-Secret | This data has the value of object category | + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford-Policy | Action-Class: | Severe | This data has the value of action category | + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford-Policy | + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Top-Secret | Stanford-Policy | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford-Policy | + And the following rule exists + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Top-Secret,Severe | metarule1 | grant | Stanford-Policy | + When the user sets to update the following meta-rule + | metarulename | updatedmetarulename | updatedmetaruledescription | updatedsubjectmetadata | updatedactionmetadata | updatedobjectmetadata | + | metarule1 | metarule1 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + Then the system should reply the following + | flag | + | False | + And the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + + + Scenario: Delete meta rules + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + When the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + Then the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | | | | | | + + Scenario: Delete meta rules that has a recorded model dependency + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + And the following model exists + | modelname | modeldescription | metarule | + | generalmodel | Thisisabasicmodel | metarule1 | + When the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + Then the system should reply the following + | flag | + | False | + And the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + + Scenario: Delete meta rules after deleting the recorded model dependency + Given the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + And the following model exists + | modelname | modeldescription | metarule | + | generalmodel | Thisisabasicmodel | metarule1 | + When the user sets to delete the following model + | modelname | + | generalmodel | + And the user sets to delete the following meta-rule + | metarulename | + | metarule1 | + Then the following meta-rules should be existed in the system + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | | | | | |
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/model.feature b/moon_manager/tests/func_tests/features/model.feature new file mode 100644 index 00000000..1f6399ab --- /dev/null +++ b/moon_manager/tests/func_tests/features/model.feature @@ -0,0 +1,176 @@ +Feature: Model + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic metarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | This is a basic metarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | This is a basic metarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | This is a basic metarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | This is a basic metarule | Affiliation: | Action-Class: | Type: | + | metarule6 | This is a basic metarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | This is a basic metarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | This is a basic metarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + | metarule9 | This is a basic metarule | | Action-Class:,Action-Priority: | Clearance:,Type: | + | metarule10 | This is a basic metarule | Affiliation:,Authorization-Level: | | Clearance:,Type: | + | metarule11 | This is a basic metarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | | + + + Scenario: Add model + When the user sets to add the following model + | modelname | modeldescription | metarule | + | A-model | Thisisabasicmodel | metarule1,metarule2,metarule6 | + | B-model | Thisisabasicmodel | metarule3,metarule4,metarule5 | + Then the following model should be existed in the system + | modelname | modeldescription | metarule | + | A-model | Thisisabasicmodel | metarule1,metarule2,metarule6 | + | B-model | Thisisabasicmodel | metarule3,metarule4,metarule5 | + + Scenario Outline: Add model validations + When the user sets to add the following model + | modelname | modeldescription | metarule | + | <modelname> | <modeldescription> | <metarule> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | modelname | modeldescription | metarule | flag | + | | This model is for creating policy prototype | metarule8,metarule3 | False | + | generalmodel | | metarule8 | True | + | 1 | This model is for creating policy prototype% | metarule8 | True | + | _%model%_ | This model is for creating policy prototype1 | metarule8 | True | + | generalmodel | This model is for creating policy prototype | | True | + | generalmodel | This model is for creating policy prototype | metarule9 | True | + | generalmodel | This model is for creating policy prototype | metarule10 | True | + | generalmodel | This model is for creating policy prototype | metarule11 | True | + | generalmodel | This model is for creating policy prototype | metarule20 | False | + | generalmodel | This model is for creating policy prototype | metarule3,,metarule20 | False | + | generalmodel | This model is for creating policy prototype | 000000000000000000000 | False | + | generalmodel | This model is for creating policy prototype | 0000000000000000000000000000000000000000000000000000000000000000000 | False | + | generalmodel | This model is for creating policy prototype | 00000000000000000000000000000000000000000000000000000000000000000000000 | False | + | generalmodel | This model is for creating policy prototype | metarule8,metarule10 | True | + +Scenario Outline: Add an existing model + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This is a basic model | metarule1,metarule2,metarule6 | + When the user sets to add the following model + | modelname | modeldescription | metarule | + | <modelname> | <modeldescription> | <metarule> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | modelname | modeldescription | metarule | flag | + | generalmodel | Thisisabasicmodel | metarule1,metarule3,metarule5 | False | + | generalmodel1 | Thisisabasicmodel | metarule1,metarule2,metarule6 | False | + + Scenario: Update model + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | Thisisabasicmodel | metarule1,metarule2,metarule6 | + When the user sets to update the following model + | modelname | updatedmodelname | updatedmodeldescription | updatedmetarule | + | generalmodel | 1-M-% | This model is for creating policy prototype | metarule3,metarule5,metarule7 | + Then the following model should be existed in the system + | modelname | modeldescription | metarule | + | 1-M-% | This model is for creating policy prototype | metarule3,metarule5,metarule7 | + + Scenario Outline: Update model validations + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This model is for creating policy prototype | metarule1,metarule2,metarule6 | + When the user sets to update the following model + | modelname | updatedmodelname | updatedmodeldescription | updatedmetarule | + | <modelname> | <updatedmodelname> | <updatedmodeldescription> | <updatedmetarule> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | modelname | updatedmodelname | updatedmodeldescription | updatedmetarule | flag | + | generalmodel | | This model is for creating policy prototype | metarule8,metarule3 | False | + | generalmodel | generalmodel | | metarule8 | True | + | generalmodel | 1 | This model is for creating policy prototype% | metarule8 | True | + | generalmodel | _%model%_ | This model is for creating policy prototype1 | metarule8 | True | + | generalmodel | generalmodel | This model is for creating policy prototype | | True | + | generalmodel | generalmodel | This model is for creating policy prototype | metarule9 | True | + | generalmodel | generalmodel | This model is for creating policy prototype | metarule10 | True | + | generalmodel | generalmodel | This model is for creating policy prototype | metarule11 | True | + | generalmodel | generalmodel | This model is for creating policy prototype | metarule3, | False | + | generalmodel | generalmodel | This model is for creating policy prototype | 0000000000000000000000000000000000000000000000000000000000000000000 | False | + | generalmodel | generalmodel | This model is for creating policy prototype | 00000000000000000000000000000000000000000000000000000000000000000000000 | False | + | generalmodel | generalmodel | This model is for creating policy prototype | metarule8,metarule10 | True | + + Scenario: Delete a model + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This model is for creating policy prototype | metarule1 | + When the user sets to delete the following model + | modelname | + | generalmodel | + Then the following model should be existed in the system + | modelname | modeldescription | metarule | + | | | | + + Scenario: Delete a model that has a recorded policy dependency + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This model is for creating policy prototype | metarule1 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | generalpolicy | This is a basic policy | generalmodel | financial | + When the user sets to delete the following model + | modelname | + | generalmodel | + Then the following model should be existed in the system + | modelname | modeldescription | metarule | + | generalmodel | This model is for creating policy prototype | metarule1 | + + Scenario: Delete a model after deleting the recorded policy dependency + Given the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This model is for creating policy prototype | metarule1 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | generalpolicy | This is a basic policy | generalmodel | financial | + When the user sets to delete the following policy + | policyname | + | generalpolicy | + And the user sets to delete the following model + | modelname | + | generalmodel | + Then the following model should be existed in the system + | modelname | modeldescription | metarule | + | | | | diff --git a/moon_manager/tests/func_tests/features/partner.feature b/moon_manager/tests/func_tests/features/partner.feature new file mode 100644 index 00000000..ebce3393 --- /dev/null +++ b/moon_manager/tests/func_tests/features/partner.feature @@ -0,0 +1,7 @@ +Feature: Partner + + Scenario: Add Partner + + Scenario: Update Partner + + Scenario: Delete Partner
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/pdp.feature b/moon_manager/tests/func_tests/features/pdp.feature new file mode 100644 index 00000000..0ba73bac --- /dev/null +++ b/moon_manager/tests/func_tests/features/pdp.feature @@ -0,0 +1,141 @@ +Feature: PDP + + Background: + + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | generalmodel | Thisisabasicmodel | metarule1,metarule2,metarule6 | + | generalmodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Policy A | Thisisabasicpolicy | generalmodel | financial | + | Policy B | Thisisabasicpolicy | generalmodel2 | financial | + | Policy C | Thisisabasicpolicy | generalmodel2 | financial | + + + Scenario: Add PDP + When the user sets to add the following pdp + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | + | B-pdp | Thisisabasicpolicy | 1111111111111111111111111111111111111111111111111111111111111111 | Policy C | + + Then the following pdp should be existed in the system + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | + | B-pdp | Thisisabasicpolicy | 1111111111111111111111111111111111111111111111111111111111111111 | Policy C | + + Scenario Outline: Add PDP validations + When the user sets to add the following pdp + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | <pdpname> | <pdpdescription> | <keystone_project_id> | <security_pipeline> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | pdpname | pdpdescription | keystone_project_id | security_pipeline | flag | + | | This pdp is for creating a collection of policies | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | False | + | generalpdp | | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | True | + | 1 P | This pdp is for creating a collection of policies | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | True | + | _%Pdp%_ | This pdp is for creating a collection of policies% | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | True | + | generalpdp | This pdp is for creating a collection of policies% | | Policy A | False | + | generalpdp | This pdp is for creating a collection of policies | 0000000000000000000000000000000000000000000000000000000000000000 | | False | + | generalpdp | This pdp is for creating a collection of policies | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A, | False | + + Scenario Outline: Add an existing PDP + Given the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy C | + When the user sets to add the following pdp + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | <pdpname> | <pdpdescription> | <keystone_project_id> | <security_pipeline> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | pdpname | pdpdescription | keystone_project_id | security_pipeline | flag | + | B-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy C | False | + | A-pdp | Thisisabasicpolicy | 3333333333333333333333333333333333333333333333333333333333333333 | Policy A | False | + + Scenario: Update PDP + Given the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | + When the user sets to update the following pdp + | pdpname | updatedpdpname | updatedpdpdescription | updatedkeystone_project_id | updatedsecurity_pipeline | + | A-pdp | B-pdp | Thisisabasicpolicy | 111111111111111111111111111111111111111111111111111111111 | Policy B | + Then the following pdp should be existed in the system + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | B-pdp | Thisisabasicpolicy | 111111111111111111111111111111111111111111111111111111111 | Policy B | + + Scenario Outline: Update PDP validations + Given the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy B | + | B-pdp | Thisisabasicpolicy | 2222222222222222222222222222222222222222222222222222222222222222 | Policy C | + When the user sets to update the following pdp + | pdpname | updatedpdpname | updatedpdpdescription | updatedkeystone_project_id | updatedsecurity_pipeline | + | <pdpname> | <updatedpdpname> | <updatedpdpdescription> | <updatedkeystone_project_id> | <updatedsecurity_pipeline> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | pdpname | updatedpdpname | updatedpdpdescription | updatedkeystone_project_id | updatedsecurity_pipeline | flag | + | A-pdp | | Thispdpisforcreatingacollectionofpolicies | 111111111111111111111111111111111111111111111111111111111 | Policy A | False | + | A-pdp | generalpdp | | 111111111111111111111111111111111111111111111111111111111 | Policy A | True | + | A-pdp | 1 P | Thispdpisforcreatingacollectionofpolicies | 111111111111111111111111111111111111111111111111111111111 | Policy A | True | + | A-pdp | _%Pdp%_ | Thispdpisforcreatingacollectionofpolicies% | 111111111111111111111111111111111111111111111111111111111 | Policy A | True | + | A-pdp | generalpdp | Thispdpisforcreatingacollectionofpolicies% | | Policy A | False | + | A-pdp | generalpdp | Thispdpisforcreatingacollectionofpolicies | 111111111111111111111111111111111111111111111111111111111 | | False | + | A-pdp | generalpdp | Thispdpisforcreatingacollectionofpolicies | 111111111111111111111111111111111111111111111111111111111 | Policy A, | False | + | A-pdp | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy B | True | + | A-pdp | B-pdp | Thisisabasicpolicy | 111111111111111111111111111111111111111111111111111111111 | Policy C | False | + + Scenario: Delete PDP + Given the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | A-pdp | Thisisabasicpolicy | 0000000000000000000000000000000000000000000000000000000000000000 | Policy A | + When the user sets to delete the following pdp + | pdpname | + | A-pdp | + Then the following pdp should be existed in the system + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | | | | | diff --git a/moon_manager/tests/func_tests/features/perimeter.feature b/moon_manager/tests/func_tests/features/perimeter.feature new file mode 100644 index 00000000..39820e15 --- /dev/null +++ b/moon_manager/tests/func_tests/features/perimeter.feature @@ -0,0 +1,465 @@ +Feature: Perimeter + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1,metarule9 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel2 | Education | + + + Scenario: Add subject perimeter + When the user sets to add the following subject perimeter + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy | + Then the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy,Stanford Policy | + + Scenario Outline: Add subject perimeter validations + When the user sets to add the following subject perimeter + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | <subjectperimetername> | <subjectperimeterdescription> | <subjectperimeteremail> | <subjectperimeterpassword> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | flag | + | | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | False | + | _%JohnLewis%_ | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | True | + | JohnLewis | | jlewis@orange.com | abc1234 | Stanford Policy | True | + | JohnLewis | Thisistheexpecteduser% | jlewis@orange.com | abc1234 | Stanford Policy | True | + | JohnLewis | Thisistheexpecteduser% | jlewis@orange.com | abc1234 | | True | + + Scenario Outline: Add an existing subject perimeter + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + When the user sets to add the following subject perimeter + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | <subjectperimetername> | <subjectperimeterdescription> | <subjectperimeteremail> | <subjectperimeterpassword> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | flag | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | False | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy | True | + + Scenario: Update subject perimeter + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy | + When the user sets to update the following subject perimeter + | subjectperimetername | updatedsubjectperimetername | updatedsubjectperimeterdescription | updatedsubjectperimeteremail | updatedsubjectperimeterpassword | policies | + | JohnLewis | JoesephWilliams | Thisdatahasthevalueofsubjectperimeter | jwilliams@orange.com | abc1234 | Stanford Policy | + Then the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JoesephWilliams | Thisdatahasthevalueofsubjectperimeter | jwilliams@orange.com | abc1234 | Cambridge Policy,Stanford Policy | + + Scenario Outline: Update subject perimeter validations + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + When the user sets to update the following subject perimeter + | subjectperimetername | updatedsubjectperimetername | updatedsubjectperimeterdescription | updatedsubjectperimeteremail | updatedsubjectperimeterpassword | policies | + | <subjectperimetername> | <updatedsubjectperimetername> | <updatedsubjectperimeterdescription> | <updatedsubjectperimeteremail> | <updatedsubjectperimeterpassword> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | subjectperimetername | updatedsubjectperimetername | updatedsubjectperimeterdescription | updatedsubjectperimeteremail | updatedsubjectperimeterpassword | policies | flag | + #| JohnLewis | | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | False | + | JohnLewis | _%JohnLewis%_ | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | True | + #| JohnLewis | JohnLewis | | jlewis@orange.com | abc1234 | Stanford Policy | True | + #| JohnLewis | JohnLewis | Thisistheexpecteduser% | jlewis@orange.com | abc1234 | Stanford Policy | True | + +Scenario: Delete subject perimeter with a policy and no assignments + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + When the user sets to delete the following subject perimeter + | subjectperimetername | + | JohnLewis | + Then the system should reply the following + | flag | + | False | + And the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + + Scenario: Check subject perimeter after removing the policy + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + Then the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | | + +Scenario: Delete subject perimeter with no policy + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + And the user sets to delete the following subject perimeter + | subjectperimetername | + | JohnLewis | + Then the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | | | | | | + + Scenario: Delete subject perimeter with a policy and with assignments + Given the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | JohnLewis | Affiliation: | Stanford | Stanford Policy | + When the user sets to delete the following subject perimeter for a given policy + | subjectperimetername | policies | + | JohnLewis | Stanford Policy | + Then the system should reply the following + | flag | + | True | + And the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | | + And the following subject assignment should be existed in the system + | subjectperimetername | subjectcategory | subjectdata | policyname | + | | | | Stanford Policy | + + Scenario: Add object perimeter + When the user sets to add the following object perimeter + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy | + + Then the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy,Stanford Policy | + + Scenario Outline: Add object perimeter validations + When the user sets to add the following object perimeter + | objectperimetername | objectperimeterdescription | policies | + | <objectperimetername> | <objectperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectperimetername | objectperimeterdescription | policies | flag | + | | Thisistherequesttoaccessfile | Stanford Policy | False | + | _%ProfessorsPromotionDocument%_ | Thisistherequesttoaccessfile | Stanford Policy | True | + | ProfessorsPromotionDocument | | Stanford Policy | True | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile% | Stanford Policy | True | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile% | | True | + + + Scenario Outline: Add an existing object perimeter + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + When the user sets to add the following object perimeter + | objectperimetername | objectperimeterdescription | policies | + | <objectperimetername> | <objectperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectperimetername | objectperimeterdescription | policies | flag | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | False | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy | True | + + Scenario: Update object perimeter + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy | + When the user sets to update the following object perimeter + | objectperimetername | updatedobjectperimetername | updatedobjectperimeterdescription | policies | + | ProfessorsPromotionDocument | StudentsGradsSheet | Thisistherequesttoaccessfile | Stanford Policy | + Then the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | StudentsGradsSheet | Thisistherequesttoaccessfile | Cambridge Policy,Stanford Policy | + + Scenario Outline: Update object perimeter validations + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + When the user sets to update the following object perimeter + | objectperimetername | updatedobjectperimetername | updatedobjectperimeterdescription | policies | + | <objectperimetername> | <updatedobjectperimetername> | <updatedobjectperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | objectperimetername | updatedobjectperimetername | updatedobjectperimeterdescription | policies | flag | + | ProfessorsPromotionDocument | | Thisistherequesttoaccessfile | Stanford Policy | False | + | ProfessorsPromotionDocument | _%ProfessorsPromotionDocument%_ | Thisistherequesttoaccessfile | Stanford Policy | True | + | ProfessorsPromotionDocument | ProfessorsPromotionDocument | | Stanford Policy | True | + | ProfessorsPromotionDocument | ProfessorsPromotionDocument | Thisistherequesttoaccessfile% | Stanford Policy | True | + + Scenario: Delete object perimeter with a policy + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + When the user sets to delete the following object perimeter + | objectperimetername | + | ProfessorsPromotionDocument | + Then the system should reply the following + | flag | + | False | + And the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + + Scenario: Check object perimeter after removing the policy + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + When the user sets to delete the following object perimeter for a given policy + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + Then the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | | + + Scenario: Delete object perimeter after removing the policy + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + When the user sets to delete the following object perimeter for a given policy + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + And the user sets to delete the following object perimeter + | objectperimetername | + | ProfessorsPromotionDocument | + Then the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | | | | + + Scenario: Delete object perimeter with a policy and with assignments + Given the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Stanford Policy | Type: | Adminstrative | This data has the value of object category | + | Stanford Policy | Type: | Staff | This data has the value of object category | + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | ProfessorsPromotionDocument | Clearance: | Public | Stanford Policy | + | ProfessorsPromotionDocument | Clearance: | Confidential | Stanford Policy | + When the user sets to delete the following object perimeter for a given policy + | objectperimetername | policies | + | ProfessorsPromotionDocument | Stanford Policy | + Then the system should reply the following + | flag | + | True | + And the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | | + And the following object assignment should be existed in the system + | objectperimetername | objectcategory | objectdata | policyname | + | | | | Stanford Policy | + + + Scenario: Add action perimeter + When the user sets to add the following action perimeter + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Read | Thisistheactionrequired | Cambridge Policy | + | Delete | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Cambridge Policy | + Then the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Delete | Thisistheactionrequired | Cambridge Policy,Stanford Policy | + | Read | Thisistheactionrequired | Cambridge Policy,Stanford Policy | + + Scenario Outline: Add action perimeter validations + When the user sets to add the following action perimeter + | actionperimetername | actionperimeterdescription | policies | + | <actionperimetername> | <actionperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionperimetername | actionperimeterdescription | policies | flag | + | | Thisistheactionrequired | Stanford Policy | False | + | _%Read%_ | Thisistheactionrequired | Stanford Policy | True | + | Read | | Stanford Policy | True | + | Read | Thisistheactionrequired% | Stanford Policy | True | + | Read | Thisistheactionrequired% | | True | + + + Scenario Outline: Add an existing action perimeter + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + When the user sets to add the following action perimeter + | actionperimetername | actionperimeterdescription | policies | + | <actionperimetername> | <actionperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionperimetername | actionperimeterdescription | policies | flag | + | Read | Thisistheactionrequired | Stanford Policy | False | + | Read | Thisistheactionrequired | Cambridge Policy | True | + + Scenario: Update action perimeter + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Read | Thisistheactionrequired | Cambridge Policy | + When the user sets to update the following action perimeter + | actionperimetername | updatedactionperimetername | updatedactionperimeterdescription | policies | + | Read | Delete | Thisistheactionrequired | Stanford Policy | + Then the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Delete | Thisistheactionrequired | Cambridge Policy,Stanford Policy | + + Scenario Outline: Update action perimeter validations + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + When the user sets to update the following action perimeter + | actionperimetername | updatedactionperimetername | updatedactionperimeterdescription | policies | + | <actionperimetername> | <updatedactionperimetername> | <updatedactionperimeterdescription> | <policies> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | actionperimetername | updatedactionperimetername | updatedactionperimeterdescription | policies | flag | + | Read | | Thisistheactionrequired | Stanford Policy | False | + | Read | _%Read%_ | Thisistheactionrequired | Stanford Policy | True | + | Read | Read | | Stanford Policy | True | + | Read | Read | Thisistheactionrequired% | Stanford Policy | True | + + Scenario: Delete action perimeter with a policy + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | This is the action required | Stanford Policy | + When the user sets to delete the following action perimeter + | actionperimetername | + | Read | + Then the system should reply the following + | flag | + | False | + And the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Read | This is the action required | Stanford Policy | + + Scenario: Check action perimeter after removing the policy + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + When the user sets to delete the following action perimeter for a given policy + | actionperimetername | policies | + | Read | Stanford Policy | + Then the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | | + + Scenario: Delete action perimeter after removing the policy + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + When the user sets to delete the following action perimeter for a given policy + | actionperimetername | policies | + | Read | Stanford Policy | + And the user sets to delete the following action perimeter + | actionperimetername | + | Read | + Then the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | | | | + + Scenario: Delete action perimeter with a policy and with assignments + Given the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Stanford Policy | Action-Priority: | Low | This data has the value of action category | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + | Read | Action-Class: | Low | Stanford Policy | + When the user sets to delete the following action perimeter for a given policy + | actionperimetername | policies | + | Read | Stanford Policy | + Then the system should reply the following + | flag | + | True | + And the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | | + And the following action assignment should be existed in the system + | actionperimetername | actioncategory | actiondata | policyname | + | | | | Stanford Policy | + + diff --git a/moon_manager/tests/func_tests/features/policy.feature b/moon_manager/tests/func_tests/features/policy.feature new file mode 100644 index 00000000..e8d4077d --- /dev/null +++ b/moon_manager/tests/func_tests/features/policy.feature @@ -0,0 +1,245 @@ +Feature: Policy + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | This is a basic metarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | This is a basic metarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | This is a basic metarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | This is a basic metarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | This is a basic metarule | Affiliation: | Action-Class: | Type: | + | metarule6 | This is a basic metarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | This is a basic metarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | This is a basic metarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | This is a basic metarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | generalmodel | This is a basic model | metarule9 | + | generalmodel2 | This is a basic model | metarule3,metarule5,metarule8 | + | generalmodel3 | This is a basic model | metarule9 | + + Scenario: Add policy + When the user sets to add the following policy + | policyname | policydescription | modelname | genre | + | A policy | This is a basic policy | generalmodel | financial | + | B policy | This is a basic policy | generalmodel | administrative | + Then the following policy should be existed in the system + | policyname | policydescription | modelname | genre | + | A policy | This is a basic policy | generalmodel | financial | + | B policy | This is a basic policy | generalmodel | administrative | + + Scenario Outline: Add policy validations + When the user sets to add the following policy + | policyname | policydescription | modelname | genre | + | <policyname> | <policydescription> | <modelname> | <genre> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | policydescription | modelname | genre | flag | + | | This is a basic policy | generalmodel | financial | False | + | generalpolicy | | generalmodel | financial | True | + | generalpolicy | This is a basic policy | | financial | False | + | generalpolicy | This is a basic policy | 0000000000000000000000 | financial | False | + | generalpolicy | This is a basic policy | 0000000000000000000000000000000000000000000000000000000000000000 | financial | False | + | generalpolicy | This is a basic policy | 00000000000000000000000000000000000000000000000000000000000000000000 | financial | False | + | generalpolicy | This is a basic policy | generalmodel | | True | + | 1 | This is a basic policy | generalmodel | financial | True | + | _%policy%_ | This is a basic policy | generalmodel | financial | True | + | policy | This is a basic policy % | generalmodel | 1 | True | + | policy | This is a basic policy % | generalmodel2 | 1 | True | + | policy | This is a basic policy % | generalmodel | _%genere%_ | True | + + Scenario Outline: Add an existing policy + Given the following policy exists + | policyname | policydescription | modelname | genre | + | generalpolicy | This is a basic policy | generalmodel | financial | + When the user sets to add the following policy + | policyname | policydescription | modelname | genre | + | <policyname> | <policydescription> | <modelname> | <genre> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | policydescription | modelname | genre | flag | + | generalpolicy | This is a basic policy | generalmodel2 | financial | False | + | generalpolicy2 | This is a basic policy | generalmodel | financial | True | + + Scenario: Update policy + Given the following policy exists + | policyname | policydescription | modelname | genre | + | generalpolicy | This is a basic policy | generalmodel | financial | + When the user sets to update the following policy + | policyname | updatedpolicyname | updatedpolicydescription | updatedmodelname | updatedgenre | + | generalpolicy | 1 P % | This is a basic policy | generalmodel | financial | + Then the following policy should be existed in the system + | policyname | policydescription | modelname | genre | + | 1 P % | This is a basic policy | generalmodel | financial | + + Scenario Outline: Update policy validations + Given the following policy exists + | policyname | policydescription | modelname | genre | + | mainpolicy | This is a basic policy | generalmodel | adminstrative | + | mainpolicy2 | This is a basic policy | generalmodel | adminstrative | + When the user sets to update the following policy + | policyname | updatedpolicyname | updatedpolicydescription | updatedmodelname | updatedgenre | + | <policyname> | <updatedpolicyname> | <updatedpolicydescription> | <updatedmodelname> | <updatedgenre> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | policyname | updatedpolicyname | updatedpolicydescription | updatedmodelname | updatedgenre | flag | + | mainpolicy | | This is a basic policy | generalmodel | financial | False | + | mainpolicy | generalpolicy | | generalmodel | financial | True | + | mainpolicy | generalpolicy | This is a basic policy | | financial | False | + | mainpolicy | generalpolicy | This is a basic policy | 0000000000000000000000 | financial | False | + | mainpolicy | generalpolicy | This is a basic policy | 0000000000000000000000000000000000000000000000000000000000000000 | financial | False | + | mainpolicy | generalpolicy | This is a basic policy | 00000000000000000000000000000000000000000000000000000000000000000000 | financial | False | + | mainpolicy | generalpolicy | This is a basic policy | generalmodel | | True | + | mainpolicy | 1 | This is a basic policy | generalmodel | financial | True | + | mainpolicy | _%policy%_ | This is a basic policy | generalmodel | financial | True | + | mainpolicy | policy | This is a basic policy % | generalmodel | financial | True | + | mainpolicy | policy | This is a basic policy % | generalmodel | 1 | True | + | mainpolicy | policy | This is a basic policy % | generalmodel2 | 1 | False | + | mainpolicy | policy | This is a basic policy % | generalmodel | _%genere%_ | True | + | mainpolicy | mainpolicy | This is a basic policy % | generalmodel | adminstrative | True | + | mainpolicy | mainpolicy2 | This is a basic policy % | generalmodel | adminstrative | False | + + Scenario: Delete policy + Given the following policy exists + | policyname | policydescription | modelname | genre | + | generalpolicy | This is a basic policy | generalmodel | financial | + When the user sets to delete the following policy + | policyname | + | generalpolicy | + Then the following policy should be existed in the system + | policyname | policydescription | modelname | genre | + | | | | | + + + Scenario: Delete a policy that has a system attributes dependency + Given the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | generalmodel | financial | + | Cambridge Policy | This is a basic policy | generalmodel2 | Education | + And the following pdp exists + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | generalpdp | This is a basic pdp | 0000000000000000000000000000000000000000000000000000000000000000 | Stanford Policy | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Stanford Policy | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Stanford Policy | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Delete | Thisistheactionrequired | Stanford Policy | + | Read | Thisistheactionrequired | Stanford Policy | + | Read | Thisistheactionrequired | Cambridge Policy | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + | Stanford Policy | Authorization-Level: | Professor | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Stanford Policy | Type: | Adminstrative | This data has the value of object category | + | Stanford Policy | Type: | Staff | This data has the value of object category | + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Stanford Policy | Action-Priority: | Low | This data has the value of action category | + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | Stanford | Stanford Policy | + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | StudentsGradesSheet | Clearance: | Public | Stanford Policy | + | StudentsGradesSheet | Clearance: | Top-Secret | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + | Read | Action-Class: | Low | Stanford Policy | + | Read | Action-Priority: | Low | Stanford Policy | + When the user sets to delete the following policy + | policyname | + | Stanford Policy | + Then the following policy should be existed in the system + | policyname | policydescription | modelname | genre | + | Cambridge Policy | This is a basic policy | generalmodel2 | Education | + And the following pdp should be existed in the system + | pdpname | pdpdescription | keystone_project_id | security_pipeline | + | generalpdp | This is a basic pdp | 0000000000000000000000000000000000000000000000000000000000000000 | | + And the following subject perimeter should be existed in the system + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Cambridge Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | | + And the following object perimeter should be existed in the system + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Cambridge Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | | + And the following action perimeter should be existed in the system + | actionperimetername | actionperimeterdescription | policies | + | Delete | Thisistheactionrequired | | + | Read | Thisistheactionrequired | Cambridge Policy | + And the following subject data should be existed in the system + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | | | | | + And the following object data should be existed in the system + | policyname | objectcategory | objectdataname | objectdatadescription | + | | | | | + And the following action data should be existed in the system + | policyname | actioncategory | actiondataname | actiondatadescription | + | | | | | + And the following subject assignment should be existed in the system + | subjectperimetername | subjectcategory | subjectdata | policyname | + | | | | | + And the following object assignment should be existed in the system + | objectperimetername | objectcategory | objectdata | policyname | + | | | | | + And the following action assignment should be existed in the system + | actionperimetername | actioncategory | actiondata | policyname | + | | | | | + diff --git a/moon_manager/tests/func_tests/features/rules.feature b/moon_manager/tests/func_tests/features/rules.feature new file mode 100644 index 00000000..e98e2b30 --- /dev/null +++ b/moon_manager/tests/func_tests/features/rules.feature @@ -0,0 +1,188 @@ +Feature: Rules + + Background: + Given the system has no rules + And the system has no subject assignments + And the system has no action assignments + And the system has no object assignments + And the system has no subject data + And the system has no action data + And the system has no object data + And the system has no subject perimeter + And the system has no object perimeter + And the system has no action perimeter + And the system has no pdps + And the system has no policies + And the system has no models + And the system has no meta-rules + And the system has no subject categories + And the system has no action categories + And the system has no object categories + And the following meta data subject category exists + | subjectmetadataname | subjectmetadatadescription | + | Affiliation: | This meta data has the categorical information about a subject | + | Authorization-Level: | This meta data has the categorical information about an object | + | Degree: | This meta data has the categorical information about an object | + And the following meta data object category exists + | objectmetadataname | objectmetadatadescription | + | Clearance: | This meta data has the categorical information about an object | + | Type: | This meta data has the categorical information about an object | + | Class: | This meta data has the categorical information about an object | + And the following meta data action category exists + | actionmetadataname | actionmetadatadescription | + | Action-Class: | This meta data has the categorical information about an action | + | Action-Priority: | This meta data has the categorical information about an action | + | Recommendation: | This meta data has the categorical information about an action | + And the following meta rule exists + | metarulename | metaruledescription | subjectmetadata | actionmetadata | objectmetadata | + | metarule1 | Thisisabasicmetarule | Affiliation: | Action-Class: | Clearance: | + | metarule2 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Clearance: | + | metarule3 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Clearance: | + | metarule4 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Clearance: | + | metarule5 | Thisisabasicmetarule | Affiliation: | Action-Class: | Type: | + | metarule6 | Thisisabasicmetarule | Authorization-Level: | Action-Class: | Type: | + | metarule7 | Thisisabasicmetarule | Affiliation: | Action-Priority: | Type: | + | metarule8 | Thisisabasicmetarule | Authorization-Level: | Action-Priority: | Type: | + | metarule9 | Thisisabasicmetarule | Affiliation:,Authorization-Level: | Action-Class:,Action-Priority: | Clearance:,Type: | + And the following model exists + | modelname | modeldescription | metarule | + | universitymodel | Thisisabasicmodel | metarule1,metarule9 | + | universitymodel2 | Thisisabasicmodel | metarule3,metarule5,metarule8 | + | universitymodel3 | Thisisabasicmodel | metarule9 | + And the following policy exists + | policyname | policydescription | modelname | genre | + | Stanford Policy | This is a basic policy | universitymodel | Education | + | Cambridge Policy | This is a basic policy | universitymodel3 | Education | + And the following subject perimeter exists + | subjectperimetername | subjectperimeterdescription | subjectperimeteremail | subjectperimeterpassword | policies | + | JohnLewis | Thisistheexpecteduser | jlewis@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Stanford Policy | + | WilliamsJoeseph | Thisistheexpecteduser | wjoeseph@orange.com | abc1234 | Cambridge Policy | + | WilliamsGeorge | Thisdatahasthevalueofsubjectperimeter | gwilliams@orange.com | abc1234 | | + And the following object perimeter exists + | objectperimetername | objectperimeterdescription | policies | + | ProfessorsPromotionDocument | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Stanford Policy | + | StudentsGradesSheet | Thisistherequesttoaccessfile | Cambridge Policy | + | Vacations | Thisistherequesttoaccessfile | | + And the following action perimeter exists + | actionperimetername | actionperimeterdescription | policies | + | Read | Thisistheactionrequired | Stanford Policy | + | Delete | Thisistheactionrequired | Stanford Policy | + | Edit | Thisistheactionrequired | | + And the following subject data exists + | policyname | subjectcategory | subjectdataname | subjectdatadescription | + | Stanford Policy | Affiliation: | University-of-Stanford | This data has the value of subject category | + | Stanford Policy | Affiliation: | Stanford | This data has the value of subject category | + | Cambridge Policy | Affiliation: | University-of-Cambridge | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Professor | This data has the value of subject category | + | Cambridge Policy | Authorization-Level: | Lecturer | This data has the value of subject category | + And the following object data exists + | policyname | objectcategory | objectdataname | objectdatadescription | + | Stanford Policy | Clearance: | Top-Secret | This data has the value of object category | + | Stanford Policy | Clearance: | Confidential | This data has the value of object category | + | Stanford Policy | Clearance: | Public | This data has the value of object category | + | Cambridge Policy | Type: | Adminstrative | This data has the value of object category | + | Cambridge Policy | Type: | Teaching-Staff | This data has the value of object category | + | Cambridge Policy | Clearance: | Confidential | This data has the value of object category | + | Cambridge Policy | Clearance: | Access-with-permission | This data has the value of object category | + | Cambridge Policy | Clearance: | Public | This data has the value of object category | + + And the following action data exists + | policyname | actioncategory | actiondataname | actiondatadescription | + | Stanford Policy | Action-Class: | Severe | This data has the value of action category | + | Stanford Policy | Action-Class: | Low | This data has the value of action category | + | Cambridge Policy | Action-Priority: | High | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Medium | This data has the value of action category | + | Cambridge Policy | Action-Priority: | Low | This data has the value of action category | + | Cambridge Policy | Action-Class: | Severe | This data has the value of action category | + | Cambridge Policy | Action-Class: | Intermediate | This data has the value of action category | + | Cambridge Policy | Action-Class: | Low | This data has the value of action category | + + And the following subject assignment exists + | subjectperimetername | subjectcategory | subjectdata | policyname | + | JohnLewis | Affiliation: | University-of-Stanford | Stanford Policy | + | WilliamsJoeseph | Affiliation: | Stanford | Stanford Policy | + + And the following object assignment exists + | objectperimetername | objectcategory | objectdata | policyname | + | StudentsGradesSheet | Clearance: | Access-with-permission | Cambridge Policy | + | StudentsGradesSheet | Clearance: | Public | Cambridge Policy | + #| StudentsGradesSheet | Clearance: | Top-Secret | Stanford Policy | + | StudentsGradesSheet | Clearance: | Confidential | Stanford Policy | + #| StudentsGradesSheet | Clearance: | Public | Stanford Policy | + And the following action assignment exists + | actionperimetername | actioncategory | actiondata | policyname | + | Read | Action-Class: | Severe | Stanford Policy | + #| Read | Action-Class: | Low | Stanford Policy | + | Delete | Action-Priority: | High | Cambridge Policy | + | Delete | Action-Priority: | Medium | Cambridge Policy | + | Delete | Action-Priority: | Low | Cambridge Policy | + + Scenario: Add rule + When the user sets to add the following rules + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + | University-of-Cambridge,Professor,Public,Adminstrative,Low,Low | metarule9 | grant | Cambridge Policy | + Then the following rules should be existed in the system + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + | University-of-Cambridge,Professor,Public,Adminstrative,Low,Low | metarule9 | grant | Cambridge Policy | + +Scenario Outline: Add rules validations + When the user sets to add the following rules + | rule | metarulename | instructions | policyname | + | <rule> | <metarulename> | <instructions> | <policyname> | + Then the system should reply the following + | flag | + | <flag> | + Examples: + | rule | metarulename | instructions | policyname | flag | + | | metarule1 | grant | Stanford Policy | False | + | Confidential,Severe | metarule1 | grant | Stanford Policy | False | + | ,Confidential,Severe | metarule1 | grant | Stanford Policy | False | + | 0000000000000000000000000000000000000000,Confidential,Severe | metarule1 | grant | Stanford Policy | False | + | University of USA,Confidential,Severe | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,,Confidential,Severe | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,,Confidential | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Superficial,Severe | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,0000000000000000000000000000000000000000,Severe | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,,Severe | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential, | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Non-Accessable | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,0000000000000000000000000000000000000000 | metarule1 | grant | Stanford Policy | False | + #| University-of-Stanford,Confidential,Severe, | metarule1 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Severe | | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Severe | metarule9 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Severe | 000000000000000000000000000000000000000000000000000 | grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Severe | metarule1 | not grant | Stanford Policy | False | + | University-of-Stanford,Confidential,Severe | metarule1 | | Stanford Policy | True | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | | False | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | 000000000000000000000000000000000000000000000000000 | False | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Cambridge Policy | False | + + + Scenario: Add existing rule + Given the following rule exists + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + When the user sets to add the following rules + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + Then the system should reply the following + | flag | + | False | + + + Scenario: Delete rule + Given the following rule exists + | rule | metarulename | instructions | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | grant | Stanford Policy | + When the user sets to delete the following rules + | rule | metarulename | policyname | + | University-of-Stanford,Confidential,Severe | metarule1 | Stanford Policy | + Then the system should reply the following + | flag | + | True | + + diff --git a/moon_manager/tests/func_tests/features/steps/Static_Variables.py b/moon_manager/tests/func_tests/features/steps/Static_Variables.py new file mode 100644 index 00000000..471f92fa --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/Static_Variables.py @@ -0,0 +1,89 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +class GeneralVariables: + serverURL="http://127.0.0.1:8000/" + + serverIP="10.237.71.141" + + serverport = "22" + + serverusername="ubuntu" + + serverpassword="ubuntu-007" + + token = "{{TOKEN}}" + + auth_headers = {"X-Api-Key": token} + + actual_authresponse = {'value': False} + + api_responseflag = {'value': False} + + pipelinePort = {'value': ""} + + wrapperPort = {'value': ""} + + projectAPI = "" + + slaveAPI="slave" + + getslavesAPI = "slaves" + + pdpAPI = "pdp" + + modelAPI = "models" + + policyAPI = "policies" + + assignpolicyid={'value': ""} + + assignsubjectperimeterid = {'value': ""} + + assignsubjectcategoryid = {'value': ""} + + assignobjectperimeterid = {'value': ""} + + assignobjectcategoryid = {'value': ""} + + assignactionperimeterid = {'value': ""} + + assignactioncategoryid = {'value': ""} + + metarulesAPI = "meta_rules" + + metadatasubjectcategoryAPI = "subject_categories" + + metadataobjectcategoryAPI = "object_categories" + + metadataactioncategoryAPI = "action_categories" + + perimetersubjectAPI = "subjects" + + perimeterobjectAPI = "objects" + + perimeteractionAPI = "actions" + + datasubjectAPI = "subject_data" + + dataobjectAPI = "object_data" + + dataactionAPI = "action_data" + + assignementssubjectAPI = "subject_assignments" + + assignementsobjectAPI = "object_assignments" + + assignementsactionAPI = "action_assignments" + + rulesAPI = "rules" + diff --git a/moon_manager/tests/func_tests/features/steps/__init__.py b/moon_manager/tests/func_tests/features/steps/__init__.py new file mode 100644 index 00000000..582be686 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/__init__.py @@ -0,0 +1,11 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + diff --git a/moon_manager/tests/func_tests/features/steps/assignments.py b/moon_manager/tests/func_tests/features/steps/assignments.py new file mode 100644 index 00000000..e3f7b5a7 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/assignments.py @@ -0,0 +1,858 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing subject meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get subject assignment id using both the policy id, data id & the category id +# 3) Loop by assignment id and delete it +@Given('the system has no subject assignments') +def step_impl(context): + logger.info("Given the system has no subject assignments") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + # subjectcategoryidslist = [] + # subjectdataidslist = [] + # modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + # if (modelid != None and modelid != ""): + # metaruleslist = \ + # requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers).json()[apis_urls.modelAPI][modelid]['meta_rules'] + # for metarule_ids in metaruleslist: + # categorieslist = \ + # requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, + # headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + # metarule_ids]['subject_categories'] + # for categoryid in categorieslist: + # if (categoryid not in subjectcategoryidslist): + # subjectcategoryidslist.append(categoryid) + # + # response_perimeters = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI, + # headers=apis_urls.auth_headers).json()[ + # apis_urls.perimetersubjectAPI] + # for perimeterid in dict(response_perimeters).keys(): + # for categoryid in subjectcategoryidslist: + # response_assignment = requests.get( + # apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementssubjectAPI + "/" + + # perimeterid + "/" + categoryid, headers=apis_urls.auth_headers) + # if len(response_assignment.json()[apis_urls.assignementssubjectAPI]) != 0: + # for ids in dict(response_assignment.json()[apis_urls.assignementssubjectAPI]).keys(): + # assignmentsid = response_assignment.json()[apis_urls.assignementssubjectAPI][str(ids)][ + # 'assignments'] + # for dataid in assignmentsid: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementssubjectAPI , headers=headers) + +# Step Definition Implementation: +# 1) Get all the existing object meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get object assignment id using both the policy id, data id & the category id +# 3) Loop by assignment id and delete it +@Given('the system has no object assignments') +def step_impl(context): + logger.info("Given the system has no object assignments") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + # objectcategoryidslist = [] + # objectdataidslist = [] + # modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + # if (modelid != None and modelid != ""): + # metaruleslist = \ + # requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers).json()[ + # apis_urls.modelAPI][modelid][ + # 'meta_rules'] + # for metarule_ids in metaruleslist: + # categorieslist = \ + # requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, + # headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + # metarule_ids]['object_categories'] + # for categoryid in categorieslist: + # if (categoryid not in objectcategoryidslist): + # objectcategoryidslist.append(categoryid) + # + # response_perimeters = \ + # requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI, + # headers=apis_urls.auth_headers).json()[ + # apis_urls.perimeterobjectAPI] + # for perimeterid in dict(response_perimeters).keys(): + # for categoryid in objectcategoryidslist: + # response_assignment = requests.get( + # apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementsobjectAPI + "/" + + # perimeterid + "/" + categoryid, headers=apis_urls.auth_headers) + # if len(response_assignment.json()[apis_urls.assignementsobjectAPI]) != 0: + # for ids in dict(response_assignment.json()[apis_urls.assignementsobjectAPI]).keys(): + # assignmentsid = response_assignment.json()[apis_urls.assignementsobjectAPI][str(ids)][ + # 'assignments'] + # for dataid in assignmentsid: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementsobjectAPI , headers=headers) + +# Step Definition Implementation: +# 1) Get all the existing action meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get action assignment id using both the policy id, data id & the category id +# 3) Loop by assignment id and delete it +@Given('the system has no action assignments') +def step_impl(context): + logger.info("Given the system has no action assignments") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + # actioncategoryidslist = [] + # actiondataidslist = [] + # modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + # if (modelid != None and modelid != ""): + # metaruleslist = \ + # requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers).json()[ + # apis_urls.modelAPI][modelid][ + # 'meta_rules'] + # for metarule_ids in metaruleslist: + # categorieslist = \ + # requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, + # headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + # metarule_ids]['action_categories'] + # for categoryid in categorieslist: + # if (categoryid not in actioncategoryidslist): + # actioncategoryidslist.append(categoryid) + # + # response_perimeters = \ + # requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI, + # headers=apis_urls.auth_headers).json()[ + # apis_urls.perimeteractionAPI] + # for perimeterid in dict(response_perimeters).keys(): + # for categoryid in actioncategoryidslist: + # response_assignment = requests.get( + # apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementsactionAPI + "/" + + # perimeterid + "/" + categoryid, headers=apis_urls.auth_headers) + # if len(response_assignment.json()[apis_urls.assignementsactionAPI]) != 0: + # for ids in dict(response_assignment.json()[apis_urls.assignementsactionAPI]).keys(): + # assignmentsid = response_assignment.json()[apis_urls.assignementsactionAPI][str(ids)][ + # 'assignments'] + # for dataid in assignmentsid: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.assignementsactionAPI , headers=headers) + +# Step Definition Implementation: +# 1) Post subject assignment using the policy id, subject perimeter id, subject category, list of subject data ids +@Given('the following subject assignment exists') +def step_impl(context): + logger.info("Given the following subject assignment exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject data: '" + row[ + "subjectdata"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataname = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_subjectperimeterid(row['subjectperimetername']) + categories_id = commonfunctions.get_subjectcategoryid(row['subjectcategory']) + dataids = commonfunctions.get_subjectdataid(row['subjectdata'], categories_id, policies_id) + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementssubjectAPI, + headers=headers, data=json.dumps(data)) + + GeneralVariables.assignpolicyid['value'] = policies_id + GeneralVariables.assignsubjectperimeterid['value'] = perimeter_id + GeneralVariables.assignsubjectcategoryid['value'] = categories_id + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Post object assignment using the policy id, object perimeter id, object category, list of object data ids +@Given('the following object assignment exists') +def step_impl(context): + logger.info("Given the following object assignment exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row["objectperimetername"] + "' object data: '" + row[ + "objectdata"] + "' and object category: '" + row[ + "objectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataname = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_objectperimeterid(row['objectperimetername']) + categories_id = commonfunctions.get_objectcategoryid(row['objectcategory']) + dataids = commonfunctions.get_objectdataid(row['objectdata'], categories_id, policies_id) + + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'policy_id': policies_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementsobjectAPI, + headers=headers, data=json.dumps(data)) + + GeneralVariables.assignpolicyid['value'] = policies_id + GeneralVariables.assignobjectperimeterid['value'] = perimeter_id + GeneralVariables.assignobjectcategoryid['value'] = categories_id + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Post action assignment using the policy id, action perimeter id, action category, list of action data ids +@Given('the following action assignment exists') +def step_impl(context): + logger.info("Given the following action assignment exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action perimeter name: '" + row["actionperimetername"] + "' action data: '" + row[ + "actiondata"] + "' and action category: '" + row[ + "actioncategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataname = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_actionperimeterid(row['actionperimetername']) + categories_id = commonfunctions.get_actioncategoryid(row['actioncategory']) + dataids = commonfunctions.get_actiondataid(row['actiondata'], categories_id, policies_id) + + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'policy_id': policies_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementsactionAPI, + headers=headers, data=json.dumps(data)) + + GeneralVariables.assignpolicyid['value'] = policies_id + GeneralVariables.assignactionperimeterid['value'] = perimeter_id + GeneralVariables.assignactioncategoryid['value'] = categories_id + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Post action assignment using the policy id, action perimeter id, action category, list of action data ids +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following subject assignment') +def step_impl(context): + logger.info("When the user sets to add the following subject assignment") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject data: '" + row[ + "subjectdata"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataids = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policyname'] == "" or row['policyname'] == "000000000000000000000000000000000000000000000000000"): + policyname = "Stanford Policy" + else: + policyname = row['policyname'] + policies_id = commonfunctions.get_policyid(policyname) + + if (row["subjectperimetername"] == "" or row[ + "subjectperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimetername = "WilliamsJoeseph" + else: + perimetername = row["subjectperimetername"] + perimeter_id = commonfunctions.get_subjectperimeterid(perimetername) + + if (row["subjectcategory"] == "" or row[ + "subjectcategory"] == "000000000000000000000000000000000000000000000000000"): + categoriesname = "Affiliation:" + else: + categoriesname = row['subjectcategory'] + categories_id = commonfunctions.get_subjectcategoryid(categoriesname) + + if (row["subjectdata"] == "" or row["subjectdata"] == "000000000000000000000000000000000000000000000000000"): + dataids = "Professor" + else: + dataids = row['subjectdata'] + dataids = commonfunctions.get_subjectdataid(dataids, categories_id, policies_id) + + if (dataids == None): + dataids = "" + + if (row["policyname"] == "" or row["policyname"] == "000000000000000000000000000000000000000000000000000"): + policies_id = row["policyname"] + if (row["subjectperimetername"] == "" or row[ + "subjectperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimeter_id = row["subjectperimetername"] + if (row["subjectcategory"] == "" or row[ + "subjectcategory"] == "000000000000000000000000000000000000000000000000000"): + categories_id = row["subjectcategory"] + if (row["subjectdata"] == "" or row["subjectdata"] == "000000000000000000000000000000000000000000000000000"): + dataids = row['subjectdata'] + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementssubjectAPI, + headers=headers, data=json.dumps(data)) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Post action assignment using the policy id, action perimeter id, action category, list of action data ids +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following object assignment') +def step_impl(context): + logger.info("When the user sets to add the following object assignment") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row["objectperimetername"] + "' object data: '" + row[ + "objectdata"] + "' and object category: '" + row[ + "objectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataids = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policyname'] == "" or row['policyname'] == "000000000000000000000000000000000000000000000000000"): + policyname = "Stanford Policy" + else: + policyname = row['policyname'] + policies_id = commonfunctions.get_policyid(policyname) + + if (row["objectperimetername"] == "" or row[ + "objectperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimetername = "StudentsGradesSheet" + else: + perimetername = row["objectperimetername"] + perimeter_id = commonfunctions.get_objectperimeterid(perimetername) + + if (row["objectcategory"] == "" or row[ + "objectcategory"] == "000000000000000000000000000000000000000000000000000"): + categoriesname = "Clearance:" + else: + categoriesname = row['objectcategory'] + categories_id = commonfunctions.get_objectcategoryid(categoriesname) + + if (row["objectdata"] == "" or row["objectdata"] == "000000000000000000000000000000000000000000000000000"): + dataids = "Confidential" + else: + dataids = row['objectdata'] + dataids = commonfunctions.get_objectdataid(dataids, categories_id, policies_id) + + if (dataids == None): + dataids = "" + + if (row["policyname"] == "" or row["policyname"] == "000000000000000000000000000000000000000000000000000"): + policies_id = row["policyname"] + if (row["objectperimetername"] == "" or row[ + "objectperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimeter_id = row["objectperimetername"] + if (row["objectcategory"] == "" or row[ + "objectcategory"] == "000000000000000000000000000000000000000000000000000"): + categories_id = row["objectcategory"] + if (row["objectdata"] == "" or row["objectdata"] == "000000000000000000000000000000000000000000000000000"): + dataids = row['objectdata'] + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementsobjectAPI, + headers=headers, data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Post action assignment using the policy id, action perimeter id, action category, list of action data ids +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following action assignment') +def step_impl(context): + logger.info("When the user sets to add the following action assignment") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action perimeter name: '" + row["actionperimetername"] + "' action data: '" + row[ + "actiondata"] + "' and action category: '" + row[ + "actioncategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + categoriesname = "" + dataids = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policyname'] == "" or row['policyname'] == "000000000000000000000000000000000000000000000000000"): + policyname = "Stanford Policy" + else: + policyname = row['policyname'] + policies_id = commonfunctions.get_policyid(policyname) + + if (row["actionperimetername"] == "" or row[ + "actionperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimetername = "Read" + else: + perimetername = row["actionperimetername"] + perimeter_id = commonfunctions.get_actionperimeterid(perimetername) + + if (row["actioncategory"] == "" or row[ + "actioncategory"] == "000000000000000000000000000000000000000000000000000"): + categoriesname = "Action-Class:" + else: + categoriesname = row['actioncategory'] + categories_id = commonfunctions.get_actioncategoryid(categoriesname) + + if (row["actiondata"] == "" or row["actiondata"] == "000000000000000000000000000000000000000000000000000"): + dataids = "Severe" + else: + dataids = row['actiondata'] + dataids = commonfunctions.get_actiondataid(dataids, categories_id, policies_id) + + if (dataids == None): + dataids = "" + + if (row["policyname"] == "" or row["policyname"] == "000000000000000000000000000000000000000000000000000"): + policies_id = row["policyname"] + if (row["actionperimetername"] == "" or row[ + "actionperimetername"] == "000000000000000000000000000000000000000000000000000"): + perimeter_id = row["actionperimetername"] + if (row["actioncategory"] == "" or row[ + "actioncategory"] == "000000000000000000000000000000000000000000000000000"): + categories_id = row["actioncategory"] + if (row["actiondata"] == "" or row["actiondata"] == "000000000000000000000000000000000000000000000000000"): + dataids = row['actiondata'] + data = { + 'id': perimeter_id, + 'category_id': categories_id, + 'policy_id': policies_id, + 'data_id': dataids, + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.assignementsactionAPI, + headers=headers, data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Delete subject assignment by policy id,subject perimeter id, subject data id, subject category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following subject assignment') +def step_impl(context): + logging.info("When the user sets to delete the following subject assignment") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject data list: '" + row[ + "subjectdata"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + dataid = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_subjectperimeterid(row['subjectperimetername']) + categories_id = commonfunctions.get_subjectcategoryid(row['subjectcategory']) + dataid = commonfunctions.get_subjectdataid(row["subjectdata"], categories_id, policies_id) + + response_assignment = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementssubjectAPI + "/" + + perimeter_id + "/" + categories_id, headers=apis_urls.auth_headers) + logging.info(response_assignment.json()[apis_urls.assignementssubjectAPI]) + if len(response_assignment.json()[apis_urls.assignementssubjectAPI]) != 0: + for ids in dict(response_assignment.json()[apis_urls.assignementssubjectAPI]).keys(): + assignmentsidlist = response_assignment.json()[apis_urls.assignementssubjectAPI][str(ids)][ + 'assignments'] + if dataid in assignmentsidlist: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementssubjectAPI + "/" + + perimeter_id + "/" + categories_id + "/" + dataid, headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + + +# Step Definition Implementation: +# 1) Delete object assignment by policy id, object perimeter id, object data id, object category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following object assignment') +def step_impl(context): + logging.info("When the user sets to delete the following object assignment") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row["objectperimetername"] + "' object data list: '" + row[ + "objectdata"] + "' and object category: '" + row[ + "objectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + datalistids = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_objectperimeterid(row['objectperimetername']) + categories_id = commonfunctions.get_objectcategoryid(row['objectcategory']) + dataid = commonfunctions.get_objectdataid(row["objectdata"], categories_id, policies_id) + + response_assignment = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementsobjectAPI + "/" + + perimeter_id + "/" + categories_id, headers=apis_urls.auth_headers) + if len(response_assignment.json()[apis_urls.assignementsobjectAPI]) != 0: + for ids in dict(response_assignment.json()[apis_urls.assignementsobjectAPI]).keys(): + assignmentsidlist = response_assignment.json()[apis_urls.assignementsobjectAPI][str(ids)][ + 'assignments'] + if dataid in assignmentsidlist: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementsobjectAPI + "/" + + perimeter_id + "/" + categories_id + "/" + dataid, headers=headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + + +# Step Definition Implementation: +# 1) Delete action assignment by policy id, action perimeter id, action data id, action category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following action assignment') +def step_impl(context): + logging.info("When the user sets to delete the following action assignment") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action perimeter name: '" + row["actionperimetername"] + "' action data list: '" + row[ + "actiondata"] + "' and action category: '" + row[ + "actioncategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + perimeter_id = "" + datalistids = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policies_id = commonfunctions.get_policyid(row['policyname']) + perimeter_id = commonfunctions.get_actionperimeterid(row['actionperimetername']) + categories_id = commonfunctions.get_actioncategoryid(row['actioncategory']) + dataid = commonfunctions.get_actiondataid(row["actiondata"], categories_id, policies_id) + + response_assignment = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementsactionAPI + "/" + + perimeter_id + "/" + categories_id, headers=apis_urls.auth_headers) + if len(response_assignment.json()[apis_urls.assignementsactionAPI]) != 0: + for ids in dict(response_assignment.json()[apis_urls.assignementsactionAPI]).keys(): + assignmentsidlist = response_assignment.json()[apis_urls.assignementsactionAPI][str(ids)][ + 'assignments'] + if dataid in assignmentsidlist: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.assignementsactionAPI + "/" + + perimeter_id + "/" + categories_id + "/" + dataid, headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing subject assignment per a given policy, subject perimeter and subject category by get request and put them into a table +# 2) Sort the table by subject perimeter name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following subject assignment should be existed in the system') +def step_impl(context): + logger.info("Then the following subject assignment should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('subjectperimetername', 'subjectcategory', 'subjectdata', 'policyname'), + dtype=('S100', 'S100', 'S100', 'S100')) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject data list: '" + row[ + "subjectdata"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + if (row['policyname'] == "" or row['subjectperimetername'] == ""): + response = requests.get( + apis_urls.serverURL + "policies/" + GeneralVariables.assignpolicyid[ + 'value'] + "/" + apis_urls.assignementssubjectAPI + "/" + + GeneralVariables.assignsubjectperimeterid['value'] + "/" + + GeneralVariables.assignsubjectcategoryid['value'], headers=apis_urls.auth_headers) + else: + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.assignementssubjectAPI + "/" + + commonfunctions.get_subjectperimeterid(row['subjectperimetername']) + "/" + + commonfunctions.get_subjectcategoryid(row['subjectcategory']), headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.assignementssubjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.assignementssubjectAPI]).keys(): + apipolicies = "" + apisubjectname = commonfunctions.get_subjectperimetername( + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['subject_id']) + apisubjectcategory = commonfunctions.get_subjectcategoryname( + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['category_id']) + apiassignments = commonfunctions.get_subjectdataname( + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['assignments'], + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['category_id'], + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['policy_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.assignementssubjectAPI][str(ids)]['policy_id']) + if ((row['policyname'] == "" or row['subjectperimetername'] == "") and "".join(apiassignments)==""): + apiresult.add_row(vals=("", "", "", "")) + else: + apiresult.add_row(vals=( + apisubjectname, apisubjectcategory, apiassignments, apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('subjectperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected subject perimeter name: '" + str( + row1["subjectperimetername"]) + "' is the same as the actual existing '" + str( + row2["subjectperimetername"]) + "'") + assert str(row1["subjectperimetername"]) == str( + row2["subjectperimetername"]), "subject perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject data description: '" + str( + row1["subjectcategory"]) + "' is the same as the actual existing '" + str( + row2["subjectcategory"]) + "'") + assert str(row1["subjectcategory"]) == str( + row2["subjectcategory"]), "subject category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject data password: '" + str( + row1["subjectdata"]) + "' is the same as the actual existing '" + str( + row2["subjectdata"]) + "'") + assert str(row1["subjectdata"]) == str( + row2["subjectdata"]), "subject data list is not correct!" + logger.info("assertion passed!") + + #logger.info("asserting the expected policies: '" + str( + # row1["policyname"]) + "' is the same as the actual existing '" + str( + # row2["policyname"]) + "'") + #assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + #logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing object assignment per a given policy, object perimeter and object category by get request and put them into a table +# 2) Sort the table by object perimeter name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following object assignment should be existed in the system') +def step_impl(context): + logger.info("Then the following object assignment should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('objectperimetername', 'objectcategory', 'objectdata', 'policyname'), + dtype=('S100', 'S100', 'S400', 'S100')) + for row in context.table: + if (row['policyname'] == "" or row['objectperimetername'] == ""): + response = requests.get( + apis_urls.serverURL + "policies/" + GeneralVariables.assignpolicyid[ + 'value'] + "/" + apis_urls.assignementsobjectAPI + "/" + + GeneralVariables.assignobjectperimeterid['value'] + "/" + + GeneralVariables.assignobjectcategoryid['value'], headers=apis_urls.auth_headers) + else: + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.assignementsobjectAPI + "/" + + commonfunctions.get_objectperimeterid(row['objectperimetername']) + "/" + + commonfunctions.get_objectcategoryid(row['objectcategory']), headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.assignementsobjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.assignementsobjectAPI]).keys(): + apipolicies = "" + apiobjectname = commonfunctions.get_objectperimetername( + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['object_id']) + apiobjectcategory = commonfunctions.get_objectcategoryname( + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['category_id']) + apiassignments = commonfunctions.get_objectdataname( + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['assignments'], + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['category_id'], + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['policy_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.assignementsobjectAPI][str(ids)]['policy_id']) + if ((row['policyname'] == "" or row['objectperimetername'] == "") and "".join(apiassignments) == ""): + apiresult.add_row(vals=("", "", "", "")) + else: + apiresult.add_row(vals=( + apiobjectname, apiobjectcategory, ",".join(apiassignments), apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('objectperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected object perimeter name: '" + str( + row1["objectperimetername"]) + "' is the same as the actual existing '" + str( + row2["objectperimetername"]) + "'") + assert str(row1["objectperimetername"]) == str( + row2["objectperimetername"]), "object perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object data description: '" + str( + row1["objectcategory"]) + "' is the same as the actual existing '" + str( + row2["objectcategory"]) + "'") + assert str(row1["objectcategory"]) == str( + row2["objectcategory"]), "object category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object data password: '" + str( + row1["objectdata"]) + "' is the same as the actual existing '" + str( + row2["objectdata"]) + "'") + assert str(row1["objectdata"]) == str( + row2["objectdata"]), "object data list is not correct!" + logger.info("assertion passed!") + + #logger.info("asserting the expected policies: '" + str( + # row1["policyname"]) + "' is the same as the actual existing '" + str( + # row2["policyname"]) + "'") + #assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + #logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing action assignment per a given policy, action perimeter and action category by get request and put them into a table +# 2) Sort the table by action perimeter name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following action assignment should be existed in the system') +def step_impl(context): + logger.info("Then the following action assignment should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('actionperimetername', 'actioncategory', 'actiondata', 'policyname'), + dtype=('S100', 'S100', 'S100', 'S100')) + for row in context.table: + if (row['policyname'] == "" or row['actionperimetername'] == ""): + response = requests.get( + apis_urls.serverURL + "policies/" + GeneralVariables.assignpolicyid[ + 'value'] + "/" + apis_urls.assignementsactionAPI + "/" + + GeneralVariables.assignactionperimeterid['value'] + "/" + + GeneralVariables.assignactioncategoryid['value'], headers=apis_urls.auth_headers) + else: + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.assignementsactionAPI + "/" + + commonfunctions.get_actionperimeterid(row['actionperimetername']) + "/" + + commonfunctions.get_actioncategoryid(row['actioncategory']), headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.assignementsactionAPI]) != 0: + for ids in dict(response.json()[apis_urls.assignementsactionAPI]).keys(): + apipolicies = "" + apiactionname = commonfunctions.get_actionperimetername( + response.json()[apis_urls.assignementsactionAPI][str(ids)]['action_id']) + apiactioncategory = commonfunctions.get_actioncategoryname( + response.json()[apis_urls.assignementsactionAPI][str(ids)]['category_id']) + apiassignments = commonfunctions.get_actiondataname( + response.json()[apis_urls.assignementsactionAPI][str(ids)]['assignments'], + response.json()[apis_urls.assignementsactionAPI][str(ids)]['category_id'], + response.json()[apis_urls.assignementsactionAPI][str(ids)]['policy_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.assignementsactionAPI][str(ids)]['policy_id']) + logger.info(apiassignments) + if ((row['policyname'] == "" or row['actionperimetername'] == "") and "".join(apiassignments) == ""): + apiresult.add_row(vals=("", "", "", "")) + else: + apiresult.add_row(vals=( + apiactionname, apiactioncategory, apiassignments, apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('actionperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected action perimeter name: '" + str( + row1["actionperimetername"]) + "' is the same as the actual existing '" + str( + row2["actionperimetername"]) + "'") + assert str(row1["actionperimetername"]) == str( + row2["actionperimetername"]), "action perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action data description: '" + str( + row1["actioncategory"]) + "' is the same as the actual existing '" + str( + row2["actioncategory"]) + "'") + assert str(row1["actioncategory"]) == str( + row2["actioncategory"]), "action category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action data password: '" + str( + row1["actiondata"]) + "' is the same as the actual existing '" + str( + row2["actiondata"]) + "'") + assert str(row1["actiondata"]) == str( + row2["actiondata"]), "action data list is not correct!" + logger.info("assertion passed!") + + #logger.info("asserting the expected policies: '" + str( + # row1["policyname"]) + "' is the same as the actual existing '" + str( + # row2["policyname"]) + "'") + #assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + #logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/authorization.py b/moon_manager/tests/func_tests/features/steps/authorization.py new file mode 100644 index 00000000..5fa0ebe7 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/authorization.py @@ -0,0 +1,217 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from common_functions import * +import requests +import json +import logging +import paramiko + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: Incomplete Step +# 1) Connect to the server +# 2) Launch Moon Manager +# 3) Set the token in the global variables +@Given('the manager is configured') +def step_impl(context): + logger.info("\n") + logger.info("******************** Scenario: " + context.scenario.name + " ********************") + logger.info("Given the manager is configured") + api_responseflag = {'value': False} + client = paramiko.SSHClient() + client.load_system_host_keys() + # client.set_missing_host_key_policy(paramiko.WarningPolicy) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=apis_urls.serverIP, port=apis_urls.serverport, username=apis_urls.serverusername, + password=apis_urls.serverpassword) + logger.info("before ") + stdin, stdout, stderr = client.exec_command( + + "sudo nohup hug -m moon_manager.server &" + " /usr/bin/python3 " + ) + #stdin, stdout, stderr = client.exec_command(" sudo /usr/local/bin/moon_manager add_user alaa00 admin") + #stdin, stdout, stderr = client.exec_command(" sudo /usr/local/bin/moon_manager get_key alaa00 admin ") + #logger.info(stdout.readlines()) + #GeneralVariables.auth_headers['X-Api-Key'] = str(stdout.readlines()) + #logger.info("token: " + str(GeneralVariables.auth_headers['X-Api-Key'])) + #logger.info("after ") + # client.close() + +# Step Definition Implementation: Incomplete Step +# 1) Get all the moon slaves +# 2) Loop on the slave by id and delete them +@Given('no slave is created') +def step_impl(context): + logger.info("\n") + logger.info("******************** Scenario: " + context.scenario.name + " ********************") + logger.info("Given no slave is created") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + response = requests.get(apis_urls.serverURL + apis_urls.getslavesAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.getslavesAPI]) != 0: + for ids in dict(response.json()[apis_urls.getslavesAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.slaveAPI + "/" + ids, + headers=headers) + +# Step Definition Implementation: +# 1) Create a slave by post request +# 2) Get the wrapper port id from the slave posting request & set it to the wrapperPort global variable +@Given('the slave is created') +def step_impl(context): + logger.info("Given the slave is created") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + data = { + 'name': "default", + 'description': "description", + 'address': "111", + } + response = requests.post(apis_urls.serverURL + apis_urls.slaveAPI, headers=headers, + data=json.dumps(data)) + slaveid = list(response.json()[apis_urls.getslavesAPI])[0] + GeneralVariables.wrapperPort['value'] = str(response.json()[apis_urls.getslavesAPI][slaveid]['extra']['port']) + +# Step Definition Implementation: Incomplete Step +# 1) Check the Pipeline is up and running +@Given('the pipeline is running') +def step_impl(context): + logger.info("Given the pipeline is running") + +# Step Definition Implementation: Incomplete Step +# 1) Connect to the server +# 2) execute the authorization curl command using the wrapperPort +@Given('the following authorization request is granted through pipeline') +def step_impl(context): + logger.info("Given the following authorization request is granted through pipeline") + api_responseflag = {'value': False} + client = paramiko.SSHClient() + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=apis_urls.serverIP, port=apis_urls.serverport, username=apis_urls.serverusername, + password=apis_urls.serverpassword) + for row in context.table: + logger.info("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.pipelinePort['value'] + "/authz/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + stdin, stdout, stderr = client.exec_command("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.pipelinePort['value'] + "/authz/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + logger.info(stdout.readlines()) + GeneralVariables.actual_authresponse['value'] = str(stdout.readlines()) + +# Step Definition Implementation: Incomplete Step +# 1) Connect to the server +# 2) execute the authorization curl command using the wrapperPort +@Given('the following authorization request is granted through wrapper') +def step_impl(context): + logger.info("Given the following authorization request is granted through wrapper") + api_responseflag = {'value': False} + client = paramiko.SSHClient() + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=apis_urls.serverIP, port=apis_urls.serverport, username=apis_urls.serverusername, + password=apis_urls.serverpassword) + for row in context.table: + logger.info("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.wrapperPort['value'] + "/authz/" + str(row[ + "keystone_project_id"]) + "/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + stdin, stdout, stderr = client.exec_command("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.wrapperPort['value'] + "/authz/" + str(row[ + "keystone_project_id"]) + "/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + logger.info(stdout.readlines()) + GeneralVariables.actual_authresponse['value'] = str(stdout.readlines()) + +# Step Definition Implementation: Incomplete Step +# 1) Connect to the server +# 2) execute the authorization curl command using the pipelinePort +# 3) set the actual_authresponse global variable with the curl response +@When('the following authorization request is sent through pipeline') +def step_impl(context): + logger.info("Given the following authorization request is sent through pipeline") + api_responseflag = {'value': False} + client = paramiko.SSHClient() + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=apis_urls.serverIP, port=apis_urls.serverport, username=apis_urls.serverusername, + password=apis_urls.serverpassword) + + for row in context.table: + logger.info("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.pipelinePort['value'] + "/authz/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + stdin, stdout, stderr = client.exec_command("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.pipelinePort['value'] + "/authz/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + logger.info(stdout.readlines()) + GeneralVariables.actual_authresponse['value'] = str(stdout.readlines()) + +# Step Definition Implementation: Incomplete Step +# 1) Connect to the server +# 2) execute the authorization curl command using the pipelinePort +# 3) set the actual_authresponse global variable with the curl response +@When('the following authorization request is sent through wrapper') +def step_impl(context): + logger.info("Given the following authorization request is sent through wrapper") + api_responseflag = {'value': False} + client = paramiko.SSHClient() + client.load_system_host_keys() + client.set_missing_host_key_policy(paramiko.WarningPolicy) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.connect(hostname=apis_urls.serverIP, port=apis_urls.serverport, username=apis_urls.serverusername, + password=apis_urls.serverpassword) + + for row in context.table: + logger.info("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.wrapperPort['value'] + "/authz/" + str(row[ + "keystone_project_id"]) + "/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + stdin, stdout, stderr = client.exec_command("curl http://" + str( + apis_urls.serverIP) + ":" + GeneralVariables.wrapperPort['value'] + "/authz/" + str(row[ + "keystone_project_id"]) + "/" + str( + row["subjectperimetername"]) + "/" + str(row["objectperimetername"]) + "/" + + str(row["actionperimetername"])) + logger.info(stdout.readlines()) + GeneralVariables.actual_authresponse['value'] = str(stdout.readlines()) + +# Step Definition Implementation: Untested Step +# 1) Assert that the actual authresponse is the same as the expected. +@Then('the authorization response should be the following') +def step_impl(context): + logger.info("Then the authorization response should be the following") + for row in context.table: + logger.info("asserting the expected api response: '" + row["auth_response"] + "' and the actual response: '" + + GeneralVariables.actual_authresponse['value'] + "'") + assert row["auth_response"] == GeneralVariables.actual_authresponse[ + 'value'], "Validation is not correct, Expected: " + \ + row[ + "auth_response"] + " but the API response was: " + \ + GeneralVariables.actual_authresponse['value'] + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/common_functions.py b/moon_manager/tests/func_tests/features/steps/common_functions.py new file mode 100644 index 00000000..b9b9f0bc --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/common_functions.py @@ -0,0 +1,279 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from steps.Static_Variables import GeneralVariables +import requests +import json +import logging + + +logger = logging.getLogger(__name__) + +class commonfunctions: + apis_urls = GeneralVariables() + + def get_subjectcategoryid(self, subjectcategoryname): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadatasubjectcategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadatasubjectcategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadatasubjectcategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadatasubjectcategoryAPI][ids]['name'] == subjectcategoryname): + return response.json()[self.apis_urls.metadatasubjectcategoryAPI][ids]['id'] + + def get_objectcategoryid(self, objectcategoryname): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadataobjectcategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadataobjectcategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadataobjectcategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadataobjectcategoryAPI][ids]['name'] == objectcategoryname): + return response.json()[self.apis_urls.metadataobjectcategoryAPI][ids]['id'] + + def get_actioncategoryid(self, actioncategoryname): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadataactioncategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadataactioncategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadataactioncategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadataactioncategoryAPI][ids]['name'] == actioncategoryname): + return response.json()[self.apis_urls.metadataactioncategoryAPI][ids]['id'] + + def get_metaruleid(self, metarulename): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metarulesAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metarulesAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metarulesAPI]).keys(): + if (response.json()[self.apis_urls.metarulesAPI][ids]['name'] == metarulename): + return ids + + def get_modelid(self, modelname): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.modelAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.modelAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.modelAPI]).keys(): + if (response.json()[self.apis_urls.modelAPI][ids]['name'] == modelname): + return ids + + def get_policyid(self, policyname): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.policyAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.policyAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.policyAPI]).keys(): + if (response.json()[self.apis_urls.policyAPI][ids]['name'] == policyname): + return ids + + def get_subjectperimeterid(self,subjectperimeter ): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimetersubjectAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimetersubjectAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.perimetersubjectAPI]).keys(): + if (response.json()[self.apis_urls.perimetersubjectAPI][ids]['name'] == subjectperimeter): + return ids + + def get_objectperimeterid(self,objectperimeter ): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimeterobjectAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimeterobjectAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.perimeterobjectAPI]).keys(): + if (response.json()[self.apis_urls.perimeterobjectAPI][ids]['name'] == objectperimeter): + return ids + + def get_actionperimeterid(self, actionperimeter): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimeteractionAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimeteractionAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.perimeteractionAPI]).keys(): + if (response.json()[self.apis_urls.perimeteractionAPI][ids]['name'] == actionperimeter): + return ids + + def get_subjectdataid(self,subjectdataname,subjectcategoryid,policyid ): + response_data = requests.get( + self.apis_urls.serverURL + "policies/" + policyid + "/" + self.apis_urls.datasubjectAPI + "/" + subjectcategoryid,headers=self.apis_urls.auth_headers) + if(len(response_data.json()[self.apis_urls.datasubjectAPI]))!=0: + subjectdataidslist = [] + matcheddataidslist = [] + dataids=response_data.json()[self.apis_urls.datasubjectAPI][0]['data'] + for ids in dataids: + apisubjectdataid = response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(ids)]['id'] + subjectdataidslist.append(apisubjectdataid) + + if ((str(subjectdataname)).find(",") != -1): + datanameslist = subjectdataname.split(",") + for dataname in datanameslist: + for data_id in subjectdataidslist: + if ((response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(data_id)][ + 'name']) == dataname): + matcheddataidslist.append(data_id) + return ",".join(matcheddataidslist) + else: + for data_id in subjectdataidslist: + if (( + response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(data_id)]['name']) == subjectdataname): + return data_id + + def get_objectdataid(self,objectdataname,objectcategoryid,policyid ): + response_data = requests.get( + self.apis_urls.serverURL + self.apis_urls.policyAPI + "/" + policyid + "/" + self.apis_urls.dataobjectAPI + "/" + objectcategoryid,headers=self.apis_urls.auth_headers) + if (len(response_data.json()[self.apis_urls.dataobjectAPI])) != 0: + objectdataidslist = [] + matcheddataidslist=[] + for ids in response_data.json()[ self.apis_urls.dataobjectAPI][0]['data']: + apiobjectdataid = response_data.json()[ self.apis_urls.dataobjectAPI][0]['data'][str(ids)]['id'] + objectdataidslist.append(apiobjectdataid) + if ((str(objectdataname)).find(",") != -1): + datanameslist = objectdataname.split(",") + for dataname in datanameslist: + for data_id in objectdataidslist: + if ((response_data.json()[self.apis_urls.dataobjectAPI][0]['data'][str(data_id)]['name']) == dataname): + matcheddataidslist.append(data_id) + return ",".join(matcheddataidslist) + + else: + for data_id in objectdataidslist: + if ((response_data.json()[self.apis_urls.dataobjectAPI][0]['data'][str(data_id)]['name']) == objectdataname): + return data_id + + def get_actiondataid(self,actiondataname,actioncategoryid,policyid ): + response_data = requests.get( + self.apis_urls.serverURL + self.apis_urls.policyAPI + "/" + policyid + "/" + self.apis_urls.dataactionAPI + "/" + actioncategoryid,headers=self.apis_urls.auth_headers) + if (len(response_data.json()[self.apis_urls.dataactionAPI])) != 0: + actiondataidslist = [] + matcheddataidslist = [] + for ids in response_data.json()[self.apis_urls.dataactionAPI][0]['data']: + apiactiondataid = response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(ids)]['id'] + actiondataidslist.append(apiactiondataid) + if ((str(actiondataname)).find(",") != -1): + datanameslist = actiondataname.split(",") + for dataname in datanameslist: + for data_id in actiondataidslist: + if ((response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(data_id)][ + 'name']) == dataname): + matcheddataidslist.append(data_id) + return ",".join(matcheddataidslist) + else: + for data_id in actiondataidslist: + if ((response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(data_id)]['name']) == actiondataname): + return data_id + + def get_subjectcategoryname(self, subjectcategoryid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadatasubjectcategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadatasubjectcategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadatasubjectcategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadatasubjectcategoryAPI][ids]['id'] == subjectcategoryid): + return response.json()[self.apis_urls.metadatasubjectcategoryAPI][ids]['name'] + + def get_objectcategoryname(self, objectcategoryid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadataobjectcategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadataobjectcategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadataobjectcategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadataobjectcategoryAPI][ids]['id'] == objectcategoryid): + return response.json()[self.apis_urls.metadataobjectcategoryAPI][ids]['name'] + + def get_actioncategoryname(self, actioncategoryid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metadataactioncategoryAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metadataactioncategoryAPI]) != 0: + for ids in dict(response.json()[self.apis_urls.metadataactioncategoryAPI]).keys(): + if (response.json()[self.apis_urls.metadataactioncategoryAPI][ids]['id'] == actioncategoryid): + return response.json()[self.apis_urls.metadataactioncategoryAPI][ids]['name'] + + def get_metarulename(self, metaruleid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.metarulesAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.metarulesAPI]) != 0: + for id in dict(response.json()[self.apis_urls.metarulesAPI]).keys(): + if (id == metaruleid): + return response.json()[self.apis_urls.metarulesAPI][id]['name'] + + def get_modelname(self, modelid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.modelAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.modelAPI]) != 0: + for id in dict(response.json()[self.apis_urls.modelAPI]).keys(): + if (id == modelid): + return response.json()[self.apis_urls.modelAPI][id]['name'] + + def get_policyname(self, policyid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.policyAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.policyAPI]) != 0: + for id in dict(response.json()[self.apis_urls.policyAPI]).keys(): + if (id == policyid): + return response.json()[self.apis_urls.policyAPI][id]['name'] + + def get_subjectperimetername(self, subjectperimeterid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimetersubjectAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimetersubjectAPI]) != 0: + for id in dict(response.json()[self.apis_urls.perimetersubjectAPI]).keys(): + if (id == subjectperimeterid): + return response.json()[self.apis_urls.perimetersubjectAPI][id]['name'] + + def get_objectperimetername(self, objectperimeterid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimeterobjectAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimeterobjectAPI]) != 0: + for id in dict(response.json()[self.apis_urls.perimeterobjectAPI]).keys(): + if (id == objectperimeterid): + return response.json()[self.apis_urls.perimeterobjectAPI][id]['name'] + + def get_actionperimetername(self, actionperimeterid): + response = requests.get(self.apis_urls.serverURL + self.apis_urls.perimeteractionAPI,headers=self.apis_urls.auth_headers) + if len(response.json()[self.apis_urls.perimeteractionAPI]) != 0: + for id in dict(response.json()[self.apis_urls.perimeteractionAPI]).keys(): + if (id == actionperimeterid): + return response.json()[self.apis_urls.perimeteractionAPI][id]['name'] + + def get_subjectdataname(self, subjectdataids, subjectcategoryid, policyid): + subjectdatanames=[] + for subjectdataid in subjectdataids: + response_data = requests.get( + self.apis_urls.serverURL + "policies/" + policyid + "/" + self.apis_urls.datasubjectAPI + "/" + subjectcategoryid+"/"+subjectdataid,headers=self.apis_urls.auth_headers) + + subjectdataidslist = [] + if(response_data.status_code==200): + for ids in response_data.json()[self.apis_urls.datasubjectAPI][0]['data']: + apisubjectdataid = response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(ids)]['id'] + subjectdataidslist.append(apisubjectdataid) + + for data_id in subjectdataidslist: + if (str((response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(data_id)][ + 'id'])) == subjectdataid): + subjectdatanames.append(str(response_data.json()[self.apis_urls.datasubjectAPI][0]['data'][str(data_id)]['name'])) + else: + subjectdataidslist = "" + return subjectdatanames + + def get_objectdataname(self, objectdataids, objectcategoryid, policyid): + objectdatanames = [] + for objectdataid in objectdataids: + response_data = requests.get( + self.apis_urls.serverURL + "policies/" + policyid + "/" + self.apis_urls.dataobjectAPI + "/" + objectcategoryid + "/" + objectdataid,headers=self.apis_urls.auth_headers) + objectdataidslist = [] + if (response_data.status_code == 200): + for ids in response_data.json()[self.apis_urls.dataobjectAPI][0]['data']: + apiobjectdataid = response_data.json()[self.apis_urls.dataobjectAPI][0]['data'][str(ids)]['id'] + objectdataidslist.append(apiobjectdataid) + for data_id in objectdataidslist: + if (str((response_data.json()[self.apis_urls.dataobjectAPI][0]['data'][str(data_id)][ + 'id'])) == objectdataid): + objectdatanames.append( + str(response_data.json()[self.apis_urls.dataobjectAPI][0]['data'][str(data_id)]['name'])) + else: + objectdataidslist = "" + return objectdatanames + + def get_actiondataname(self, actiondataids, actioncategoryid, policyid): + actiondatanames = [] + for actiondataid in actiondataids: + response_data = requests.get( + self.apis_urls.serverURL + "policies/" + policyid + "/" + self.apis_urls.dataactionAPI + "/" + actioncategoryid + "/" + actiondataid,headers=self.apis_urls.auth_headers) + #logger.info(response_data.json()[self.apis_urls.dataactionAPI][0]) + + actiondataidslist = [] + if (response_data.status_code == 200): + for ids in response_data.json()[self.apis_urls.dataactionAPI][0]['data']: + apiactiondataid = response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(ids)]['id'] + actiondataidslist.append(apiactiondataid) + logging.info(actiondataidslist) + for data_id in actiondataidslist: + if (str((response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(data_id)][ + 'id'])) == actiondataid): + actiondatanames.append( + str(response_data.json()[self.apis_urls.dataactionAPI][0]['data'][str(data_id)]['name'])) + else: + actiondataidslist = "" + return actiondatanames
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/steps/data.py b/moon_manager/tests/func_tests/features/steps/data.py new file mode 100644 index 00000000..67d743c2 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/data.py @@ -0,0 +1,629 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing subject meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get subject data using both the policy id & the category id +# 3) Loop by data id and delete it +@Given('the system has no subject data') +def step_impl(context): + logger.info("Given the system has no subject data") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI,headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + subjectcategoryidslist = [] + modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + if (modelid != None and modelid != ""): + metaruleslist = \ + requests.get(apis_urls.serverURL + apis_urls.modelAPI,headers=apis_urls.auth_headers).json()[apis_urls.modelAPI][modelid][ + 'meta_rules'] + for metarule_ids in metaruleslist: + categorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metarule_ids]['subject_categories'] + for categoryid in categorieslist: + if (categoryid not in subjectcategoryidslist): + subjectcategoryidslist.append(categoryid) + + for categoryid in subjectcategoryidslist: + response_data = requests.get( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.datasubjectAPI + "/" + categoryid,headers=apis_urls.auth_headers) + for ids in response_data.json()[apis_urls.datasubjectAPI][0]['data']: + data_id = response_data.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['id'] + requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.datasubjectAPI + "/" + categoryid + "/" + data_id, + headers=headers) + +# Step Definition Implementation: +# 1) Post subject data using the policy id & the category id +@Given('the following subject data exists') +def step_impl(context): + logger.info("Given the following subject data exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject data name: '" + row["subjectdataname"] + "' subject data description: '" + row[ + "subjectdatadescription"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['subjectcategory']) > 25): + categories_id = row['subjectcategory'] + else: + categories_id = commonfunctions.get_subjectcategoryid(row['subjectcategory']) + + data = { + 'name': row["subjectdataname"], + 'description': row["subjectdatadescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.datasubjectAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get all the existing object meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get object data using both the policy id & the category id +# 3) Loop by data id and delete it +@Given('the system has no object data') +def step_impl(context): + logger.info("Given the system has no object data") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI,headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + objectcategoryidslist = [] + modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + if (modelid != None and modelid != ""): + metaruleslist = \ + requests.get(apis_urls.serverURL + apis_urls.modelAPI,headers=apis_urls.auth_headers).json()[apis_urls.modelAPI][modelid][ + 'meta_rules'] + for metarule_ids in metaruleslist: + for categoryid in \ + (requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers)).json()[apis_urls.metarulesAPI][ + metarule_ids][ + 'object_categories']: + if (categoryid not in objectcategoryidslist): + objectcategoryidslist.append(categoryid) + + for categoryid in objectcategoryidslist: + response_data = requests.get( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.dataobjectAPI + "/" + categoryid,headers=apis_urls.auth_headers) + for ids in response_data.json()[apis_urls.dataobjectAPI][0]['data']: + data_id = response_data.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['id'] + requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.dataobjectAPI + "/" + categoryid + "/" + data_id, + headers=headers) + +# Step Definition Implementation: +# 1) Post object data using the policy id & the category id +@Given('the following object data exists') +def step_impl(context): + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject data name: '" + row["objectdataname"] + "' object data description: '" + row[ + "objectdatadescription"] + "' and object category: '" + row[ + "objectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['objectcategory']) > 25): + categories_id = row['objectcategory'] + else: + categories_id = commonfunctions.get_objectcategoryid(row['objectcategory']) + + data = { + 'name': row["objectdataname"], + 'description': row["objectdatadescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.dataobjectAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get all the existing action meta data in the system by getting the policies then their models then the model attached meta rules and then the categories +# 2) Get action data using both the policy id & the category id +# 3) Loop by data id and delete it +@Given('the system has no action data') +def step_impl(context): + logger.info("Given the system has no action data") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + actioncategoryidslist = [] + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI,headers=apis_urls.auth_headers) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + actioncategoryidslist = [] + modelid = response_policies.json()[apis_urls.policyAPI][policies_ids]['model_id'] + if (modelid != None and modelid != ""): + metaruleslist = \ + requests.get(apis_urls.serverURL + apis_urls.modelAPI,headers=apis_urls.auth_headers).json()[apis_urls.modelAPI][modelid][ + 'meta_rules'] + for metarule_ids in metaruleslist: + for categoryid in \ + (requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers)).json()[apis_urls.metarulesAPI][ + metarule_ids][ + 'action_categories']: + if (categoryid not in actioncategoryidslist): + actioncategoryidslist.append(categoryid) + + for categoryid in actioncategoryidslist: + response_data = requests.get( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.dataactionAPI + "/" + categoryid,headers=apis_urls.auth_headers) + for ids in response_data.json()[apis_urls.dataactionAPI][0]['data']: + data_id = response_data.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['id'] + requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + policies_ids + "/" + apis_urls.dataactionAPI + "/" + categoryid + "/" + data_id, + headers=headers) + +# Step Definition Implementation: +# 1) Post action data using the policy id & the category id +@Given('the following action data exists') +def step_impl(context): + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject data name: '" + row["actiondataname"] + "' action data description: '" + row[ + "actiondatadescription"] + "' and action category: '" + row[ + "actioncategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['actioncategory']) > 25): + categories_id = row['actioncategory'] + else: + categories_id = commonfunctions.get_actioncategoryid(row['actioncategory']) + + data = { + 'name': row["actiondataname"], + 'description': row["actiondatadescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.dataactionAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Add subject data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following subject data') +def step_impl(context): + logger.info("When the user sets to add the following subject data") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject data name: '" + row["subjectdataname"] + "' subject data description: '" + row[ + "subjectdatadescription"] + "' and subject category: '" + row[ + "subjectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['subjectcategory']) > 25): + categories_id = row['subjectcategory'] + else: + categories_id = commonfunctions.get_subjectcategoryid(row['subjectcategory']) + + data = { + 'name': row["subjectdataname"], + 'description': row["subjectdatadescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.datasubjectAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Delete subject data by policy id, subject data id, subject category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following subject data') +def step_impl(context): + logging.info("When the user sets to delete the following subject data") + + model = getattr(context, "model", None) + for row in context.table: + + logger.info("subject data name:'" + row["subjectdataname"] + "' and subject category name:'" + row[ + "subjectcategory"] + "' and policy name:'" + row["policyname"] + "'") + + policies_id = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_data = requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + commonfunctions.get_policyid(row[ + "policyname"]) + "/" + apis_urls.datasubjectAPI + "/" + commonfunctions.get_subjectcategoryid( + row["subjectcategory"]) + "/" + commonfunctions.get_subjectdataid(row["subjectdataname"], + commonfunctions.get_subjectcategoryid( + row["subjectcategory"]), + commonfunctions.get_policyid( + row["policyname"])), + headers=headers) + + if response_data.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Add object data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following object data') +def step_impl(context): + logger.info("When the user sets to add the following object data") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object data name: '" + row["objectdataname"] + "' object data description: '" + row[ + "objectdatadescription"] + "' and object category: '" + row[ + "objectcategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_list = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['objectcategory']) > 25): + categories_id = row['objectcategory'] + else: + categories_id = commonfunctions.get_objectcategoryid(row['objectcategory']) + + data = { + 'name': row["objectdataname"], + 'description': row["objectdatadescription"], + } + + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.dataobjectAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Delete object data by policy id, object data id, object category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following object data') +def step_impl(context): + logging.info("When the user sets to delete the following object data") + model = getattr(context, "model", None) + for row in context.table: + + logger.info("object data name:'" + row["objectdataname"] + "' and object category name:'" + row[ + "objectcategory"] + "' and policy name:'" + row["policyname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_data = requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + commonfunctions.get_policyid(row[ + "policyname"]) + "/" + apis_urls.dataobjectAPI + "/" + commonfunctions.get_objectcategoryid( + row["objectcategory"]) + "/" + commonfunctions.get_objectdataid(row["objectdataname"], + commonfunctions.get_objectcategoryid( + row["objectcategory"]), + commonfunctions.get_policyid( + row["policyname"])), + headers=headers) + + if response_data.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Add action data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following action data') +def step_impl(context): + logger.info("When the user sets to add the following action data") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action data name: '" + row["actiondataname"] + "' action data description: '" + row[ + "actiondatadescription"] + "' and action category: '" + row[ + "actioncategory"] + "' and policies: '" + row['policyname'] + "'") + + policies_id = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + if (len(row['actioncategory']) > 25): + categories_id = row['actioncategory'] + else: + categories_id = commonfunctions.get_actioncategoryid(row['actioncategory']) + + data = { + 'name': row["actiondataname"], + 'description': row["actiondatadescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.dataactionAPI + "/" + str( + categories_id), headers=headers, data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Delete action data by policy id, action data id, action category id +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following action data') +def step_impl(context): + logging.info("When the user sets to delete the following action data") + model = getattr(context, "model", None) + for row in context.table: + + logger.info("action data name:'" + row["actiondataname"] + "' and action category name:'" + row[ + "actioncategory"] + "' and policy name:'" + row["policyname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response_data = requests.delete( + apis_urls.serverURL + apis_urls.policyAPI + "/" + commonfunctions.get_policyid(row[ + "policyname"]) + "/" + apis_urls.dataactionAPI + "/" + commonfunctions.get_actioncategoryid( + row["actioncategory"]) + "/" + commonfunctions.get_actiondataid(row["actiondataname"], + commonfunctions.get_actioncategoryid( + row["actioncategory"]), + commonfunctions.get_policyid( + row["policyname"])), + headers=headers) + + if response_data.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing subject data by get request and put them into a table +# 2) Sort the table by policy name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following subject data should be existed in the system') +def step_impl(context): + logger.info("Then the following subject data should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('subjectdataname', 'subjectdatadescription', 'subjectcategory', 'policyname'), + dtype=('S100', 'S100', 'S100', 'S100')) + for row in context.table: + if (row['policyname'] != ""): + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.datasubjectAPI + "/" + + commonfunctions.get_subjectcategoryid(row['subjectcategory']),headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.datasubjectAPI]) != 0: + for ids in response.json()[apis_urls.datasubjectAPI][0]['data']: + apipolicies = "" + apisubjectdataname = response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['name'] + apisubjectdatadescription = response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)][ + 'description'] + apisubjectcategory = commonfunctions.get_subjectcategoryname( + response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['category_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['policy_id']) + apiresult.add_row(vals=( + apisubjectdataname, apisubjectdatadescription, apisubjectcategory, apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('policyname') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected subject data name: '" + str( + row1["subjectdataname"]) + "' is the same as the actual existing '" + str( + row2["subjectdataname"]) + "'") + assert str(row1["subjectdataname"]) == str(row2["subjectdataname"]), "subject data name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject data description: '" + str( + row1["subjectdatadescription"]) + "' is the same as the actual existing '" + str( + row2["subjectdatadescription"]) + "'") + assert str(row1["subjectdatadescription"]) == str( + row2["subjectdatadescription"]), "subject data description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject data password: '" + str( + row1["subjectcategory"]) + "' is the same as the actual existing '" + str( + row2["subjectcategory"]) + "'") + assert str(row1["subjectcategory"]) == str( + row2["subjectcategory"]), "subject category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected policies: '" + str( + row1["policyname"]) + "' is the same as the actual existing '" + str( + row2["policyname"]) + "'") + assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing object data by get request and put them into a table +# 2) Sort the table by policy name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following object data should be existed in the system') +def step_impl(context): + logger.info("Then the following object data should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('objectdataname', 'objectdatadescription', 'objectcategory', 'policyname'), + dtype=('S100', 'S100', 'S100', 'S100')) + + for row in context.table: + if (row['policyname'] != ""): + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.dataobjectAPI + "/" + + commonfunctions.get_objectcategoryid(row['objectcategory']),headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.dataobjectAPI]) != 0: + for ids in response.json()[apis_urls.dataobjectAPI][0]['data']: + apipolicies = "" + apiobjectdataname = response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['name'] + apiobjectdatadescription = response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)][ + 'description'] + apiobjectcategory = commonfunctions.get_objectcategoryname( + response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['category_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['policy_id']) + + apiresult.add_row(vals=( + apiobjectdataname, apiobjectdatadescription, apiobjectcategory, apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('policyname') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected object data name: '" + str( + row1["objectdataname"]) + "' is the same as the actual existing '" + str( + row2["objectdataname"]) + "'") + assert str(row1["objectdataname"]) == str(row2["objectdataname"]), "subject data name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object data description: '" + str( + row1["objectdatadescription"]) + "' is the same as the actual existing '" + str( + row2["objectdatadescription"]) + "'") + assert str(row1["objectdatadescription"]) == str( + row2["objectdatadescription"]), "object data description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object data category: '" + str( + row1["objectcategory"]) + "' is the same as the actual existing '" + str( + row2["objectcategory"]) + "'") + assert str(row1["objectcategory"]) == str( + row2["objectcategory"]), "object category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected policies: '" + str( + row1["policyname"]) + "' is the same as the actual existing '" + str( + row2["policyname"]) + "'") + assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing action data by get request and put them into a table +# 2) Sort the table by policy name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following action data should be existed in the system') +def step_impl(context): + logger.info("Then the following action data should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('actiondataname', 'actiondatadescription', 'actioncategory', 'policyname'), + dtype=('S100', 'S100', 'S100', 'S100')) + for row in context.table: + if (row['policyname'] != ""): + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.dataactionAPI + "/" + + commonfunctions.get_actioncategoryid(row['actioncategory']),headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.dataactionAPI]) != 0: + for ids in response.json()[apis_urls.dataactionAPI][0]['data']: + apipolicies = "" + apiactiondataname = response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['name'] + apiactiondatadescription = response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)][ + 'description'] + apiactioncategory = commonfunctions.get_actioncategoryname( + response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['category_id']) + apipolicies = commonfunctions.get_policyname( + response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['policy_id']) + + apiresult.add_row(vals=( + apiactiondataname, apiactiondatadescription, apiactioncategory, apipolicies)) + else: + apiresult.add_row(vals=("", "", "", "")) + + else: + apiresult.add_row(vals=("", "", "", "")) + apiresult.sort('policyname') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected action data name: '" + str( + row1["actiondataname"]) + "' is the same as the actual existing '" + str( + row2["actiondataname"]) + "'") + assert str(row1["actiondataname"]) == str(row2["actiondataname"]), "action data name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action data description: '" + str( + row1["actiondatadescription"]) + "' is the same as the actual existing '" + str( + row2["actiondatadescription"]) + "'") + assert str(row1["actiondatadescription"]) == str( + row2["actiondatadescription"]), "action data description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action data category: '" + str( + row1["actioncategory"]) + "' is the same as the actual existing '" + str( + row2["actioncategory"]) + "'") + assert str(row1["actioncategory"]) == str( + row2["actioncategory"]), "action category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected policies: '" + str( + row1["policyname"]) + "' is the same as the actual existing '" + str( + row2["policyname"]) + "'") + assert str(row1["policyname"]) == str(row2["policyname"]), " policies is not correct!" + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/meta_data.py b/moon_manager/tests/func_tests/features/steps/meta_data.py new file mode 100644 index 00000000..b2a6d02c --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/meta_data.py @@ -0,0 +1,394 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +api_subjectcategory = {'name': "", 'description': ""} +api_objectcategory = {'name': "", 'description': ""} +api_actioncategory = {'name': "", 'description': ""} + +logger = logging.getLogger(__name__) + + +# Step Definition Implementation: +# 1) Get all the existing subject meta data in the system +# 2) Loop by id and delete them +@Given('the system has no subject categories') +def step_impl(context): + logger.info("Given the system has no subject categories") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.metadatasubjectcategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadatasubjectcategoryAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI + "/" + ids, + headers=headers) + +# Step Definition Implementation: +# 1) Get all the existing action meta data in the system +# 2) Loop by id and delete them +@Given('the system has no action categories') +def step_impl(context): + logger.info("Given the system has no action categories") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.metadataactioncategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadataactioncategoryAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI + "/" + ids, + headers=headers) + + +# Step Definition Implementation: +# 1) Get all the existing object meta data in the system +# 2) Loop by id and delete them +@Given('the system has no object categories') +def step_impl(context): + logger.info("Given the system has no object categories") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.metadataobjectcategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadataobjectcategoryAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI + "/" + ids, + headers=headers) + + + +# Step Definition Implementation: +# 1) Insert subject meta data using the post request +@Given('the following meta data subject category exists') +def step_impl(context): + logger.info("Given the following meta data subject category exists") + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + data = { + 'name': row["subjectmetadataname"], + 'description': row["subjectmetadatadescription"], + } + logger.info( + "subject category name: '" + row["subjectmetadataname"] + "' and subject category description: '" + row[ + "subjectmetadatadescription"] + "'") + response = requests.post(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Insert object meta data using the post request +@Given('the following meta data object category exists') +def step_impl(context): + logger.info("Given the following meta data object category exists") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + data = { + 'name': row["objectmetadataname"], + 'description': row["objectmetadatadescription"], + } + logger.info( + "object category name: '" + row["objectmetadataname"] + "' and object category description: '" + row[ + "objectmetadatadescription"] + "'") + response = requests.post(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Insert action meta data using the post request +@Given('the following meta data action category exists') +def step_impl(context): + logger.info("Given the following meta data action category exists") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + data = { + 'name': row["actionmetadataname"], + 'description': row["actionmetadatadescription"], + } + logger.info( + "action category name: '" + row["actionmetadataname"] + "' and action category description: '" + row[ + "actionmetadatadescription"] + "'") + response = requests.post(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Add subject meta data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following meta data subject category') +def step_impl(context): + logger.info("When the user sets to add the following meta data subject category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + data = { + 'name': row["subjectmetadataname"], + 'description': row["subjectmetadatadescription"], + } + logger.info( + "subject category name: '" + row["subjectmetadataname"] + "' and subject category description: '" + row[ + "subjectmetadatadescription"] + "'") + + response = requests.post(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + + +# Step Definition Implementation: +# 1) Get all the subject meta data by get request +# 2) Loop by ids and search for the matching subject meta data by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following meta data subject category') +def step_impl(context): + logger.info("When the user sets to delete the following meta data subject category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + logger.info("subject category name: '" + row["subjectmetadataname"] + "'") + + response = requests.get(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI, + headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.metadatasubjectcategoryAPI]).keys(): + if (response.json()[apis_urls.metadatasubjectcategoryAPI][ids]['name'] == row["subjectmetadataname"]): + response = requests.delete(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI + "/" + ids, + headers=headers) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Add object meta data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following meta data object category') +def step_impl(context): + logger.info("When the user sets to add the following meta data object category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + data = { + 'name': row["objectmetadataname"], + 'description': row["objectmetadatadescription"], + } + logger.info( + "object category Name: '" + row["objectmetadataname"] + "' and object category description: '" + row[ + "objectmetadatadescription"] + "''") + response = requests.post(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI, headers=headers, + data=json.dumps(data)) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the object meta data by get request +# 2) Loop by ids and search for the matching object meta data by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following meta data object category') +def step_impl(context): + logger.info("When the user sets to delete the following meta data object category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + logger.info("object category name: '" + row["objectmetadataname"] + "'") + + response = requests.get(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI, + headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.metadataobjectcategoryAPI]).keys(): + if (response.json()[apis_urls.metadataobjectcategoryAPI][ids]['name'] == row["objectmetadataname"]): + response = requests.delete(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI + "/" + ids, + headers=headers) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Add subject meta data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following meta data action category') +def step_impl(context): + logger.info("When the user sets to add the following meta data action category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + data = { + 'name': row["actionmetadataname"], + 'description': row["actionmetadatadescription"], + } + logger.info( + "action category name: '" + row["actionmetadataname"] + "' and action category description: '" + row[ + "actionmetadatadescription"] + "'") + + response = requests.post(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI, headers=headers, + data=json.dumps(data)) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the action meta data by get request +# 2) Loop by ids and search for the matching action meta data by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following meta data action category') +def step_impl(context): + logger.info("When the user sets to delete the following meta data action category") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("action category name: '" + row["actionmetadataname"] + "'") + + response = requests.get(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI, + headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.metadataactioncategoryAPI]).keys(): + # logger.info(ids) + if (response.json()[apis_urls.metadataactioncategoryAPI][ids]['name'] == row["actionmetadataname"]): + response = requests.delete(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI + "/" + ids, + headers=headers) + # logger.info(response.status_code) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing subject meta data by get request and put them into a table +# 2) Loop using both the expected and actual tables and assert the data row by row +@Then('the following meta data subject category should be existed in the system') +def step_impl(context): + logger.info("Then the following meta data subject category should be existed in the system") + + model = getattr(context, "model", None) + response = requests.get(apis_urls.serverURL + apis_urls.metadatasubjectcategoryAPI, headers=apis_urls.auth_headers) + apiresult = Table(names=('subjectcategoryname', 'subjectcategorydescription'), dtype=('S100', 'S100')) + if len(response.json()[apis_urls.metadatasubjectcategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadatasubjectcategoryAPI]).keys(): + apisubjectcategoryname = response.json()[apis_urls.metadatasubjectcategoryAPI][ids]['name'] + apisubjectcategorydescription = response.json()[apis_urls.metadatasubjectcategoryAPI][ids]['description'] + apiresult.add_row(vals=(apisubjectcategoryname, apisubjectcategorydescription)) + else: + apiresult.add_row(vals=("", "")) + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected subject category name: '" + str( + row1["subjectmetadataname"]) + "' is the same as the actual existing '" + str( + row2["subjectcategoryname"]) + "'") + assert str(row1["subjectmetadataname"]) == str( + row2["subjectcategoryname"]), "subject category name is not correct!" + logger.info("assertion passed!") + logger.info("asserting the expected subject category description: '" + str( + row1["subjectmetadatadescription"]) + "' is the same as the actual existing '" + str( + row2["subjectcategorydescription"]) + "'") + assert str(row1["subjectmetadatadescription"]) == str( + row2["subjectcategorydescription"]), "Subject meta-data category description is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing object meta data by get request and put them into a table +# 2) Loop using both the expected and actual tables and assert the data row by row +@Then('the following meta data object category should be existed in the system') +def step_impl(context): + model = getattr(context, "model", None) + logger.info("Then the following meta data object category should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.metadataobjectcategoryAPI, headers=apis_urls.auth_headers) + apiresult = Table(names=('objectcategoryname', 'objectcategorydescription'), dtype=('S100', 'S100')) + + if len(response.json()[apis_urls.metadataobjectcategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadataobjectcategoryAPI]).keys(): + apiobjectcategoryname = response.json()[apis_urls.metadataobjectcategoryAPI][ids]['name'] + apiobjectcategorydescription = response.json()[apis_urls.metadataobjectcategoryAPI][ids]['description'] + apiresult.add_row(vals=(apiobjectcategoryname, apiobjectcategorydescription)) + else: + apiresult.add_row(vals=("", "")) + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected object category description: '" + str( + row1["objectmetadataname"]) + "' is the same as the actual existing '" + str( + row2["objectcategoryname"]) + "'") + assert str(row1["objectmetadataname"]) == str( + row2["objectcategoryname"]), "object category name is not correct!" + logger.info("assertion passed!") + logger.info("asserting the expected object category description: '" + str( + row1["objectmetadatadescription"]) + "' is the same as the actual existing '" + str( + row2["objectcategorydescription"]) + "'") + assert str(row1["objectmetadatadescription"]) == str( + row2["objectcategorydescription"]), "object meta-data category description is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing action meta data by get request and put them into a table +# 2) Loop using both the expected and actual tables and assert the data row by row +@Then('the following meta data action category should be existed in the system') +def step_impl(context): + logger.info("Then the following meta data action category should be existed in the system") + + model = getattr(context, "model", None) + response = requests.get(apis_urls.serverURL + apis_urls.metadataactioncategoryAPI, headers=apis_urls.auth_headers) + apiresult = Table(names=('actioncategoryname', 'actioncategorydescription'), dtype=('S100', 'S100')) + if len(response.json()[apis_urls.metadataactioncategoryAPI]) != 0: + for ids in dict(response.json()[apis_urls.metadataactioncategoryAPI]).keys(): + apiactioncategoryname = response.json()[apis_urls.metadataactioncategoryAPI][ids]['name'] + apiactioncategorydescription = response.json()[apis_urls.metadataactioncategoryAPI][ids]['description'] + apiresult.add_row(vals=(apiactioncategoryname, apiactioncategorydescription)) + else: + apiresult.add_row(vals=("", "")) + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected action category description: '" + str( + row1["actionmetadataname"]) + "' is the same as the actual existing '" + str( + row2["actioncategoryname"]) + "'") + + assert str(row1["actionmetadataname"]) == str( + row2["actioncategoryname"]), "action category name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action category description: '" + str( + row1["actionmetadatadescription"]) + "' is the same as the actual existing '" + str( + row2["actioncategorydescription"]) + "'") + + assert str(row1["actionmetadatadescription"]) == str( + row2["actioncategorydescription"]), "action meta-data category description is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# Assert the saved api response flag with the expected flag +@Then('the system should reply the following') +def step_impl(context): + logger.info("Then the system should reply the following:") + model = getattr(context, "model", None) + for row in context.table: + logger.info("asserting the expected api response: '" + row["flag"] + "' and the actual response: '" + + GeneralVariables.api_responseflag['value'] + "'") + assert row["flag"] == GeneralVariables.api_responseflag['value'], "Validation is not correct, Expected: " + row[ + "flag"] + " but the API response was: " + GeneralVariables.api_responseflag['value'] + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/meta_rules.py b/moon_manager/tests/func_tests/features/steps/meta_rules.py new file mode 100644 index 00000000..f56d4d4c --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/meta_rules.py @@ -0,0 +1,335 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import numpy as np +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing meta rule in the system +# 2) Loop by id and delete them +@Given('the system has no meta-rules') +def step_impl(context): + logger.info("Given the system has no meta-rules") + + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.metarulesAPI]) != 0: + for ids in dict(response.json()[apis_urls.metarulesAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.metarulesAPI + "/" + ids, + headers=headers) + +# Step Definition Implementation: +# 1) Get subject, object, action categories ids list by calling the common funtion: get_subjectcategoryid, get_objectcategoryid and get_actioncategoryid +# 2) create the meta rule data jason then post it +@Given('the following meta rule exists') +def step_impl(context): + logger.info("Given the following meta rule exists") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "meta-rule name: '" + row["metarulename"] + "' and meta-rule description: '" + row[ + "metaruledescription"] + "' and subject categories:'" + row[ + "subjectmetadata"] + "' and object categories:'" + row["objectmetadata"] + "' and action categories:'" + + row["actionmetadata"] + "'") + subjectcategoryids = [] + objectcategoryids = [] + actioncategoryids = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row["subjectmetadata"]) < 40 and str(row["subjectmetadata"])!=""): + if(str(row["subjectmetadata"]).find(",")!=-1): + for category in row["subjectmetadata"].split(","): + subjectcategoryids.append(commonfunctions.get_subjectcategoryid(category)) + else: + subjectcategoryids.append(commonfunctions.get_subjectcategoryid(row["subjectmetadata"])) + else: + if(str(row["subjectmetadata"])==""): + subjectcategoryids=[] + else: + subjectcategoryids.append(row["subjectmetadata"]) + + if (len(row["objectmetadata"]) < 40 and str(row["objectmetadata"])!=""): + if(str(row["objectmetadata"]).find(",")!=-1): + for category in row["objectmetadata"].split(","): + objectcategoryids.append(commonfunctions.get_objectcategoryid(category)) + else: + objectcategoryids.append(commonfunctions.get_objectcategoryid(row["objectmetadata"])) + else: + if (str(row["objectmetadata"]) == ""): + objectcategoryids = [] + else: + objectcategoryids.append(row["objectmetadata"]) + + if (len(row["actionmetadata"]) < 40 and str(row["actionmetadata"])!=""): + if(str(row["actionmetadata"]).find(",")!=-1): + for category in row["actionmetadata"].split(","): + actioncategoryids.append(commonfunctions.get_actioncategoryid(category)) + else: + actioncategoryids.append(commonfunctions.get_actioncategoryid(row["actionmetadata"])) + else: + if(str(row["actionmetadata"]) == ""): + actioncategoryids = [] + else: + actioncategoryids.append(row["actionmetadata"]) + + data = { + 'name': row["metarulename"], + 'description': row["metaruledescription"], + 'subject_categories': subjectcategoryids, + 'object_categories': objectcategoryids, + 'action_categories': actioncategoryids + } + response = requests.post(apis_urls.serverURL + apis_urls.metarulesAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get subject, object, action categories ids list by calling the common funtion: get_subjectcategoryid, get_objectcategoryid and get_actioncategoryid +# 2) create the meta rule data jason then post it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following meta-rule') +def step_impl(context): + logger.info("When the user sets to add the following meta-rule") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "meta-rule name: '" + row["metarulename"] + "' and meta-rule description: '" + row[ + "metaruledescription"] + "' and subject categories:'" + row[ + "subjectmetadata"] + "' and object categories:'" + row["objectmetadata"] + "' and action categories:'" + + row["actionmetadata"] + "'") + + subjectcategoryids = [] + objectcategoryids = [] + actioncategoryids = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row["subjectmetadata"]) < 40 and str(row["subjectmetadata"])!=""): + if (str(row["subjectmetadata"]).find(",") != -1): + for category in row["subjectmetadata"].split(","): + subjectcategoryids.append(commonfunctions.get_subjectcategoryid(category)) + else: + subjectcategoryids.append(commonfunctions.get_subjectcategoryid(row["subjectmetadata"])) + else: + subjectcategoryids.append(row["subjectmetadata"]) + + if (len(row["objectmetadata"]) < 40 and str(row["objectmetadata"])!=""): + if (str(row["objectmetadata"]).find(",") != -1): + for category in row["objectmetadata"].split(","): + objectcategoryids.append(commonfunctions.get_objectcategoryid(category)) + else: + objectcategoryids.append(commonfunctions.get_objectcategoryid(row["objectmetadata"])) + else: + objectcategoryids.append(row["objectmetadata"]) + + if (len(row["actionmetadata"]) < 40 and str(row["actionmetadata"])!=""): + if (str(row["actionmetadata"]).find(",") != -1): + for category in row["actionmetadata"].split(","): + actioncategoryids.append(commonfunctions.get_actioncategoryid(category)) + else: + actioncategoryids.append(commonfunctions.get_actioncategoryid(row["actionmetadata"])) + else: + actioncategoryids.append(row["actionmetadata"]) + + + data = { + 'name': row["metarulename"], + 'description': row["metaruledescription"], + 'subject_categories': subjectcategoryids, + 'object_categories': objectcategoryids, + 'action_categories': actioncategoryids + } + + response = requests.post(apis_urls.serverURL + apis_urls.metarulesAPI, headers=headers, + data=json.dumps(data)) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get subject, object, action categories ids list by calling the common funtion: get_subjectcategoryid, get_objectcategoryid and get_actioncategoryid +# 2) create the meta rule data jason then patch the meta rule after searching for it's id. +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following meta-rule') +def step_impl(context): + logger.info("When the user sets to update the following meta-rule") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "meta-rule name: '" + row["metarulename"] + "' which will be updated to metarule name:" + row[ + "updatedmetarulename"] + "' and meta-rule description: '" + row[ + "updatedmetaruledescription"] + "' and subject categories:'" + row[ + "updatedsubjectmetadata"] + "' and object categories:'" + row[ + "updatedobjectmetadata"] + "' and action categories:'" + + row["updatedactionmetadata"] + "'") + + subjectcategoryids = [] + objectcategoryids = [] + actioncategoryids = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row["updatedsubjectmetadata"]) > 40): + subjectcategoryids.append(row["updatedsubjectmetadata"]) + else: + for category in row["updatedsubjectmetadata"].split(","): + subjectcategoryids.append(commonfunctions.get_subjectcategoryid(category)) + + if (len(row["updatedobjectmetadata"]) > 40): + objectcategoryids.append(row["updatedobjectmetadata"]) + else: + for category in row["updatedobjectmetadata"].split(","): + objectcategoryids.append(commonfunctions.get_objectcategoryid(category)) + + if (len(row["updatedactionmetadata"]) > 40): + actioncategoryids.append(row["updatedactionmetadata"]) + else: + for category in row["updatedactionmetadata"].split(","): + actioncategoryids.append(commonfunctions.get_actioncategoryid(category)) + + data = { + 'name': row["updatedmetarulename"], + 'description': row["updatedmetaruledescription"], + 'subject_categories': subjectcategoryids, + 'object_categories': objectcategoryids, + 'action_categories': actioncategoryids + } + + response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.metarulesAPI]).keys(): + if (response.json()[apis_urls.metarulesAPI][ids]['name'] == row["metarulename"]): + response = requests.patch(apis_urls.serverURL + apis_urls.metarulesAPI + '/' + ids, headers=headers, + data=json.dumps(data)) + break + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the meta rule by get request +# 2) Loop by ids and search for the matching meta rule by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following meta-rule') +def step_impl(context): + logger.info("When the user sets to delete the following meta-rule") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info( + "meta-rule name: '" + row["metarulename"] + "'") + response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.metarulesAPI]).keys(): + if (response.json()[apis_urls.metarulesAPI][ids]['name'] == row["metarulename"]): + response = requests.delete(apis_urls.serverURL + apis_urls.metarulesAPI + "/" + ids, + headers=headers) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing action meta data by get request and put them into a table +# 2) Sort the table by meta rule name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following meta-rules should be existed in the system') +def step_impl(context): + logger.info("Then the following meta-rules should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI,headers=apis_urls.auth_headers) + apimetarulesubjectcategoryname = "" + apimetaruleobjectcategoryname = "" + apimetaruleactioncategoryname = "" + apiresult = Table( + names=('metarulename', 'metaruledescription', 'subjectmetadata', 'actionmetadata', 'objectmetadata'), + dtype=('S10', 'S100', 'S100', 'S100', 'S100')) + if len(response.json()[apis_urls.metarulesAPI]) != 0: + for ids in dict(response.json()[apis_urls.metarulesAPI]).keys(): + apimetarulesubjectcategoryname = "" + apimetaruleobjectcategoryname = "" + apimetaruleactioncategoryname = "" + apimetarulename = response.json()[apis_urls.metarulesAPI][ids]['name'] + apimetaruledescription = response.json()[apis_urls.metarulesAPI][ids]['description'] + for categoryid in response.json()[apis_urls.metarulesAPI][ids]['subject_categories']: + if (len(apimetarulesubjectcategoryname) > 2): + apimetarulesubjectcategoryname = apimetarulesubjectcategoryname + ',' + commonfunctions.get_subjectcategoryname( + categoryid) + else: + apimetarulesubjectcategoryname = commonfunctions.get_subjectcategoryname(categoryid) + for categoryid in response.json()[apis_urls.metarulesAPI][ids]['object_categories']: + if (len(apimetaruleobjectcategoryname) > 2): + apimetaruleobjectcategoryname = apimetaruleobjectcategoryname + ',' + commonfunctions.get_objectcategoryname( + categoryid) + else: + apimetaruleobjectcategoryname = commonfunctions.get_objectcategoryname(categoryid) + for categoryid in response.json()[apis_urls.metarulesAPI][ids]['action_categories']: + if (len(apimetaruleactioncategoryname) > 2): + apimetaruleactioncategoryname = apimetaruleactioncategoryname + ',' + commonfunctions.get_actioncategoryname( + categoryid) + else: + apimetaruleactioncategoryname = commonfunctions.get_actioncategoryname(categoryid) + + apiresult.add_row(vals=( + apimetarulename, apimetaruledescription, apimetarulesubjectcategoryname, apimetaruleactioncategoryname, + apimetaruleobjectcategoryname)) + + else: + apiresult.add_row(vals=("", "", "", "", "")) + + apiresult.sort('metarulename') + + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected meta rule name: '" + str( + row1["metarulename"]) + "' is the same as the actual existing '" + str( + row2["metarulename"]) + "'") + assert str(row1["metarulename"]) == str(row2["metarulename"]), "meta-rule name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected meta rule description: '" + str( + row1["metaruledescription"]) + "' is the same as the actual existing '" + str( + row2["metaruledescription"]) + "'") + assert str(row1["metaruledescription"]) == str( + row2["metaruledescription"]), "meta-rule description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject categories: '" + str( + row1["subjectmetadata"]) + "' is the same as the actual existing '" + str( + row2["subjectmetadata"]) + "'") + assert str(row1["subjectmetadata"]) == str(row2["subjectmetadata"]), "subject category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object categories: '" + str( + row1["objectmetadata"]) + "' is the same as the actual existing '" + str( + row2["objectmetadata"]) + "'") + assert str(row1["objectmetadata"]) == str(row2["objectmetadata"]), "object category is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action categories: '" + str( + row1["actionmetadata"]) + "' is the same as the actual existing '" + str( + row2["actionmetadata"]) + "'") + assert str(row1["actionmetadata"]) == str(row2["actionmetadata"]), "action category is not correct!" + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/model.py b/moon_manager/tests/func_tests/features/steps/model.py new file mode 100644 index 00000000..36b16746 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/model.py @@ -0,0 +1,230 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing models in the system +# 2) Loop by id and delete them +@Given('the system has no models') +def step_impl(context): + logger.info("Given the system has no models") + + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.modelAPI]) != 0: + for ids in dict(response.json()[apis_urls.modelAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.modelAPI + "/" + ids, + headers=headers) + +# Step Definition Implementation: +# 1) Get meta rule ids list by calling the common funtion: get_metaruleid +# 2) create the model data jason then post it +@Given('the following model exists') +def step_impl(context): + logger.info("Given the following model exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "model name: '" + row["modelname"] + "' model description: '" + row[ + "modeldescription"] + "' and meta-rules:'" + row[ + "metarule"]+"'") + + metarulesids = [] + + if (len(row["metarule"]) > 35): + metarulesids.append(row["metarule"]) + else: + for metarule in row["metarule"].split(","): + metarulesids.append(commonfunctions.get_metaruleid(metarule)) + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + data = { + 'name': row["modelname"], + 'description': row["modeldescription"], + 'meta_rules': metarulesids + } + response = requests.post(apis_urls.serverURL + apis_urls.modelAPI, headers=headers, + data=json.dumps(data)) + + +# Step Definition Implementation: +# 1) Get meta rule ids list by calling the common funtion: get_metaruleid +# 2) create the model data jason then post it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following model') +def step_impl(context): + logger.info("When the user sets to add the following model") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "model name: '" + row["modelname"] + "' model description: '" + row[ + "modeldescription"] + "' and meta-rules:'" + row[ + "metarule"] + "'") + + metarules = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if(row["metarule"]!=""): + if (len(row["metarule"]) > 35): + metarules.append(row["metarule"]) + else: + for metarule in row["metarule"].split(","): + metarules.append(commonfunctions.get_metaruleid(metarule)) + + data = { + 'name': row["modelname"], + 'description': row["modeldescription"], + 'meta_rules': metarules, + } + else: + data = { + 'name': row["modelname"], + 'description': row["modeldescription"], + 'meta_rules': "", + } + response = requests.post(apis_urls.serverURL + apis_urls.modelAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + + +# Step Definition Implementation: +# 1) Get meta rule ids list by calling the common funtion: get_modelid +# 2) create the model jason then patch the model after searching for it's id. +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following model') +def step_impl(context): + logging.info("When the user sets to update the following model") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "model name: '" + row["modelname"] + "' which will be updated to model name:" + row[ + "updatedmodelname"] + "' and model description: '" + row[ + "updatedmodeldescription"] + "' meta-rules: '"+row["updatedmetarule"] + "'") + + metarules = [] + data={} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + if(row["updatedmetarule"]!=""): + if (len(row["updatedmetarule"]) > 35): + metarules.append(row["updatedmetarule"]) + else: + for metarule in row["updatedmetarule"].split(","): + metarules.append(commonfunctions.get_metaruleid(metarule)) + data = { + 'name': row["updatedmodelname"], + 'description': row["updatedmodeldescription"], + 'meta_rules': metarules, + } + else: + data = { + 'name': row["updatedmodelname"], + 'description': row["updatedmodeldescription"], + 'meta_rules': "", + } + response = requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.modelAPI]).keys(): + if (response.json()[apis_urls.modelAPI][ids]['name'] == row["modelname"]): + response = requests.patch(apis_urls.serverURL + apis_urls.modelAPI+'/'+ids, headers=headers, + data=json.dumps(data)) + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the model by get request +# 2) Loop by ids and search for the matching model by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following model') +def step_impl(context): + logging.info("When the user sets to delete the following model") + model = getattr(context, "model", None) + for row in context.table: + logger.info("model name: '" + row["modelname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("policy name:'" + row["modelname"] + "'") + response = requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.modelAPI]).keys(): + if (response.json()[apis_urls.modelAPI][ids]['name'] == row["modelname"]): + response = requests.delete(apis_urls.serverURL + apis_urls.modelAPI + "/" + ids, + headers=headers) + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing models by get request and put them into a table +# 2) Sort the table by model name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following model should be existed in the system') +def step_impl(context): + logger.info("Then the following model should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.modelAPI, headers=apis_urls.auth_headers) + apimetarulesname="" + apiresult = Table( + names=('modelname', 'modeldescription', 'metarule'), + dtype=('S100', 'S100', 'S100')) + if len(response.json()[apis_urls.modelAPI]) != 0: + for ids in dict(response.json()[apis_urls.modelAPI]).keys(): + apimetarulesname = [] + apimodelname = response.json()[apis_urls.modelAPI][ids]['name'] + apimodeldescription = response.json()[apis_urls.modelAPI][ids]['description'] + for metaruleid in response.json()[apis_urls.modelAPI][ids]['meta_rules']: + apimetarulesname.append(commonfunctions.get_metarulename(metaruleid)) + apiresult.add_row(vals=( + apimodelname, apimodeldescription, ",".join(apimetarulesname))) + else: + apiresult.add_row(vals=("", "", "")) + + apiresult.sort('modelname') + + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected model name: '" + str( + row1["modelname"]) + "' is the same as the actual existing '" + str( + row2["modelname"]) + "'") + assert str(row1["modelname"]) == str(row2["modelname"]), "model name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected model description: '" + str( + row1["modeldescription"]) + "' is the same as the actual existing '" + str( + row2["modeldescription"]) + "'") + assert str(row1["modeldescription"]) == str(row2["modeldescription"]), "model description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected meta rules: '" + str( + row1["metarule"]) + "' is the same as the actual existing '" + str( + row2["metarule"]) + "'") + assert str(row1["metarule"]) == str(row2["metarule"]), "metarule is not correct!" + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/pdp.py b/moon_manager/tests/func_tests/features/steps/pdp.py new file mode 100644 index 00000000..bf839658 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/pdp.py @@ -0,0 +1,248 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing pdps in the system +# 2) Loop by id and delete them +@Given('the system has no pdps') +def step_impl(context): + logger.info("Given the system has no pdps") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.pdpAPI, headers=apis_urls.auth_headers) + pdpjason=apis_urls.pdpAPI+"s" + if len(response.json()[pdpjason]) != 0: + for ids in dict(response.json()[pdpjason]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.pdpAPI + "/" + ids, + headers=headers) + +# Step Definition Implementation: +# 1) Get model id by calling the common funtion: get_policyid +# 2) create the pdp data jason then post it +@Given('the following pdp exists') +def step_impl(context): + logger.info("Given the following pdp exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "pdp name: '" + row["pdpname"] + "' pdp description: '" + row[ + "pdpdescription"] + "' and keystone project:'" + row[ + "keystone_project_id"] + "' and security pipeline '" + row['security_pipeline'] + "'") + policies_list = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['security_pipeline']) > 25): + policies_list = row['security_pipeline'] + else: + for policy in row["security_pipeline"].split(","): + policies_list.append(commonfunctions.get_policyid(policy)) + + data = { + 'name': row["pdpname"], + 'description': row["pdpdescription"], + 'vim_project_id': row['keystone_project_id'], + 'security_pipeline': policies_list + } + response = requests.post(apis_urls.serverURL + apis_urls.pdpAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get policy id by calling the common funtion: get_policyid +# 2) create the pdp jason then patch the policy after searching for it's id. +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following pdp') +def step_impl(context): + logger.info("When the user sets to add the following pdp") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "pdp name: '" + row["pdpname"] + "' pdp description: '" + row[ + "pdpdescription"] + "' and keystone project:'" + row[ + "keystone_project_id"] + "' and security pipeline '" + row['security_pipeline'] + "'") + + policies_list = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + if (row["security_pipeline"] != ""): + if (len(row['security_pipeline']) > 25): + policies_list = row['security_pipeline'] + else: + for policy in row["security_pipeline"].split(","): + policies_list.append(commonfunctions.get_policyid(policy)) + data = { + 'name': row["pdpname"], + 'description': row["pdpdescription"], + 'vim_project_id': row['keystone_project_id'], + 'security_pipeline': policies_list + } + else: + data = { + 'name': row["pdpname"], + 'description': row["pdpdescription"], + 'vim_project_id': row['keystone_project_id'], + 'security_pipeline': "" + } + response = requests.post(apis_urls.serverURL + apis_urls.pdpAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get model id by calling the common funtion: get_policyid +# 2) create the pdp data jason then patch it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following pdp') +def step_impl(context): + logger.info("When the user sets to update the following pdp") + + model = getattr(context, "model", None) + policies_list=[] + for row in context.table: + logger.info( + "pdp name: '" + row["pdpname"] + "' which will be updated to pdp name:" + row[ + "updatedpdpname"] + "' and pdp description: '" + row[ + "updatedpdpdescription"] + "' keystone_project: '" + row["updatedkeystone_project_id"] + "' security pipeline: '"+row["updatedsecurity_pipeline"]+"'") + + policies_list = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['updatedsecurity_pipeline']) > 25): + policies_list = row['updatedsecurity_pipeline'] + else: + for policy in row["updatedsecurity_pipeline"].split(","): + policies_list.append(commonfunctions.get_policyid(policy)) + + data = { + 'name': row["updatedpdpname"], + 'description': row["updatedpdpdescription"], + 'vim_project_id': row['updatedkeystone_project_id'], + 'security_pipeline': policies_list + } + + response = requests.get(apis_urls.serverURL + apis_urls.pdpAPI,headers=apis_urls.auth_headers) + logger.info(response.json()) + pdpjason = apis_urls.pdpAPI + "s" + for ids in dict(response.json()[pdpjason]).keys(): + logger.info(str(response.json()[pdpjason][ids]['name'])) + if (response.json()[pdpjason][ids]['name'] == row["pdpname"]): + logger.info(apis_urls.serverURL + apis_urls.pdpAPI+ '/' + ids) + response = requests.patch(apis_urls.serverURL + apis_urls.pdpAPI+ '/' + ids, headers=headers, + data=json.dumps(data)) + logger.info(response.json()) + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + break + +# Step Definition Implementation: +# 1) Get all the pdps by get request +# 2) Loop by ids and search for the matching pdp by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following pdp') +def step_impl(context): + logging.info("When the user sets to delete the following pdp") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("pdp name:'" + row["pdpname"] + "'") + + response = requests.get(apis_urls.serverURL + apis_urls.pdpAPI,headers=apis_urls.auth_headers) + pdpjason=apis_urls.pdpAPI+"s" + for ids in dict(response.json()[pdpjason]).keys(): + if (response.json()[pdpjason][ids]['name'] == row["pdpname"]): + response = requests.delete(apis_urls.serverURL + apis_urls.pdpAPI + "/" + ids, + headers=headers) + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing pdps by get request and put them into a table +# 2) Sort the table by pdp name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following pdp should be existed in the system') +def step_impl(context): + logger.info("Then the following pdp should be existed in the system") + + response = requests.get(apis_urls.serverURL + apis_urls.pdpAPI,headers=apis_urls.auth_headers) + apiresult = Table( + names=('pdpname', 'pdpdescription', 'keystone_project_id','security_pipeline'), + dtype=('S10', 'S100', 'S100','S100')) + pdp_jason=apis_urls.pdpAPI+"s" + if len(response.json()[pdp_jason]) != 0: + for ids in dict(response.json()[pdp_jason]).keys(): + apipdppolicies = "" + apipdpname = response.json()[pdp_jason][ids]['name'] + apipdpdescription = response.json()[pdp_jason][ids]['description'] + apipdpprojectid = response.json()[pdp_jason][ids]['vim_project_id'] + for policies in response.json()[pdp_jason][ids]['security_pipeline']: + if(len(apipdppolicies)>2): + apipdppolicies = apipdppolicies +','+ commonfunctions.get_policyname(policies) + else: + apipdppolicies=commonfunctions.get_policyname(policies) + + apiresult.add_row(vals=( + apipdpname, apipdpdescription, apipdpprojectid,apipdppolicies)) + + else: + apiresult.add_row(vals=("", "", "","")) + + apiresult.sort('pdpname') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected pdp name: '" + str( + row1["pdpname"]) + "' is the same as the actual existing '" + str( + row2["pdpname"]) + "'") + assert str(row1["pdpname"]) == str(row2["pdpname"]), "pdp name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected pdp description: '" + str( + row1["pdpdescription"]) + "' is the same as the actual existing '" + str( + row2["pdpdescription"]) + "'") + + assert str(row1["pdpdescription"]) == str(row2["pdpdescription"]), "pdp description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected keystone project id description: '" + str( + row1["keystone_project_id"]) + "' is the same as the actual existing '" + str( + row2["keystone_project_id"]) + "'") + assert str(row1["keystone_project_id"]) == str(row2["keystone_project_id"]), "project id is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected security pipeline description: '" + str( + row1["security_pipeline"]) + "' is the same as the actual existing '" + str( + row2["security_pipeline"]) + "'") + assert str(row1["security_pipeline"]) == str(row2["security_pipeline"]), "security_pipeline policies is not correct!" + logger.info("assertion passed!") + diff --git a/moon_manager/tests/func_tests/features/steps/perimeter.py b/moon_manager/tests/func_tests/features/steps/perimeter.py new file mode 100644 index 00000000..a4a53120 --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/perimeter.py @@ -0,0 +1,727 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing subject preimeters in the system +# 2) Loop by id to unlink the policies attached +# 3) Then delete the perimeter itself +@Given('the system has no subject perimeter') +def step_impl(context): + logger.info("Given the system has no subject perimeter") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + response = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI,headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.perimetersubjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimetersubjectAPI]).keys(): + policies_list = response.json()[apis_urls.perimetersubjectAPI][ids]['policy_list'] + for policy in policies_list: + response_delete_policies = requests.delete( + apis_urls.serverURL + "policies/" + policy + "/" + apis_urls.perimetersubjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + response_delete = requests.delete(apis_urls.serverURL + apis_urls.perimetersubjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + + # exit(0) + +# Step Definition Implementation: +# 1) Post subject perimeter using the policy id +@Given('the following subject perimeter exists') +def step_impl(context): + logger.info("Given the following subject perimeter exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject perimeter description: '" + row[ + "subjectperimeterdescription"] # "' and subject perimeter email:'" + row[ + # "subjectperimeteremail"] + "' and subject perimeter password '" + row['subjectperimeterpassword'] + + "' and policies '" + row['policies'] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + policyid="" + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + data = { + 'name': row["subjectperimetername"], + 'description': row["subjectperimeterdescription"], + # 'email': row['subjectperimeteremail'], + # 'password': row['subjectperimeterpassword'], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimetersubjectAPI, headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get all the existing object preimeters in the system +# 2) Loop by id to unlink the policies attached +# 3) Then delete the perimeter itself +@Given('the system has no object perimeter') +def step_impl(context): + logger.info("Given the system has no object perimeter") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + response = requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI,headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.perimeterobjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimeterobjectAPI]).keys(): + policies_list = response.json()[apis_urls.perimeterobjectAPI][ids]['policy_list'] + for policy in policies_list: + response_delete_policies = requests.delete( + apis_urls.serverURL + "policies/" + policy + "/" + apis_urls.perimeterobjectAPI + "/" + ids, + headers=headers) + response_delete = requests.delete(apis_urls.serverURL + apis_urls.perimeterobjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + +# Step Definition Implementation: +# 1) Post object perimeter using the policy id +@Given('the following object perimeter exists') +def step_impl(context): + logger.info("Given the following object perimeter exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row["objectperimetername"] + "' object perimeter description: '" + row[ + "objectperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + + data = { + 'name': row["objectperimetername"], + 'description': row["objectperimeterdescription"], + + } + response = requests.post(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeterobjectAPI, + headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Get all the existing action preimeters in the system +# 2) Loop by id to unlink the policies attached +# 3) Then delete the perimeter itself +@Given('the system has no action perimeter') +def step_impl(context): + logger.info("Given the system has no action perimeter") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI,headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.perimeteractionAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimeteractionAPI]).keys(): + policies_list = response.json()[apis_urls.perimeteractionAPI][ids]['policy_list'] + for policy in policies_list: + response_delete_policies = requests.delete( + apis_urls.serverURL + "policies/" + policy + "/" + apis_urls.perimeteractionAPI + "/" + ids, + headers=headers) + response_delete = requests.delete(apis_urls.serverURL + apis_urls.perimeteractionAPI + "/" + ids, + headers=apis_urls.auth_headers) + + +# Step Definition Implementation: +# 1) Post action perimeter using the policy id +@Given('the following action perimeter exists') +def step_impl(context): + logger.info("Given the following action perimeter exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action perimeter name: '" + row["actionperimetername"] + "' action perimeter description: '" + row[ + "actionperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + policyid="" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + data = { + 'name': row["actionperimetername"], + 'description': row["actionperimeterdescription"], + + } + response = requests.post(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeteractionAPI, + headers=headers, + data=json.dumps(data)) + +# Step Definition Implementation: +# 1) Insert subject perimeter using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following subject perimeter') +def step_impl(context): + logger.info("When the user sets to add the following subject perimeter") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "subject perimeter name: '" + row["subjectperimetername"] + "' subject perimeter description: '" + row[ + "subjectperimeterdescription"] + + # "' and subject perimeter email:'" + row["subjectperimeteremail"] + "' and subject perimeter password '" + row['subjectperimeterpassword'] + + "' and policies '" + row['policies'] + "'") + + policyid = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + data = { + 'name': row["subjectperimetername"], + 'description': row["subjectperimeterdescription"], + # 'email': row['subjectperimeteremail'], + # 'password': row['subjectperimeterpassword'], + } + response = requests.post(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimetersubjectAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing subject perimeter & get its id +# 2) create the new perimeter jason and patch it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following subject perimeter') +def step_impl(context): + logger.info("When the user sets to update the following subject perimeter") + model = getattr(context, "model", None) + policies_list = [] + for row in context.table: + logger.info( + "subject perimeter name: '" + row[ + 'subjectperimetername'] + "' which will be updated to subject perimeter name:'" + row[ + "updatedsubjectperimetername"] + "' subject perimeter description: '" + row[ + "updatedsubjectperimeterdescription"] + + # "' and subject perimeter email:'" + row["updatedsubjectperimeteremail"] + "' and subject perimeter password '" + row['updatedsubjectperimeterpassword'] + "' and policies '" + row['policies'] + "'") + + policyid = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid=commonfunctions.get_policyid(row['policies']) + else: + policyid="" + data = { + 'name': row["updatedsubjectperimetername"], + 'description': row["updatedsubjectperimeterdescription"], + # 'email': row['subjectperimeteremail'], + # 'password': row['subjectperimeterpassword'], + } + response = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimetersubjectAPI]).keys(): + if (response.json()[apis_urls.perimetersubjectAPI][ids]['name'] == row["subjectperimetername"]): + #print(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimetersubjectAPI + '/' + ids) + response = requests.patch(apis_urls.serverURL + apis_urls.perimetersubjectAPI + '/' + ids, + headers=headers,data=json.dumps(data)) + print(response) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing subject perimeter & get its id +# 2) Delete it without having the policy id in the request +@When('the user sets to delete the following subject perimeter') +def step_impl(context): + logging.info("When the user sets to delete the following subject perimeter") + + model = getattr(context, "model", None) + for row in context.table: + headers = { + 'Content-Type': 'application/json', + } + logger.info("subject perimeter name:'" + row["subjectperimetername"] + "'") + response = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimetersubjectAPI]).keys(): + if (response.json()[apis_urls.perimetersubjectAPI][ids]['name'] == row["subjectperimetername"]): + response = requests.delete(apis_urls.serverURL + apis_urls.perimetersubjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing subject perimeter & get its id +# 2) Delete it while having the policy id in the request +@When('the user sets to delete the following subject perimeter for a given policy') +def step_impl(context): + logging.info("the user sets to delete the following subject perimeter for a given policy") + + model = getattr(context, "model", None) + for row in context.table: + headers = { + 'Content-Type': 'application/json', + } + logger.info("subject perimeter name:'" + row["subjectperimetername"] + "' and policy:"+ row["policies"]+"'") + policyid = commonfunctions.get_policyid(row['policies']) + response = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimetersubjectAPI]).keys(): + if (response.json()[apis_urls.perimetersubjectAPI][ids]['name'] == row["subjectperimetername"]): + response = requests.delete(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimetersubjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + logger.info(response.json()) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Insert object perimeter using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following object perimeter') +def step_impl(context): + logger.info("When the user sets to add the following object perimeter") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row["objectperimetername"] + "' object perimeter description: '" + row[ + "objectperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + policies_list = [] + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + else: + policyid="" + data = { + 'name': row["objectperimetername"], + 'description': row["objectperimeterdescription"], + } + response = requests.post(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeterobjectAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing object perimeter & get its id +# 2) create the new perimeter jason and patch it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following object perimeter') +def step_impl(context): + logger.info("When the user sets to update the following object perimeter") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "object perimeter name: '" + row[ + 'objectperimetername'] + "' which will be updated to object perimeter name:" + row[ + "updatedobjectperimetername"] + "' object perimeter description: '" + row[ + "updatedobjectperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + else: + policyid="" + data = { + 'name': row["updatedobjectperimetername"], + 'description': row["updatedobjectperimeterdescription"], + } + response = requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeterobjectAPI]).keys(): + if (response.json()[apis_urls.perimeterobjectAPI][ids]['name'] == row["objectperimetername"]): + response = requests.patch(apis_urls.serverURL + apis_urls.perimeterobjectAPI + '/' + ids, + headers=headers,data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing object perimeter & get its id +# 2) Delete it without having the policy id in the request +@When('the user sets to delete the following object perimeter') +def step_impl(context): + logging.info("When the user sets to delete the following object perimeter") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("object perimeter name:'" + row["objectperimetername"] + "'") + + response = requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeterobjectAPI]).keys(): + if (response.json()[apis_urls.perimeterobjectAPI][ids]['name'] == row["objectperimetername"]): + response = requests.delete(apis_urls.serverURL + apis_urls.perimeterobjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing object perimeter & get its id +# 2) Delete it while having the policy id in the request +@When('the user sets to delete the following object perimeter for a given policy') +def step_impl(context): + logging.info("the user sets to delete the following object perimeter for a given policy") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("object perimeter name:'" + row["objectperimetername"] + "' and policy:"+ row["policies"]+"'") + policyid = commonfunctions.get_policyid(row['policies']) + response = requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeterobjectAPI]).keys(): + if (response.json()[apis_urls.perimeterobjectAPI][ids]['name'] == row["objectperimetername"]): + response = requests.delete(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeterobjectAPI + "/" + ids, + headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Insert action perimeter using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following action perimeter') +def step_impl(context): + logger.info("When the user sets to add the following action perimeter") + + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "action perimeter name: '" + row["actionperimetername"] + "' action perimeter description: '" + row[ + "actionperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + policyid="" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + else: + policyid="" + data = { + 'name': row["actionperimetername"], + 'description': row["actionperimeterdescription"], + + } + response = requests.post( + apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeteractionAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing action perimeter & get its id +# 2) create the new perimeter jason and patch it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following action perimeter') +def step_impl(context): + logger.info("When the user sets to update the following action perimeter") + + model = getattr(context, "model", None) + + for row in context.table: + + logger.info( + "action perimeter name: '" + row[ + 'actionperimetername'] + "' which will be updated to action perimeter name:" + row[ + "updatedactionperimetername"] + "' action perimeter description: '" + row[ + "updatedactionperimeterdescription"] + "' and policies '" + row['policies'] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (row['policies'] != ""): + policyid = commonfunctions.get_policyid(row['policies']) + else: + policyid="" + data = { + 'name': row["updatedactionperimetername"], + 'description': row["updatedactionperimeterdescription"], + } + response = requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeteractionAPI]).keys(): + if (response.json()[apis_urls.perimeteractionAPI][ids]['name'] == row["actionperimetername"]): + response = requests.patch( + apis_urls.serverURL + apis_urls.perimeteractionAPI + '/' + ids, + headers=headers,data=json.dumps(data)) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing action perimeter & get its id +# 2) Delete it without having the policy id in the request +@When('the user sets to delete the following action perimeter') +def step_impl(context): + logging.info("When the user sets to delete the following action perimeter") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("action perimeter name:'" + row["actionperimetername"] + "'") + response = requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeteractionAPI]).keys(): + if (response.json()[apis_urls.perimeteractionAPI][ids]['name'] == row["actionperimetername"]): + response = requests.delete(apis_urls.serverURL + apis_urls.perimeteractionAPI + "/" + ids, + headers=apis_urls.auth_headers) + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Search for the existing action perimeter & get its id +# 2) Delete it while having the policy id in the request +@When('the user sets to delete the following action perimeter for a given policy') +def step_impl(context): + logging.info("the user sets to delete the following action perimeter for a given policy") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("action perimeter name:'" + row["actionperimetername"] + "' and policy:"+ row["policies"]+"'") + policyid = commonfunctions.get_policyid(row['policies']) + response = requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI,headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.perimeteractionAPI]).keys(): + if (response.json()[apis_urls.perimeteractionAPI][ids]['name'] == row["actionperimetername"]): + response = requests.delete(apis_urls.serverURL + "policies/" + policyid + "/" + apis_urls.perimeteractionAPI + "/" + ids, + headers=apis_urls.auth_headers) + + if response.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing subject perimeter by get request and put them into a table +# 2) Sort the table by subject perimeter +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following subject perimeter should be existed in the system') +def step_impl(context): + logger.info("Then the following subject perimeter should be existed in the system") + + response = requests.get(apis_urls.serverURL + apis_urls.perimetersubjectAPI,headers=apis_urls.auth_headers) + apiresult = Table( + names=('subjectperimetername', 'subjectperimeterdescription', + # 'subjectperimeteremail', + # 'subjectperimeterpassword', + 'policies'), + dtype=('S100', 'S100', 'S100')) + + if len(response.json()[apis_urls.perimetersubjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimetersubjectAPI]).keys(): + apipoliciesid = [] + apipolicies = "" + GeneralVariables.assignsubjectperimeterid['value']=ids + apisubjectperimetername = response.json()[apis_urls.perimetersubjectAPI][ids]['name'] + apisubjectperimeterdescription = response.json()[apis_urls.perimetersubjectAPI][ids]['description'] + # apisubjectperimeteremail = response.json()[apis_urls.perimetersubjectAPI][ids]['email'] + # apisubjectperimeterpassword = response.json()[apis_urls.perimetersubjectAPI][ids]['password'] + if (len(response.json()[apis_urls.perimetersubjectAPI][ids]['policy_list']) != 0): + for policies in response.json()[apis_urls.perimetersubjectAPI][ids]['policy_list']: + apipoliciesid.append(commonfunctions.get_policyname(str(policies))) + apipolicies = ",".join(apipoliciesid) + else: + apipolicies = "" + apiresult.add_row(vals=( + apisubjectperimetername, apisubjectperimeterdescription, + # apisubjectperimeteremail,# apisubjectperimeterpassword, + apipolicies)) + else: + apiresult.add_row(vals=("", "", "")) + + apiresult.sort('subjectperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected subject perimeter name: '" + str( + row1["subjectperimetername"]) + "' is the same as the actual existing '" + str( + row2["subjectperimetername"]) + "'") + assert str(row1["subjectperimetername"]) == str( + row2["subjectperimetername"]), "subject perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected subject perimeter description: '" + str( + row1["subjectperimeterdescription"]) + "' is the same as the actual existing '" + str( + row2["subjectperimeterdescription"]) + "'") + assert str(row1["subjectperimeterdescription"]) == str( + row2["subjectperimeterdescription"]), "subject perimeter description is not correct!" + logger.info("assertion passed!") + + # logger.info("asserting the expected subject perimeter email: '" + str( + # row1["subjectperimeteremail"]) + "' is the same as the actual existing '" + str( + # row2["subjectperimeteremail"]) + "'") + # assert str(row1["subjectperimeteremail"]) == str( + # row2["subjectperimeteremail"]), "subject perimeter email is not correct!" + # logger.info("assertion passed!") + # + # logger.info("asserting the expected subject perimeter password: '" + str( + # row1["subjectperimeterpassword"]) + "' is the same as the actual existing '" + str( + # row2["subjectperimeterpassword"]) + "'") + # assert str(row1["subjectperimeterpassword"]) == str( + # row2["subjectperimeterpassword"]), "subject perimeter password is not correct!" + # logger.info("assertion passed!") + + if (str(row1["policies"]).find(',') == -1): + logger.info("asserting the expected policies: '" + str( + row1["policies"]) + "' is the same as the actual existing '" + str( + row2["policies"]) + "'") + logger.info("policies is not correct!") + assert str(row1["policies"]) == str(row2["policies"]), " policies is not correct!" + else: + + logger.info("asserting the expected policies: '" + ','.join( + sorted(str(row1["policies"]).split(','), key=str.lower)) + "' is the same as the actual existing '" + + ','.join(sorted(str(row2["policies"]).split(','), key=str.lower)) + "'") + logger.info("policies is not correct!") + assert ','.join(sorted(str(row1["policies"]).split(','), key=str.lower)) == ','.join( + sorted(str(row2["policies"]).split(','), key=str.lower)), " policies is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing object perimeter by get request and put them into a table +# 2) Sort the table by subject perimeter +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following object perimeter should be existed in the system') +def step_impl(context): + logger.info("Then the following object perimeter should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.perimeterobjectAPI,headers=apis_urls.auth_headers) + apiresult = Table( + names=('objectperimetername', 'objectperimeterdescription', 'policies'), + dtype=('S100', 'S100', 'S100')) + if len(response.json()[apis_urls.perimeterobjectAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimeterobjectAPI]).keys(): + apipolicies = "" + apipoliciesid = [] + apiobjectperimetername = response.json()[apis_urls.perimeterobjectAPI][ids]['name'] + apiobjectperimeterdescription = response.json()[apis_urls.perimeterobjectAPI][ids]['description'] + if (len(response.json()[apis_urls.perimeterobjectAPI][ids]['policy_list']) != 0): + for policies in response.json()[apis_urls.perimeterobjectAPI][ids]['policy_list']: + apipoliciesid.append(commonfunctions.get_policyname(str(policies))) + apipolicies = ",".join(apipoliciesid) + else: + apipolicies = "" + apiresult.add_row(vals=( + apiobjectperimetername, apiobjectperimeterdescription, apipolicies)) + else: + apiresult.add_row(vals=("", "", "")) + + apiresult.sort('objectperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected object perimeter name: '" + str( + row1["objectperimetername"]) + "' is the same as the actual existing '" + str( + row2["objectperimetername"]) + "'") + assert str(row1["objectperimetername"]) == str( + row2["objectperimetername"]), "object perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected object perimeter description: '" + str( + row1["objectperimeterdescription"]) + "' is the same as the actual existing '" + str( + row2["objectperimeterdescription"]) + "'") + assert str(row1["objectperimeterdescription"]) == str( + row2["objectperimeterdescription"]), "object perimeter description is not correct!" + logger.info("assertion passed!") + + if (str(row1["policies"]).find(',') == -1): + logger.info("asserting the expected policies: '" + str( + row1["policies"]) + "' is the same as the actual existing '" + str( + row2["policies"]) + "'") + logger.info("policies is not correct!") + assert str(row1["policies"]) == str(row2["policies"]), " policies is not correct!" + else: + logger.info("asserting the expected policies: '" + ','.join( + sorted(str(row1["policies"]).split(','), key=str.lower)) + "' is the same as the actual existing '" + + ','.join(sorted(str(row2["policies"]).split(','), key=str.lower)) + "'") + logger.info("policies is not correct!") + assert ','.join(sorted(str(row1["policies"]).split(','), key=str.lower)) == ','.join( + sorted(str(row2["policies"]).split(','), key=str.lower)), " policies is not correct!" + logger.info("assertion passed!") + +# Step Definition Implementation: +# 1) Get all the existing subject perimeter by get request and put them into a table +# 2) Sort the table by subject perimeter +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following action perimeter should be existed in the system') +def step_impl(context): + logger.info("Then the following action perimeter should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.perimeteractionAPI,headers=apis_urls.auth_headers) + apiresult = Table( + names=('actionperimetername', 'actionperimeterdescription', 'policies'), + dtype=('S100', 'S100', 'S100')) + if len(response.json()[apis_urls.perimeteractionAPI]) != 0: + for ids in dict(response.json()[apis_urls.perimeteractionAPI]).keys(): + apipolicies = "" + apipoliciesid = [] + apiactionperimetername = response.json()[apis_urls.perimeteractionAPI][ids]['name'] + apiactionperimeterdescription = response.json()[apis_urls.perimeteractionAPI][ids]['description'] + if (len(response.json()[apis_urls.perimeteractionAPI][ids]['policy_list']) != 0): + for policies in response.json()[apis_urls.perimeteractionAPI][ids]['policy_list']: + apipoliciesid.append(commonfunctions.get_policyname(str(policies))) + apipolicies = ",".join(apipoliciesid) + else: + apipolicies = "" + apiresult.add_row(vals=( + apiactionperimetername, apiactionperimeterdescription, apipolicies)) + else: + apiresult.add_row(vals=("", "", "")) + + apiresult.sort('actionperimetername') + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected action perimeter name: '" + str( + row1["actionperimetername"]) + "' is the same as the actual existing '" + str( + row2["actionperimetername"]) + "'") + assert str(row1["actionperimetername"]) == str( + row2["actionperimetername"]), "action perimeter name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected action perimeter description: '" + str( + row1["actionperimeterdescription"]) + "' is the same as the actual existing '" + str( + row2["actionperimeterdescription"]) + "'") + assert str(row1["actionperimeterdescription"]) == str( + row2["actionperimeterdescription"]), "action perimeter description is not correct!" + logger.info("assertion passed!") + + if(str(row1["policies"]).find(',')==-1): + logger.info("asserting the expected policies: '" + str( + row1["policies"]) + "' is the same as the actual existing '" + str( + row2["policies"]) + "'") + logger.info("policies is not correct!") + assert str(row1["policies"]) == str(row2["policies"]), " policies is not correct!" + else: + + logger.info("asserting the expected policies: '" + ','.join(sorted(str(row1["policies"]).split(','),key=str.lower)) + "' is the same as the actual existing '" + + ','.join(sorted(str(row2["policies"]).split(','), key=str.lower)) + "'") + logger.info("policies is not correct!") + assert ','.join(sorted(str(row1["policies"]).split(','),key=str.lower)) == ','.join(sorted(str(row2["policies"]).split(','),key=str.lower)), " policies is not correct!" + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/features/steps/policy.py b/moon_manager/tests/func_tests/features/steps/policy.py new file mode 100644 index 00000000..faa7156a --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/policy.py @@ -0,0 +1,219 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing policies in the system +# 2) Loop by id and delete them +@Given('the system has no policies') +def step_impl(context): + logger.info("Given the system has no policies") + api_responseflag = {'value': False} + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + response = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.policyAPI]) != 0: + for ids in dict(response.json()[apis_urls.policyAPI]).keys(): + response = requests.delete(apis_urls.serverURL + apis_urls.policyAPI + "/" + ids, + headers=headers) + + +# Step Definition Implementation: +# 1) Get model id by calling the common funtion: get_modelid +# 2) create the policy data jason then post it +@Given('the following policy exists') +def step_impl(context): + logger.info("Given the following policy exists") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "policy name: '" + row["policyname"] + "' policy description: '" + row[ + "policydescription"] + "' and model name:'" + row[ + "modelname"] + "' and genre '"+row['genre']+"'") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + data = { + 'name': row["policyname"], + 'description': row["policydescription"], + 'model_id': commonfunctions.get_modelid(row['modelname']), + 'genre': row['genre'] + } + response = requests.post(apis_urls.serverURL + apis_urls.policyAPI, headers=headers, + data=json.dumps(data)) + + +# Step Definition Implementation: +# 1) Get model id by calling the common funtion: get_modelid +# 2) create the policy data jason then post it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following policy') +def step_impl(context): + logger.info("When the user sets to add the following policy") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "policy name: '" + row["policyname"] + "' policy description: '" + row[ + "policydescription"] + "' and model name:'" + row[ + "modelname"] + "' and genre '" + row['genre'] + "'") + policymodel = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['modelname']) > 20): + policymodel=row['modelname'] + else: + policymodel=commonfunctions.get_modelid(row['modelname']) + + data = { + 'name': row["policyname"], + 'description': row["policydescription"], + 'model_id': policymodel, + 'genre': row['genre'] + } + response = requests.post(apis_urls.serverURL + apis_urls.policyAPI, headers=headers, + data=json.dumps(data)) + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + + +# Step Definition Implementation: +# 1) Get model id by calling the common funtion: get_modelid +# 2) create the policy jason then patch the policy after searching for it's id. +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to update the following policy') +def step_impl(context): + logger.info("When the user sets to update the following policy") + model = getattr(context, "model", None) + for row in context.table: + logger.info( + "policy name: '" + row["policyname"] + "' which will be updated to policy name:" + row[ + "updatedpolicyname"] + "' and policy description: '" + row[ + "updatedpolicydescription"] + "' model name: '" + row["updatedmodelname"] + "' and genre: '"+row["updatedgenre"]+"'") + policymodel = "" + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['updatedmodelname']) > 20): + policymodel = row['updatedmodelname'] + else: + policymodel = commonfunctions.get_modelid(row['updatedmodelname']) + + data = { + 'name': row["updatedpolicyname"], + 'description': row["updatedpolicydescription"], + 'model_id': policymodel, + 'genre': row['updatedgenre'] + } + response = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.policyAPI]).keys(): + if (response.json()[apis_urls.policyAPI][ids]['name'] == row["policyname"]): + print(apis_urls.serverURL + apis_urls.policyAPI + '/' + ids) + response = requests.patch(apis_urls.serverURL + apis_urls.policyAPI + '/' + ids, headers=headers, + data=json.dumps(data)) + logger.info(response.json()) + logger.info(response.status_code) + break + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the policy by get request +# 2) Loop by ids and search for the matching policy by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following policy') +def step_impl(context): + logger.info("When the user sets to delete the following policy") + + model = getattr(context, "model", None) + for row in context.table: + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + logger.info("policy name:'" +row["policyname"]+"'") + response = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + for ids in dict(response.json()[apis_urls.policyAPI]).keys(): + if (response.json()[apis_urls.policyAPI][ids]['name'] == row["policyname"]): + GeneralVariables.assignpolicyid['value']=ids + response = requests.delete(apis_urls.serverURL + apis_urls.policyAPI + "/" + ids, + headers=headers) + break + + if response.status_code==200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing policies by get request and put them into a table +# 2) Sort the table by policy name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following policy should be existed in the system') +def step_impl(context): + logger.info("Then the following policy should be existed in the system") + response = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + #print(response) + apiresult = Table( + names=('policyname', 'policydescription', 'modelname','genre'), + dtype=('S100', 'S100', 'S100','S100')) + if len(response.json()[apis_urls.policyAPI]) != 0: + for ids in dict(response.json()[apis_urls.policyAPI]).keys(): + apipolicyname = response.json()[apis_urls.policyAPI][ids]['name'] + apipolicydescription = response.json()[apis_urls.policyAPI][ids]['description'] + apipolicymodel = commonfunctions.get_modelname(response.json()[apis_urls.policyAPI][ids]['model_id']) + apipolicygenre=response.json()[apis_urls.policyAPI][ids]['genre'] + + apiresult.add_row(vals=( + apipolicyname, apipolicydescription, apipolicymodel,apipolicygenre)) + + else: + apiresult.add_row(vals=("", "", "","")) + + apiresult.sort('policyname') + + for row1, row2 in zip(context.table, apiresult): + logger.info("asserting the expected policy name: '" + str( + row1["policyname"]) + "' is the same as the actual existing '" + str( + row2["policyname"]) + "'") + assert str(row1["policyname"]) == str(row2["policyname"]), "policy name is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected policy description: '" + str( + row1["policydescription"]) + "' is the same as the actual existing '" + str( + row2["policydescription"]) + "'") + assert str(row1["policydescription"]) == str(row2["policydescription"]), "policy description is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected genre: '" + str( + row1["genre"]) + "' is the same as the actual existing '" + str( + row2["genre"]) + "'") + assert str(row1["genre"]) == str(row2["genre"]), "genre is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected model name: '" + str( + row1["modelname"]) + "' is the same as the actual existing '" + str( + row2["modelname"]) + "'") + assert str(row1["modelname"]) == str(row2["modelname"]), "model name is not correct!" + logger.info("assertion passed!")
\ No newline at end of file diff --git a/moon_manager/tests/func_tests/features/steps/rules.py b/moon_manager/tests/func_tests/features/steps/rules.py new file mode 100644 index 00000000..4dd85e2c --- /dev/null +++ b/moon_manager/tests/func_tests/features/steps/rules.py @@ -0,0 +1,495 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from behave import * +from Static_Variables import GeneralVariables +from astropy.table import Table, Column +from common_functions import * +import numpy as np +import requests +import json +import logging + +apis_urls = GeneralVariables() +commonfunctions = commonfunctions() + +logger = logging.getLogger(__name__) + +# Step Definition Implementation: +# 1) Get all the existing rules by the policy id +# 2) Loop by assignment id and delete it +@Given('the system has no rules') +def step_impl(context): + logger.info("Given the system has no rules") + + response_policies = requests.get(apis_urls.serverURL + apis_urls.policyAPI, headers=apis_urls.auth_headers) + #logger.info(response_policies.json()) + if len(response_policies.json()[apis_urls.policyAPI]) != 0: + apiruleid = [] + for policies_ids in dict(response_policies.json()[apis_urls.policyAPI]).keys(): + response = requests.get( + apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.rulesAPI + "/", headers=apis_urls.auth_headers) + if len(response.json()[apis_urls.rulesAPI]['rules']) != 0: + for ids in range(len(response.json()[apis_urls.rulesAPI]['rules'])): + apiruleid.append(dict(response.json()[apis_urls.rulesAPI]['rules'][ids])['id']) + for ruleid in apiruleid: + response = requests.delete( + apis_urls.serverURL + "policies/" + policies_ids + "/" + apis_urls.rulesAPI + "/" + ruleid, headers=apis_urls.auth_headers) + +# Step Definition Implementation: +# 1) Add rule using the post request +@Given('the following rule exists') +def step_impl(context): + logger.info("Given the following rule exists") + api_responseflag = {'value': False} + model = getattr(context, "model", None) + for row in context.table: + subjectcategoryidslist = [] + subjectdataidslist = [] + objectcategoryidslist = [] + objectdataidslist = [] + actioncategoryidslist = [] + actiondataidslist = [] + ruleidslist = [] + metaruleids = "" + subjectindex = 0 + objectindex = 0 + actionindex = 0 + logger.info( + "rule '" + row["rule"] + "' and metarule name:'" + row[ + "metarulename"] + "' and instructions: '" + row[ + "instructions"] + "' and policyname:'" + row[ + "policyname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + ruleparameter = row["rule"].split(",") + metarules_response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers) + for metaruleids in dict(metarules_response.json()[apis_urls.metarulesAPI]).keys(): + if (metarules_response.json()[apis_urls.metarulesAPI][metaruleids]['name'] == row["metarulename"]): + meta_rule_id = metaruleids + subjectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['subject_categories'] + objectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['object_categories'] + actioncategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['action_categories'] + break + + index = 0 + for categoryid in subjectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.datasubjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.datasubjectAPI]) != 0: + for ids in data_response.json()[apis_urls.datasubjectAPI][0]['data']: + if (data_response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + for categoryid in objectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataobjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataobjectAPI]) != 0: + for ids in data_response.json()[apis_urls.dataobjectAPI][0]['data']: + if (data_response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + for categoryid in actioncategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataactionAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataactionAPI]) != 0: + for ids in data_response.json()[apis_urls.dataactionAPI][0]['data']: + if (data_response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + data = { + 'meta_rule_id': meta_rule_id, + 'rule': ruleidslist, + 'instructions': [{"decision": row['instructions']}], + 'enabled': 'True' + } + rulesresponse = requests.post(apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.rulesAPI, + headers=headers, + data=json.dumps(data)) + + +# Step Definition Implementation: +# 1) Add subject meta data using the post request +# 2) If the request code was 200 set the api response flag to true else false +@When('the user sets to add the following rules') +def step_impl(context): + logger.info("When the user sets to add the following rules") + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + api_responseflag = {'value': False} + model = getattr(context, "model", None) + for row in context.table: + subjectcategoryidslist = [] + subjectdataidslist = [] + objectcategoryidslist = [] + objectdataidslist = [] + actioncategoryidslist = [] + actiondataidslist = [] + ruleidslist = [] + metaruleids = "" + subjectindex = 0 + objectindex = 0 + actionindex = 0 + logger.info( + "rule '" + row["rule"] + "' and metarule name:'" + row[ + "metarulename"] + "' and instructions: '" + row[ + "instructions"] + "' and policyname:'" + row[ + "policyname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if(row['policyname']=="" or row['policyname']=="000000000000000000000000000000000000000000000000000"): + policyname="Stanford Policy" + else: + policyname=row['policyname'] + policies_id = commonfunctions.get_policyid(policyname) + + if(row["metarulename"]=="" or row["metarulename"]=="000000000000000000000000000000000000000000000000000"): + mata_rule_name="metarule1" + else: + mata_rule_name = row['metarulename'] + + + if (row["rule"] != ""): + ruleparameter = row["rule"].split(",") + metarules_response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers) + for metaruleids in dict(metarules_response.json()[apis_urls.metarulesAPI]).keys(): + if (metarules_response.json()[apis_urls.metarulesAPI][metaruleids]['name'] == mata_rule_name): + meta_rule_id = metaruleids + subjectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['subject_categories'] + objectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['object_categories'] + actioncategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['action_categories'] + break + + index = 0 + for categoryid in subjectcategorieslist: + if (index < len(ruleparameter)): + if (len(ruleparameter[index]) < 30): + if (ruleparameter[index] != ""): + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.datasubjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.datasubjectAPI]) != 0: + for ids in data_response.json()[apis_urls.datasubjectAPI][0]['data']: + if (index < len(ruleparameter)): + if (data_response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)][ + 'name'] == + ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + else: + break + else: + ruleidslist.append("") + index = index + 1 + else: + ruleidslist.append(ruleparameter[index]) + index = index + 1 + for categoryid in objectcategorieslist: + if (index < len(ruleparameter)): + if (len(ruleparameter[index]) < 30): + if (ruleparameter[index] != ""): + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataobjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataobjectAPI]) != 0: + for ids in data_response.json()[apis_urls.dataobjectAPI][0]['data']: + if (index < len(ruleparameter)): + if (data_response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)][ + 'name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + else: + break + else: + ruleidslist.append("") + index = index + 1 + else: + ruleidslist.append(ruleparameter[index]) + index = index + 1 + + for categoryid in actioncategorieslist: + if (index < len(ruleparameter)): + if (len(ruleparameter[index]) < 30): + if (ruleparameter[index] != ""): + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataactionAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataactionAPI]) != 0: + for ids in data_response.json()[apis_urls.dataactionAPI][0]['data']: + if (index < len(ruleparameter)): + if (data_response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)][ + 'name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + else: + break + else: + ruleidslist.append("") + index = index + 1 + else: + ruleidslist.append(ruleparameter[index]) + index = index + 1 + if(row["metarulename"]=="" or row["metarulename"] == "000000000000000000000000000000000000000000000000000"): + meta_rule_id=row["metarulename"] + if (row["policyname"] == "" or row["policyname"] == "000000000000000000000000000000000000000000000000000"): + policies_id = row["policyname"] + data = { + 'meta_rule_id': meta_rule_id, + 'rule': ruleidslist, + 'instructions': [{"decision": row['instructions']}], + 'enabled': 'True' + } + else: + + data = { + 'meta_rule_id': commonfunctions.get_metaruleid(mata_rule_name), + 'rule': [], + 'instructions': [{"decision": row['instructions']}], + 'enabled': 'True' + } + rulesresponse = requests.post(apis_urls.serverURL + "policies/" + str(policies_id) + "/" + apis_urls.rulesAPI, + headers=headers, + data=json.dumps(data)) + logger.info(rulesresponse.json()) + if rulesresponse.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the meta rule by get request +# 2) Loop by ids and search for the matching meta rule by name and delete it +# 3) If the request code was 200 set the api response flag to true else false +@When('the user sets to delete the following rules') +def step_impl(context): + logger.info("When the user sets to delete the following rules") + for row in context.table: + subjectcategoryidslist = [] + subjectdataidslist = [] + objectcategoryidslist = [] + objectdataidslist = [] + actioncategoryidslist = [] + actiondataidslist = [] + ruleidslist = [] + metaruleids = "" + subjectindex = 0 + objectindex = 0 + actionindex = 0 + logger.info( + "rule '" + row["rule"] + "' and metarule name:'" + row[ + "metarulename"] + "' and policyname:'" + row[ + "policyname"] + "'") + + headers = {"Content-Type": "application/json", "X-Api-Key": apis_urls.token} + + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + ruleparameter = row["rule"].split(",") + metarules_response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers) + for metaruleids in dict(metarules_response.json()[apis_urls.metarulesAPI]).keys(): + if (metarules_response.json()[apis_urls.metarulesAPI][metaruleids]['name'] == row["metarulename"]): + meta_rule_id = metaruleids + subjectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['subject_categories'] + objectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['object_categories'] + actioncategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['action_categories'] + break + + index = 0 + for categoryid in subjectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.datasubjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.datasubjectAPI]) != 0: + for ids in data_response.json()[apis_urls.datasubjectAPI][0]['data']: + if (data_response.json()[apis_urls.datasubjectAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + for categoryid in objectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataobjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataobjectAPI]) != 0: + for ids in data_response.json()[apis_urls.dataobjectAPI][0]['data']: + if (data_response.json()[apis_urls.dataobjectAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + for categoryid in actioncategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataactionAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataactionAPI]) != 0: + for ids in data_response.json()[apis_urls.dataactionAPI][0]['data']: + if (data_response.json()[apis_urls.dataactionAPI][0]['data'][str(ids)]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + rulesresponse = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.rulesAPI + "/", headers=apis_urls.auth_headers) + + if len(rulesresponse.json()[apis_urls.rulesAPI]) != 0: + for ids in range(len(rulesresponse.json()[apis_urls.rulesAPI]['rules'])): + if (dict(rulesresponse.json()[apis_urls.rulesAPI]['rules'][ids])[ + 'rule'] == ruleidslist): + ruleid = dict(rulesresponse.json()[apis_urls.rulesAPI]['rules'][ids])['id'] + rulesresponse = requests.delete( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.rulesAPI + "/" + ruleid,headers=apis_urls.auth_headers) + + if rulesresponse.status_code == 200: + GeneralVariables.api_responseflag['value'] = 'True' + else: + GeneralVariables.api_responseflag['value'] = 'False' + +# Step Definition Implementation: +# 1) Get all the existing rules per a given policy, metarule using get request and put them into a table +# 2) Sort the table by policy name +# 3) Loop using both the expected and actual tables and assert the data row by row +@Then('the following rules should be existed in the system') +def step_impl(context): + logger.info("Then the following rule should be existed in the system") + model = getattr(context, "model", None) + apiresult = Table(names=('rule', 'metarule', 'instructions', 'policyname'), + dtype=('S1000', 'S100', 'S100', 'S100')) + + expectedresult = Table(names=('rule', 'metarule', 'instructions', 'policyname'), + dtype=('S1000', 'S100', 'S100', 'S100')) + + for row in context.table: + ruleidslist = [] + apirule = [] + if (len(row['policyname']) > 25): + policies_id = row['policyname'] + else: + policies_id = commonfunctions.get_policyid(row['policyname']) + + ruleparameter = row["rule"].split(",") + metarules_response = requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers) + for metaruleids in dict(metarules_response.json()[apis_urls.metarulesAPI]).keys(): + if (metarules_response.json()[apis_urls.metarulesAPI][metaruleids]['name'] == row["metarulename"]): + meta_rule_id = metaruleids + subjectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['subject_categories'] + objectcategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['object_categories'] + actioncategorieslist = \ + requests.get(apis_urls.serverURL + apis_urls.metarulesAPI, headers=apis_urls.auth_headers).json()[apis_urls.metarulesAPI][ + metaruleids]['action_categories'] + + index = 0 + for categoryid in subjectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.datasubjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.datasubjectAPI]) != 0: + for ids in data_response.json()[apis_urls.datasubjectAPI][0]['data']: + if (data_response.json()[apis_urls.datasubjectAPI][0]['data'][ids]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + for categoryid in objectcategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataobjectAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataobjectAPI]) != 0: + for ids in data_response.json()[apis_urls.dataobjectAPI][0]['data']: + if (data_response.json()[apis_urls.dataobjectAPI][0]['data'][ids]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + + for categoryid in actioncategorieslist: + data_response = requests.get( + apis_urls.serverURL + "policies/" + policies_id + "/" + apis_urls.dataactionAPI + "/" + categoryid, headers=apis_urls.auth_headers) + if len(data_response.json()[apis_urls.dataactionAPI]) != 0: + for ids in data_response.json()[apis_urls.dataactionAPI][0]['data']: + if (data_response.json()[apis_urls.dataactionAPI][0]['data'][ids]['name'] == ruleparameter[ + index]): + ruleidslist.append(ids) + index = index + 1 + expectedresult.add_row(vals=(','.join(ruleidslist), meta_rule_id, row['instructions'], policies_id)) + + if (row['policyname'] != ""): + apipolicyid = commonfunctions.get_policyid( + row['policyname']) + response = requests.get( + apis_urls.serverURL + "policies/" + commonfunctions.get_policyid( + row['policyname']) + "/" + apis_urls.rulesAPI + "/", headers=apis_urls.auth_headers) + + if len(response.json()[apis_urls.rulesAPI]) != 0: + for ids in range(len(response.json()[apis_urls.rulesAPI]['rules'])): + if (dict(response.json()[apis_urls.rulesAPI]['rules'][ids])[ + 'meta_rule_id'] == commonfunctions.get_metaruleid(row['metarulename'])): + apirule = dict(response.json()[apis_urls.rulesAPI]['rules'][ids])['rule'] + #logger.info(dict(dict(response.json()[apis_urls.rulesAPI]['rules'][ids])['instructions'][0])['decision']) + apiinstructions = dict(dict(response.json()[apis_urls.rulesAPI]['rules'][ids])['instructions'][0])['decision'] + apimetaruleid = dict(response.json()[apis_urls.rulesAPI]['rules'][ids])['meta_rule_id'] + apiresult.add_row(vals=(','.join(apirule), apimetaruleid, apiinstructions, apipolicyid)) + + else: + apiresult.add_row(vals=("", "", "", "")) + + else: + apiresult.add_row(vals=("", "", "", "")) + + apiresult.sort('policyname') + expectedresult.sort('policyname') + for row1, row2 in zip(expectedresult, apiresult): + logger.info("asserting the expected rule: '" + str( + row1["rule"]) + "' is the same as the actual existing '" + str( + row2["rule"]) + "'") + assert str(row1["rule"]) == str(row2["rule"]), "rule is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected instructions: '" + str( + row1["instructions"]) + "' is the same as the actual existing '" + str( + row2["instructions"]) + "'") + assert str(row1["instructions"]) == str(row2["instructions"]), "instructions is not correct!" + logger.info("assertion passed!") + + logger.info("asserting the expected metarule: '" + str( + row1["metarule"]) + "' is the same as the actual existing '" + str( + row2["metarule"]) + "'") + assert str(row1["metarule"]) == str(row2["metarule"]), "metarule is not correct!" + logger.info("assertion passed!") diff --git a/moon_manager/tests/func_tests/run.sh b/moon_manager/tests/func_tests/run.sh new file mode 100755 index 00000000..f67ba8c6 --- /dev/null +++ b/moon_manager/tests/func_tests/run.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# pip install behave astropy + +mkdir -p logs + +echo -e "\033[31massignments.feature\033[m" +behave --junit features/assignments.feature | grep -vE "^ " +echo -e "\033[31mdata.feature\033[m" +behave --junit features/data.feature | grep -vE "^ " +echo -e "\033[31mmeta_data.feature\033[m" +behave --junit features/meta_data.feature | grep -vE "^ " +echo -e "\033[31mmeta_rules.feature\033[m" +behave --junit features/meta_rules.feature | grep -vE "^ " +echo -e "\033[31mmodel.feature\033[m" +behave --junit features/model.feature | grep -vE "^ " +echo -e "\033[31mpartner.feature\033[m" +behave --junit features/partner.feature | grep -vE "^ " +echo -e "\033[31mpdp.feature\033[m" +behave --junit features/pdp.feature | grep -vE "^ " +echo -e "\033[31mperimeter.feature\033[m" +behave --junit features/perimeter.feature | grep -vE "^ " +echo -e "\033[31mpolicy.feature\033[m" +behave --junit features/policy.feature | grep -vE "^ " +echo -e "\033[31mrules.feature\033[m" +behave --junit features/rules.feature | grep -vE "^ " diff --git a/moon_manager/tests/functional_pod/conftest.py b/moon_manager/tests/functional_pod/conftest.py deleted file mode 100644 index b5811755..00000000 --- a/moon_manager/tests/functional_pod/conftest.py +++ /dev/null @@ -1,12 +0,0 @@ -import pytest - -print("ANALYSING CONFTEST") - - -@pytest.fixture -def context(): - print("CREATING CONTEXT") - yield { - "hostname": "manager", - "port": 8082, - } diff --git a/moon_manager/tests/functional_pod/json/mls.json b/moon_manager/tests/functional_pod/json/mls.json deleted file mode 100644 index 01ef6deb..00000000 --- a/moon_manager/tests/functional_pod/json/mls.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "pdps": [{"name" : "pdp_mls", "keystone_project_id" : "", "description": "", "policies": [{"name": "MLS policy example"}]}], - - "policies":[{ "name": "MLS policy example", "genre": "authz", "description": "", "model": {"name": "MLS"} , "mandatory" :false , "override":true}], - - "models":[{"name":"MLS", "description":"","meta_rules": [{"name" : "mls"}], "override":true}], - - - - - - "subjects": [{ "name":"adminuser", "description": "", "extra": {}, "policies": [{ "name": "MLS policy example"}]} , - { "name": "user1", "description": "", "extra": {}, "policies": [{ "name": "MLS policy example"}] }, - { "name": "user2", "description": "", "extra": {}, "policies": [{ "name": "MLS policy example"}] }], - - "subject_categories": [{ "name":"subject-security-level", "description": "" }], - - "subject_data": [{ "name":"low", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "subject-security-level"}}, - { "name":"medium", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "subject-security-level"}}, - { "name":"high", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "subject-security-level"}}], - - "subject_assignments":[{ "subject" : {"name": "adminuser"}, "category" : {"name": "subject-security-level"}, "assignments": [{"name" : "high"}]}, - { "subject" : {"name": "user1"}, "category" : {"name": "subject-security-level"}, "assignments": [{"name" : "medium"}] }], - - - - - - - "objects": [{ "name":"vm0", "description": "", "extra": {}, "policies": [{"name": "MLS policy example"}]} , - {"name": "vm1", "description": "", "extra": {}, "policies": [{"name": "MLS policy example"}]} ], - - "object_categories": [{"name":"object-security-level", "description": ""}], - - "object_data": [{ "name":"low", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "object-security-level"}}, - { "name":"medium", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "object-security-level"}}, - { "name":"high", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "object-security-level"}}], - - "object_assignments":[{ "object" : {"name": "vm0"}, "category" : {"name": "object-security-level"}, "assignments": [{"name" : "medium"}]}, - { "object" : {"name": "vm1"}, "category" : {"name": "object-security-level"}, "assignments": [{"name" : "low"}]}], - - - - - - - "actions": [{ "name": "start", "description": "", "extra": {}, "policies": [{"name": "MLS policy example"}]} , - { "name": "stop", "description": "", "extra": {}, "policies": [{"name": "MLS policy example"}]}], - - "action_categories": [{"name":"action-type", "description": ""}], - - "action_data": [{"name":"vm-action", "description": "", "policies": [{"name": "MLS policy example"}], "category": {"name": "action-type"}}, - {"name":"storage-action", "description": "", "policies": [{"name" :"MLS policy example"}], "category": {"name": "action-type"}}], - - "action_assignments":[{ "action" : {"name": "start"}, "category" : {"name": "action-type"}, "assignments": [{"name" : "vm-action"}]}, - { "action" : {"name": "stop"}, "category" : {"name": "action-type"}, "assignments": [{"name" : "vm-action"}]}], - - - - - - - "meta_rules":[{"name":"mls", "description": "", - "subject_categories": [{"name": "subject-security-level"}], - "object_categories": [{"name": "object-security-level"}], - "action_categories": [{"name": "action-type"}] - }], - - "rules": [{ - "meta_rule": {"name" : "mls"}, - "rule": {"subject_data" : [{"name":"high"}], "object_data": [{"name": "medium"}], "action_data": [{"name": "vm-action"}]}, - "policy": {"name" :"MLS policy example"}, - "instructions" : {"decision" : "grant"} - }, { - "meta_rule": {"name" : "mls"}, - "rule": {"subject_data" : [{"name":"high"}], "object_data": [{"name": "low"}], "action_data": [{"name": "vm-action"}]}, - "policy": {"name" :"MLS policy example"}, - "instructions" : {"decision" : "grant"} - }, { - "meta_rule": {"name" : "mls"}, - "rule": {"subject_data" : [{"name":"medium"}], "object_data": [{"name": "low"}], "action_data": [{"name": "vm-action"}]}, - "policy": {"name" :"MLS policy example"}, - "instructions" : {"decision" : "grant"} - }] - - - - -}
\ No newline at end of file diff --git a/moon_manager/tests/functional_pod/json/rbac.json b/moon_manager/tests/functional_pod/json/rbac.json deleted file mode 100644 index a75f291b..00000000 --- a/moon_manager/tests/functional_pod/json/rbac.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "pdps": [{"name" : "pdp_rbac", "keystone_project_id" : "", "description": "", "policies": [{"name": "RBAC policy example"}]}], - - "policies":[{ "name": "RBAC policy example", "genre": "authz", "description": "", "model": {"name": "RBAC"} , "mandatory" :true , "override":true}], - - "models":[{"name":"RBAC", "description":"","meta_rules": [{"name" : "rbac"}], "override":true}], - - - - - - "subjects": [{ "name":"adminuser", "description": "", "extra": {}, "policies": [{ "name": "RBAC policy example"}]} , - { "name": "user1", "description": "", "extra": {}, "policies": [{ "name": "RBAC policy example"}] }, - { "name": "public", "description": "", "extra": {}, "policies": [] }], - - "subject_categories": [{ "name":"role", "description": "" }], - - "subject_data": [{ "name":"admin", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "role"}}, - { "name":"employee", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "role"}}, - { "name":"*", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "role"}}], - - "subject_assignments":[{ "subject" : {"name": "adminuser"}, "category" : {"name": "role"}, "assignments": [{"name" : "admin"}, {"name" : "employee"}, {"name" : "*"}]}, - { "subject" : {"name": "user1"}, "category" : {"name": "role"}, "assignments": [{"name" : "employee"}, {"name" : "*"}] }], - - - - - - - "objects": [{ "name":"vm0", "description": "", "extra": {}, "policies": [{"name": "RBAC policy example"}]} , - {"name": "vm1", "description": "", "extra": {}, "policies": [{"name": "RBAC policy example"}]} ], - - "object_categories": [{"name":"id", "description": ""}], - - "object_data": [{ "name":"vm0", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "id"}}, - { "name":"vm1", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "id"}}, - { "name":"*", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "id"}}], - - "object_assignments":[{ "object" : {"name": "vm0"}, "category" : {"name": "id"}, "assignments": [{"name" : "vm0"}, {"name" : "*"}]}, - { "object" : {"name": "vm1"}, "category" : {"name": "id"}, "assignments": [{"name" : "vm1"}, {"name" : "*"}]}], - - - - - - - "actions": [{ "name": "start", "description": "", "extra": {}, "policies": [{"name": "RBAC policy example"}]} , - { "name": "stop", "description": "", "extra": {}, "policies": [{"name": "RBAC policy example"}]}], - - "action_categories": [{"name":"action-type", "description": ""}], - - "action_data": [{"name":"vm-action", "description": "", "policies": [{"name": "RBAC policy example"}], "category": {"name": "action-type"}}, - {"name":"*", "description": "", "policies": [{"name" :"RBAC policy example"}], "category": {"name": "action-type"}}], - - "action_assignments":[{ "action" : {"name": "start"}, "category" : {"name": "action-type"}, "assignments": [{"name" : "vm-action"}, {"name" : "*"}]}, - { "action" : {"name": "stop"}, "category" : {"name": "action-type"}, "assignments": [{"name" : "vm-action"}, {"name" : "*"}]}], - - - - - - - "meta_rules":[{"name":"rbac", "description": "", - "subject_categories": [{"name": "role"}], - "object_categories": [{"name": "id"}], - "action_categories": [{"name": "action-type"}] - }], - - "rules": [{ - "meta_rule": {"name" : "rbac"}, - "rule": {"subject_data" : [{"name":"admin"}], "object_data": [{"name": "vm0"}], "action_data": [{"name": "vm-action"}]}, - "policy": {"name" :"RBAC policy example"}, - "instructions" : {"decision" : "grant"}, - "enabled": true - }, { - "meta_rule": {"name" : "rbac"}, - "rule": {"subject_data" : [{"name":"employee"}], "object_data": [{"name": "vm1"}], "action_data": [{"name": "vm-action"}]}, - "policy": {"name" :"RBAC policy example"}, - "instructions" : {"decision" : "grant"} - }] - - - - -}
\ No newline at end of file diff --git a/moon_manager/tests/functional_pod/run_functional_tests.sh b/moon_manager/tests/functional_pod/run_functional_tests.sh deleted file mode 100644 index 960e9480..00000000 --- a/moon_manager/tests/functional_pod/run_functional_tests.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash - -if [ -d /data/dist ]; -then - pip install /data/dist/*.tar.gz --upgrade - pip install /data/dist/*.whl --upgrade -fi - - -cd /data/tests/functional_pod -pytest . diff --git a/moon_manager/tests/functional_pod/test_manager.py b/moon_manager/tests/functional_pod/test_manager.py deleted file mode 100644 index 454d861b..00000000 --- a/moon_manager/tests/functional_pod/test_manager.py +++ /dev/null @@ -1,116 +0,0 @@ -import json -import requests - -def test_import_rbac(context): - files = {'file': open('/data/tests/functional_pod/json/rbac.json', 'r')} - req = requests.post("http://{}:{}/import".format( - context.get("hostname"), - context.get("port")) - , files=files) - print(req) - result = req.json() - print(result) - req.raise_for_status() - -def test_import_mls(context): - files = {'file': open('/data/tests/functional_pod/json/mls.json', 'r')} - req = requests.post("http://{}:{}/import".format( - context.get("hostname"), - context.get("port")) - , files=files) - req.raise_for_status() - - -def test_export_rbac(context): - test_import_rbac(context) - req = requests.get("http://{}:{}/export".format( - context.get("hostname"), - context.get("port")), - data={"filename":"/data/tests/functional_pod/json/rbac_export.json"} - ) - req.raise_for_status() - - -def test_export_mls(context): - test_import_mls(context) - req = requests.get("http://{}:{}/export".format( - context.get("hostname"), - context.get("port")), - data={"filename":"/data/tests/functional_pod/json/mls_export.json"} - ) - req.raise_for_status() - - -def get_json(data): - return json.loads(data.decode("utf-8")) - - -def get_pdp(context): - req = requests.get("http://{}:{}/pdp".format( - context.get("hostname"), - context.get("port")), - timeout=3) - pdp = req.json() - return req, pdp - - -def add_pdp(context, data): - req = requests.post("http://{}:{}/pdp".format( - context.get("hostname"), - context.get("port")), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}, - timeout=3) - pdp = req.json() - return req, pdp - - -def delete_pdp(context, key): - req = requests.delete("http://{}:{}/pdp/{}".format( - context.get("hostname"), - context.get("port"), key), - timeout=3) - return req - - -def delete_pdp_without_id(context): - req = requests.delete("http://{}:{}/pdp/{}".format( - context.get("hostname"), - context.get("port"), ""), - timeout=3) - return req - - -def test_get_pdp(context): - req, pdp = get_pdp(context) - assert req.status_code == 200 - assert isinstance(pdp, dict) - assert "pdps" in pdp - - -def test_add_pdp(context): - data = { - "name": "testuser", - "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "keystone_project_id", - "description": "description of testuser" - } - req, pdp = add_pdp(context, data) - assert req.status_code == 200 - assert isinstance(pdp, dict) - value = list(pdp["pdps"].values())[0] - assert "pdps" in pdp - assert value['name'] == "testuser" - assert value["description"] == "description of {}".format("testuser") - assert value["keystone_project_id"] == "keystone_project_id" - - -def test_delete_pdp(context): - request, pdp = get_pdp(context) - success_req = None - for key, value in pdp['pdps'].items(): - if value['name'] == "testuser": - success_req = delete_pdp(context, key) - break - assert success_req - assert success_req.status_code == 200 diff --git a/moon_manager/tests/functional_pod/test_models.py b/moon_manager/tests/functional_pod/test_models.py deleted file mode 100644 index 8b4ceef5..00000000 --- a/moon_manager/tests/functional_pod/test_models.py +++ /dev/null @@ -1,79 +0,0 @@ -import json -import requests - - -def get_models(context): - req = requests.get("http://{}:{}/models".format( - context.get("hostname"), - context.get("port")), - timeout=3) - models = req.json() - return req, models - - -def add_models(context, name): - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": ["meta_rule_id1", "meta_rule_id2"] - } - req = requests.post("http://{}:{}/models".format( - context.get("hostname"), - context.get("port")), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}, - timeout=3) - models = req.json() - return req, models - - -def delete_models(context, name): - _, models = get_models(context) - request = None - for key, value in models['models'].items(): - if value['name'] == name: - request = requests.delete("http://{}:{}/models/{}".format( - context.get("hostname"), - context.get("port"), - key), - timeout=3) - break - return request - - -def delete_models_without_id(context): - req = requests.delete("http://{}:{}/models/{}".format( - context.get("hostname"), - context.get("port"), - ""), - timeout=3) - return req - - -def test_get_models(context): - req, models = get_models(context) - assert req.status_code == 200 - assert isinstance(models, dict) - assert "models" in models - - -def test_add_models(context): - req, models = add_models(context, "testuser") - assert req.status_code == 200 - assert isinstance(models, dict) - value = list(models["models"].values())[0] - assert "models" in models - assert value['name'] == "testuser" - assert value["description"] == "description of {}".format("testuser") - assert value["meta_rules"][0] == "meta_rule_id1" - - -def test_delete_models(context): - req = delete_models(context, "testuser") - assert req.status_code == 200 - - -def test_delete_models_without_id(context): - req = delete_models_without_id(context) - assert req.status_code == 500 - diff --git a/moon_manager/tests/performance_tests/authz_pipeline.py b/moon_manager/tests/performance_tests/authz_pipeline.py new file mode 100644 index 00000000..7d2b48ce --- /dev/null +++ b/moon_manager/tests/performance_tests/authz_pipeline.py @@ -0,0 +1,115 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from locust import TaskSet, task +import logging +import json + +LOGGER = logging.getLogger("locust") + + +class AuthzPipelineRequests(TaskSet): + token = "" + moon_errors = 0 + moon_requests = 0 + stats_filename = "/tmp/perf_stats.log" + + def on_start(self): + """ on_start is called when a Locust start before any task is scheduled """ + self.moon_errors = [] + + def __del__(self): + """ on_stop is called when the TaskSet is stopping """ + stats = {} + try: + stats = json.loads(open(self.stats_filename).read()) + except Exception: + pass + _num = stats.get("errors", 0) + _num += len(self.moon_errors) + _total = stats.get("total", 0) + _total += self.moon_requests + _list = stats.get("list", []) + _list.extend(self.moon_errors) + _percent = _num * 100 / _total + json.dump({"errors": _num, "total": _total, + "percentage": "{0:.2f}".format(_percent), + "list": _list}, + open(self.stats_filename, "w"), indent=4) + + def get(self, url, status_code=200): + with self.client.get(url, catch_response=True) as response: + self.moon_requests += 1 + if response.status_code != status_code: + self.moon_errors.append((url, f"{response.status_code}/{status_code}")) + response.success() + + @task(10) + def authz_ok1(self): + url = "/authz/{}/{}/{}".format( + "admin", "vm1", "use_image" + ) + self.get(url) + + @task(10) + def authz_ok2(self): + url = "/authz/{}/{}/{}".format( + "admin", "vm1", "get_images" + ) + self.get(url) + + @task(10) + def authz_ok3(self): + url = "/authz/{}/{}/{}".format( + "admin", "vm1", "set_image" + ) + self.get(url) + + @task(10) + def authz_ok4(self): + url = "/authz/{}/{}/{}".format( + "demo", "vm1", "set_image" + ) + self.get(url) + + @task(10) + def authz_ok5(self): + url = "/authz/{}/{}/{}".format( + "demo", "vm1", "get_images" + ) + self.get(url) + + @task(10) + def authz_rule_ko(self): + url = "/authz/{}/{}/{}".format("demo", "vm1", "use_image") + self.get(url, 403) + + @task(10) + def authz_subject_ko(self): + url = "/authz/{}/{}/{}".format("admins", "vm1", "use_image") + self.get(url, 403) + + @task(10) + def authz_object_ko(self): + url = "/authz/{}/{}/{}".format("admin", "vm4", "use_image") + self.get(url, 403) + + @task(10) + def authz_action_ko(self): + url = "/authz/{}/{}/{}".format("admin", "vm1", "use_images") + self.get(url, 403) + + @task(1) + def status(self): + self.client.get("/status/") + + diff --git a/moon_manager/tests/performance_tests/locustfile.py b/moon_manager/tests/performance_tests/locustfile.py new file mode 100644 index 00000000..cf077720 --- /dev/null +++ b/moon_manager/tests/performance_tests/locustfile.py @@ -0,0 +1,26 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from locust import HttpLocust, TaskSet +import authz_pipeline + + +class MoonRequests(TaskSet): + tasks = { + authz_pipeline.AuthzPipelineRequests: 10, + } + + +class MoonUser(HttpLocust): + task_set = MoonRequests + min_wait = 10 + max_wait = 100 diff --git a/moon_manager/tests/performance_tests/policy_rbac.json b/moon_manager/tests/performance_tests/policy_rbac.json new file mode 100644 index 00000000..2f7c704e --- /dev/null +++ b/moon_manager/tests/performance_tests/policy_rbac.json @@ -0,0 +1,411 @@ +{ + "policies": [ + { + "name": "Policy for Locust", + "genre": "authz", + "description": "Policy for Locust", + "model": { + "name": "RBAC" + }, + "mandatory": true, + "override": true + } + ], + "models": [ + { + "name": "RBAC", + "description": "", + "meta_rules": [ + { + "name": "rbac" + } + ], + "override": true + } + ], + "subjects": [ + { + "name": "admin", + "description": "", + "extra": {}, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "demo", + "description": "", + "extra": {}, + "policies": [ + { + "name": "Policy for Locust" + } + ] + } + ], + "subject_categories": [ + { + "name": "role", + "description": "role of a user" + } + ], + "subject_data": [ + { + "name": "admin", + "description": "", + "policies": [], + "category": { + "name": "role" + } + }, + { + "name": "user", + "description": "", + "policies": [], + "category": { + "name": "role" + } + } + ], + "subject_assignments": [ + { + "subject": {"name": "admin"}, + "category": {"name": "role"}, + "assignments": [{"name": "admin"}] + }, + { + "subject": {"name": "admin"}, + "category": {"name": "role"}, + "assignments": [{"name": "user"}] + }, + { + "subject": {"name": "demo"}, + "category": {"name": "role"}, + "assignments": [{"name": "user"}] + } + ], + "objects": [ + { + "name": "vm1", + "description": "", + "extra": {}, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "vm2", + "description": "", + "extra": {}, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "vm3", + "description": "", + "extra": {}, + "policies": [ + { + "name": "Policy for Locust" + } + ] + } + ], + "object_categories": [ + { + "name": "id", + "description": "identification of the object" + } + ], + "object_data": [ + { + "name": "vm1", + "description": "", + "policies": [], + "category": { + "name": "id" + } + }, + { + "name": "vm2", + "description": "", + "policies": [], + "category": { + "name": "id" + } + }, + { + "name": "vm3", + "description": "", + "policies": [], + "category": { + "name": "id" + } + } + ], + "object_assignments": [ + { + "object": {"name": "vm1"}, + "category": {"name": "id"}, + "assignments": [{"name": "vm1"}] + }, + { + "object": {"name": "vm2"}, + "category": {"name": "id"}, + "assignments": [{"name": "vm2"}] + }, + { + "object": {"name": "vm3"}, + "category": {"name": "id"}, + "assignments": [{"name": "vm3"}] + } + ], + "actions": [ + { + "name": "use_image", + "description": "use_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "get_images", + "description": "get_images action for glance", + "extra": { + "component": "glance" + }, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "update_image", + "description": "update_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [ + { + "name": "Policy for Locust" + } + ] + }, + { + "name": "set_image", + "description": "set_image action for glance", + "extra": { + "component": "glance" + }, + "policies": [ + { + "name": "Policy for Locust" + } + ] + } + ], + "action_categories": [ + { + "name": "type", + "description": "" + } + ], + "action_data": [ + { + "name": "read", + "description": "read action", + "policies": [], + "category": { + "name": "type" + } + }, + { + "name": "write", + "description": "write action", + "policies": [], + "category": { + "name": "type" + } + }, + { + "name": "execute", + "description": "execute action", + "policies": [], + "category": { + "name": "type" + } + } + ], + "action_assignments": [ + { + "action": {"name": "use_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "read"}, {"name": "execute"}] + }, + { + "action": {"name": "update_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "read"}, {"name": "write"}] + }, + { + "action": {"name": "set_image"}, + "category": {"name": "type"}, + "assignments": [{"name": "write"}] + }, + { + "action": {"name": "get_images"}, + "category": {"name": "type"}, + "assignments": [{"name": "read"}] + } + ], + "meta_rules": [ + { + "name": "rbac", + "description": "", + "subject_categories": [{"name": "role"}], + "object_categories": [{"name": "id"}], + "action_categories": [{"name": "type"}] + } + ], + "rules": [ + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm1"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm1"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm1"}], + "action_data": [{"name": "execute"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm2"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm2"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "admin"}], + "object_data": [{"name": "vm3"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "user"}], + "object_data": [{"name": "vm1"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "user"}], + "object_data": [{"name": "vm1"}], + "action_data": [{"name": "write"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + }, + { + "meta_rule": {"name": "rbac"}, + "rule": { + "subject_data": [{"name": "user"}], + "object_data": [{"name": "vm2"}], + "action_data": [{"name": "read"}] + }, + "policy": {"name": "Policy for Locust"}, + "instructions": [{"decision": "grant"}], + "enabled": true + } + ], + "checks": { + "granted": [ + ["admin", "vm1", "get_images"], + ["admin", "vm1", "set_image"], + ["admin", "vm1", "use_image"], + ["admin", "vm2", "get_images"], + ["admin", "vm2", "set_image"], + ["admin", "vm3", "get_images"], + ["user", "vm1", "get_images"], + ["user", "vm1", "set_image"], + ["user", "vm2", "get_images"], + ["user", "vm1", "get_images"] + ], + "denied": [ + ["admin", "vm2", "update_image"], + ["admin", "vm3", "set_image"], + ["admin", "vm3", "update_image"], + ["user", "vm1", "update_image"], + ["user", "vm2", "set_image"], + ["user", "vm2", "update_image"], + ["user", "vm1", "use_image"], + ["user", "vm2", "use_image"], + ["user", "vm3", "get_images"], + ["user", "vm3", "set_image"], + ["user", "vm3", "update_image"] + ] + } +}
\ No newline at end of file diff --git a/moon_manager/tests/performance_tests_policies/actions.py b/moon_manager/tests/performance_tests_policies/actions.py new file mode 100644 index 00000000..0f31d645 --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/actions.py @@ -0,0 +1,54 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import json +from locust import TaskSet, task +from uuid import uuid4 +import utils + + +class ActionRequests(TaskSet): + token = "" + + def on_start(self): + """ on_start is called when a Locust start before any task is scheduled """ + utils.login(self) + + def on_stop(self): + """ on_stop is called when the TaskSet is stopping """ + utils.logout(self) + + @task(10) + def actions(self): + policy_id = utils.create_policy(self.client, self.token) + self.client.get("/actions", headers={"X-Api-Key": self.token}) + perimeter_name = "test_action_" + str(uuid4()) + req = self.client.post("/policies/{}/actions".format(policy_id), + headers={"X-Api-Key": self.token}, + data={ + "name": perimeter_name, + "description": "locust test", + }) + content = json.loads(req.content.decode("utf-8")) + subject_id = None + for subject_id, subject_value in content.get("actions", {}).items(): + if subject_value.get("name") == perimeter_name: + break + self.client.delete("/policies/{}/actions/{}".format(policy_id, subject_id), + headers={"X-Api-Key": self.token}) + utils.delete_policy(self.client, self.token, policy_id) + + @task(1) + def status(self): + self.client.get("/status", headers={"X-Api-Key": self.token}) + + diff --git a/moon_manager/tests/performance_tests_policies/locustfile.py b/moon_manager/tests/performance_tests_policies/locustfile.py new file mode 100644 index 00000000..368801b0 --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/locustfile.py @@ -0,0 +1,32 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from locust import HttpLocust, TaskSet +import subjects +import objects +import actions +import meta_rules + + +class MoonRequests(TaskSet): + tasks = { + subjects.SubjectRequests: 10, + objects.ObjectRequests: 10, + actions.ActionRequests: 10, + meta_rules.MetaRulesRequests: 5 + } + + +class MoonUser(HttpLocust): + task_set = MoonRequests + min_wait = 100 + max_wait = 1000 diff --git a/moon_manager/tests/performance_tests_policies/meta_rules.py b/moon_manager/tests/performance_tests_policies/meta_rules.py new file mode 100644 index 00000000..e9d85944 --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/meta_rules.py @@ -0,0 +1,80 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from locust import TaskSet, task +import json +from uuid import uuid4 +import utils + + +class MetaRulesRequests(TaskSet): + token = "" + + def on_start(self): + """ on_start is called when a Locust start before any task is scheduled """ + utils.login(self) + + def on_stop(self): + """ on_stop is called when the TaskSet is stopping """ + utils.logout(self) + + def create_category(self, otype="subject"): + self.client.get("/{}_categories".format(otype), headers={"X-Api-Key": self.token}) + category_name = "test_category_" + str(uuid4()) + req = self.client.post("/{}_categories".format(otype), + headers={"X-Api-Key": self.token}, + data={ + "name": category_name, + "description": "locust {} category tests".format(otype), + }) + content = json.loads(req.content.decode("utf-8")) + for category_id, category_value in content.get("{}_categories".format(otype), {}).items(): + if category_value.get("name") == category_name: + return category_id + + def delete_category(self, category_id, otype="subject"): + self.client.delete("/{}_categories/{}".format(otype, category_id), + headers={"X-Api-Key": self.token}) + + @task(10) + def meta_rules(self): + self.client.get("/meta_rules", headers={"X-Api-Key": self.token}) + subject_category_id = self.create_category("subject") + object_category_id = self.create_category("object") + action_category_id = self.create_category("action") + meta_rule_name = "meta_rule_" + str(uuid4()) + data = { + "name": meta_rule_name, + "subject_categories": [subject_category_id], + "object_categories": [object_category_id], + "action_categories": [action_category_id] + } + req = self.client.post("/meta_rules", + headers={"X-Api-Key": self.token, + "Content-Type": "application/json"}, + data=json.dumps(data) + ) + content = json.loads(req.content.decode("utf-8")) + for meta_rule_id, meta_rule_value in content.get("meta_rules", {}).items(): + if meta_rule_value.get("name") == meta_rule_name: + self.client.delete("/meta_rules/{}".format(meta_rule_id), + headers={"X-Api-Key": self.token}) + break + self.delete_category(subject_category_id, "subject") + self.delete_category(object_category_id, "object") + self.delete_category(action_category_id, "action") + + @task(1) + def status(self): + self.client.get("/status", headers={"X-Api-Key": self.token}) + + diff --git a/moon_manager/tests/performance_tests_policies/objects.py b/moon_manager/tests/performance_tests_policies/objects.py new file mode 100644 index 00000000..24932d70 --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/objects.py @@ -0,0 +1,54 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import json +from locust import TaskSet, task +from uuid import uuid4 +import utils + + +class ObjectRequests(TaskSet): + token = "" + + def on_start(self): + """ on_start is called when a Locust start before any task is scheduled """ + utils.login(self) + + def on_stop(self): + """ on_stop is called when the TaskSet is stopping """ + utils.logout(self) + + @task(10) + def objects(self): + policy_id = utils.create_policy(self.client, self.token) + self.client.get("/objects", headers={"X-Api-Key": self.token}) + perimeter_name = "test_object_" + str(uuid4()) + req = self.client.post("/policies/{}/objects".format(policy_id), + headers={"X-Api-Key": self.token}, + data={ + "name": perimeter_name, + "description": "locust test", + }) + content = json.loads(req.content.decode("utf-8")) + subject_id = None + for subject_id, subject_value in content.get("objects", {}).items(): + if subject_value.get("name") == perimeter_name: + break + self.client.delete("/policies/{}/objects/{}".format(policy_id, subject_id), + headers={"X-Api-Key": self.token}) + utils.delete_policy(self.client, self.token, policy_id) + + @task(1) + def status(self): + self.client.get("/status", headers={"X-Api-Key": self.token}) + + diff --git a/moon_manager/tests/performance_tests_policies/subjects.py b/moon_manager/tests/performance_tests_policies/subjects.py new file mode 100644 index 00000000..cacf04c8 --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/subjects.py @@ -0,0 +1,57 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from locust import TaskSet, task +import json +import logging +from uuid import uuid4 +import utils + +LOGGER = logging.getLogger(__name__) + + +class SubjectRequests(TaskSet): + token = "" + + def on_start(self): + """ on_start is called when a Locust start before any task is scheduled """ + utils.login(self) + + def on_stop(self): + """ on_stop is called when the TaskSet is stopping """ + utils.logout(self) + + @task(10) + def subjects(self): + policy_id = utils.create_policy(self.client, self.token) + self.client.get("/subjects", headers={"X-Api-Key": self.token}) + perimeter_name = "test_subject_" + str(uuid4()) + req = self.client.post("/policies/{}/subjects".format(policy_id), + headers={"X-Api-Key": self.token}, + data={ + "name": perimeter_name, + "description": "locust test", + }) + content = json.loads(req.content.decode("utf-8")) + subject_id = None + for subject_id, subject_value in content.get("subjects", {}).items(): + if subject_value.get("name") == perimeter_name: + break + self.client.delete("/policies/{}/subjects/{}".format(policy_id, subject_id), + headers={"X-Api-Key": self.token}) + utils.delete_policy(self.client, self.token, policy_id) + + @task(1) + def status(self): + self.client.get("/status", headers={"X-Api-Key": self.token}) + + diff --git a/moon_manager/tests/performance_tests_policies/utils.py b/moon_manager/tests/performance_tests_policies/utils.py new file mode 100644 index 00000000..4a721b4c --- /dev/null +++ b/moon_manager/tests/performance_tests_policies/utils.py @@ -0,0 +1,45 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import json +from uuid import uuid4 + + +def login(taskset): + req = taskset.client.get("/auth", auth=("admin", "admin")) + taskset.token = req.content.decode("utf-8").strip('"') + + +def logout(taskset): + pass + + +def log(msg): + open("/tmp/tests.log", 'a').write(str(msg) + "\n") + + +def create_policy(client, token): + policy_name = "test_policy_" + str(uuid4()) + req = client.post("/policies", headers={"X-Api-Key": token}, data={ + "name": policy_name, + "description": "locust test policy", + }) + content = json.loads(req.content.decode("utf-8")) + for policy_key, policy_value in content.get("policies", {}).items(): + if policy_value.get("name") == policy_name: + return policy_key + + +def delete_policy(client, token, policy_id): + client.delete("/policies/{}".format(policy_id), headers={"X-Api-Key": token}) + + diff --git a/moon_manager/tests/unit_python/api/__init__.py b/moon_manager/tests/unit_python/api/__init__.py new file mode 100644 index 00000000..1856aa2c --- /dev/null +++ b/moon_manager/tests/unit_python/api/__init__.py @@ -0,0 +1,12 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + diff --git a/moon_manager/tests/unit_python/api/import_export_utilities.py b/moon_manager/tests/unit_python/api/import_export_utilities.py deleted file mode 100644 index 2ee2627d..00000000 --- a/moon_manager/tests/unit_python/api/import_export_utilities.py +++ /dev/null @@ -1,202 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import api.test_unit_models as test_models -import api.test_policies as test_policies -import api.test_perimeter as test_perimeter -import api.test_meta_data as test_categories -import api.test_data as test_data -import api.test_meta_rules as test_meta_rules -import api.test_assignement as test_assignments -import api.test_rules as test_rules -import logging - -logger = logging.getLogger("moon.manager.test.api." + __name__) - - -def clean_models(client): - req, models = test_models.get_models(client) - for key in models["models"]: - client.delete("/models/{}".format(key)) - - -def clean_policies(client): - req, policies = test_policies.get_policies(client) - for key in policies["policies"]: - req = client.delete("/policies/{}".format(key)) - assert req.status_code == 200 - - -def clean_subjects(client): - subjects = test_perimeter.get_subjects(client) - logger.info("subjects {}".format(subjects)) - for key in subjects[1]["subjects"]: - subject = subjects[1]["subjects"][key] - 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)) - - -def clean_objects(client): - objects = test_perimeter.get_objects(client) - logger.info("objects {}".format(objects)) - for key in objects[1]["objects"]: - object_ = objects[1]["objects"][key] - policy_keys = object_["policy_list"] - logger.info("objects policy_keys {}".format(policy_keys)) - for policy_key in policy_keys: - client.delete("/policies/{}/objects/{}".format(policy_key, key)) - - -def clean_actions(client): - actions = test_perimeter.get_actions(client) - actions = test_perimeter.get_actions(client) - logger.info("actions {}".format(actions)) - for key in actions[1]["actions"]: - action = actions[1]["actions"][key] - policy_keys = action["policy_list"] - logger.info("action policy_keys {}".format(policy_keys)) - for policy_key in policy_keys: - client.delete("/policies/{}/actions/{}".format(policy_key, key)) - - -def clean_subject_categories(client): - req, categories = test_categories.get_subject_categories(client) - logger.info(categories) - for key in categories["subject_categories"]: - client.delete("/subject_categories/{}".format(key)) - - -def clean_object_categories(client): - req, categories = test_categories.get_object_categories(client) - logger.info(categories) - for key in categories["object_categories"]: - client.delete("/object_categories/{}".format(key)) - - -def clean_action_categories(client): - req, categories = test_categories.get_action_categories(client) - logger.info(categories) - for key in categories["action_categories"]: - client.delete("/action_categories/{}".format(key)) - - -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) - logger.info("============= data {}".format(data)) - for data_item in data["subject_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= Deleting {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/subject_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -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) - for data_item in data["object_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= object_data {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/object_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -def clean_action_data(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, data = test_data.get_action_data(client, policy_id=policy_key) - for data_item in data["action_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= action_data {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/action_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -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: - 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)) - - -def clean_subject_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_subject_assignment(client, policy_key) - for key in assignments["subject_assignments"]: - subject_key = assignments["subject_assignments"][key]["subject_id"] - cat_key = assignments["subject_assignments"][key]["category_id"] - data_keys = assignments["subject_assignments"][key]["assignments"] - for data_key in data_keys: - client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, subject_key, - cat_key, data_key)) - - -def clean_object_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_object_assignment(client, policy_key) - for key in assignments["object_assignments"]: - object_key = assignments["object_assignments"][key]["object_id"] - cat_key = assignments["object_assignments"][key]["category_id"] - data_keys = assignments["object_assignments"][key]["assignments"] - for data_key in data_keys: - client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_key, object_key, - cat_key, data_key)) - - -def clean_action_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_action_assignment(client, policy_key) - for key in assignments["action_assignments"]: - action_key = assignments["action_assignments"][key]["action_id"] - cat_key = assignments["action_assignments"][key]["category_id"] - data_keys = assignments["action_assignments"][key]["assignments"] - for data_key in data_keys: - 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) - rules = rules["rules"]["rules"] - for rule_key in rules: - req = client.delete("/policies/{}/rules/{}".format(policy_key, rule_key["id"])) - - -def clean_all(client): - clean_rules(client) - - clean_subject_assignments(client) - clean_object_assignments(client) - clean_action_assignments(client) - - - clean_subject_data(client) - clean_object_data(client) - clean_action_data(client) - - clean_actions(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) - clean_meta_rule(client)
\ No newline at end of file diff --git a/moon_manager/tests/unit_python/api/meta_data_test.py b/moon_manager/tests/unit_python/api/meta_data_test.py deleted file mode 100644 index 8609f0b5..00000000 --- a/moon_manager/tests/unit_python/api/meta_data_test.py +++ /dev/null @@ -1,238 +0,0 @@ -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: - req = client.delete("/subject_categories/{}".format(key)) - break - return req - - -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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - - -#--------------------------------------------------------------------------- -#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: - req = client.delete("/object_categories/{}".format(key)) - break - return req - - -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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - - -#--------------------------------------------------------------------------- -#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: - req = client.delete("/action_categories/{}".format(key)) - break - return req - - -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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 diff --git a/moon_manager/tests/unit_python/api/meta_rules_test.py b/moon_manager/tests/unit_python/api/meta_rules_test.py deleted file mode 100644 index a87c16f3..00000000 --- a/moon_manager/tests/unit_python/api/meta_rules_test.py +++ /dev/null @@ -1,162 +0,0 @@ -import json -import api.utilities as utilities - - -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): - data = { - "name": name, - "subject_categories": ["subject_category_id1", - "subject_category_id2"], - "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 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): - data = { - "name": name, - "subject_categories": ["subject_category_id1_update", - "subject_category_id2_update"], - "object_categories": ["object_category_id1_update"], - "action_categories": ["action_category_id1_update"] - } - 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" - assert value["subject_categories"][0] == "subject_category_id1" - assert value["object_categories"][0] == "object_category_id1" - assert value["action_categories"][0] == "action_category_id1" - - -def test_add_meta_rules_with_empty_user(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "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 == 500 - assert json.loads(req.data)["message"] == "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 == 500 - assert json.loads(req.data)["message"] == '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 == 500 - - -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 - value = list(req_update[1]["meta_rules"].values())[0] - assert value["subject_categories"][0] == "subject_category_id1_update" - 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 == 500 - - -def test_update_meta_rules_without_user(): - client = utilities.register_client() - req_update = update_meta_rules(client, "", "") - assert req_update[0].status_code == 500 - assert json.loads(req_update[0].data)["message"] == "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 == 500 - assert json.loads(req_update[0].data)["message"] == "Empty Container" diff --git a/moon_manager/tests/unit_python/api/test_assignement.py b/moon_manager/tests/unit_python/api/test_assignement.py index b56fb420..3a127477 100644 --- a/moon_manager/tests/unit_python/api/test_assignement.py +++ b/moon_manager/tests/unit_python/api/test_assignement.py @@ -1,19 +1,60 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +from uuid import uuid4 +import pytest import api.utilities as utilities -import json from helpers import data_builder as builder -from uuid import uuid4 +from moon_utilities import exceptions + + +def delete_assignment_based_on_parameters(type, policy_id, pre_id=None, cat_id=None, data_id=None): + if type in ["subject_assignments", "object_assignments", "action_assignments"] and policy_id: + url = "/policies/" + policy_id + "/" + type + if pre_id: + url += "/" + pre_id + if cat_id: + url += "/" + cat_id + if data_id: + url += "/" + data_id + else: + return "" + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, url, headers=auth_headers) + return req # subject_categories_test -def get_subject_assignment(client, policy_id): - req = client.get("/policies/{}/subject_assignments".format(policy_id)) +def get_subject_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/subject_assignments".format(policy_id), headers=auth_headers) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def add_subject_assignment(client): +def add_subject_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -27,34 +68,41 @@ def add_subject_assignment(client): "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'}) + req = hug.test.post(assignments, "/policies/{}/subject_assignments/".format(policy_id), + body=data, headers=auth_headers) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def add_subject_assignment_without_cat_id(client): +def add_subject_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} 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'}) + req = hug.test.post(assignments, "/policies/{}/subject_assignments".format("1111"), body=data, + headers=auth_headers) 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)) +def delete_subject_assignment(policy_id, sub_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/subject_assignments/{}/{}/{}".format( + policy_id, sub_id, cat_id, data_id), headers=auth_headers) return req def test_add_subject_assignment(): - client = utilities.register_client() - req, subject_assignment = add_subject_assignment(client) - assert req.status_code == 200 + req, subject_assignment = add_subject_assignment() + assert req.status == hug.HTTP_200 assert isinstance(subject_assignment, dict) assert "subject_assignments" in subject_assignment @@ -62,50 +110,97 @@ def test_add_subject_assignment(): # def test_add_subject_assignment_without_cat_id(): # client = utilities.register_client() # req, subject_assignment = add_subject_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_get_subject_assignment(): - 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 + req, subject_assignment = get_subject_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(subject_assignment, dict) assert "subject_assignments" in subject_assignment def test_delete_subject_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_subject_assignment() - req, subject_assignment = get_subject_assignment(client, policy_id) + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_subject_assignment( + policy_id, + value[_id]['subject_id'], + value[_id]['category_id'], + value[_id]['assignments'][0]) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) value = subject_assignment["subject_assignments"] _id = list(value.keys())[0] - success_req = delete_subject_assignment(client, - policy_id, - value[_id]['subject_id'], - value[_id]['category_id'], - value[_id]['assignments'][0]) - assert success_req.status_code == 200 + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id, + value[_id]['subject_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id, + value[_id]['subject_id'], + value[_id]['category_id']) + assert success_req.status == hug.HTTP_200 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 == 404 + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_subject_assignment("", "id1", "111", "data_id1") + + assert '400: Policy Unknown' == str(exception_info.value) + + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" # --------------------------------------------------------------------------- # object_categories_test -def get_object_assignment(client, policy_id): - req = client.get("/policies/{}/object_assignments".format(policy_id)) +def get_object_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/object_assignments".format(policy_id), headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def add_object_assignment(client): +def add_object_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -120,84 +215,135 @@ def add_object_assignment(client): "data_id": data_id } - req = client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/object_assignments".format(policy_id), + body=data, headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def add_object_assignment_without_cat_id(client): +def add_object_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} data = { "id": "object_id", "category_id": "", "data_id": "data_id" } - req = client.post("/policies/{}/object_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/object_assignments".format("1111"), + body=data, headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id): - req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_id, obj_id, cat_id, data_id)) +def delete_object_assignment(policy_id, obj_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/object_assignments/{}/{}/{}".format( + policy_id, obj_id, cat_id, data_id), headers=auth_headers) return req def test_get_object_assignment(): 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 + + req, object_assignment = get_object_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(object_assignment, dict) assert "object_assignments" in object_assignment def test_add_object_assignment(): - client = utilities.register_client() - req, object_assignment = add_object_assignment(client) - assert req.status_code == 200 + req, object_assignment = add_object_assignment() + assert req.status == hug.HTTP_200 assert "object_assignments" in object_assignment # def test_add_object_assignment_without_cat_id(): # client = utilities.register_client() # req, object_assignment = add_object_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_delete_object_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_object_assignment() - req, object_assignment = get_object_assignment(client, policy_id) + req, object_assignment = get_object_assignment(policy_id) value = object_assignment["object_assignments"] _id = list(value.keys())[0] - success_req = delete_object_assignment(client, - policy_id, + success_req = delete_object_assignment(policy_id, value[_id]['object_id'], value[_id]['category_id'], value[_id]['assignments'][0]) - assert success_req.status_code == 200 + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id, + value[_id]['object_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id, + value[_id]['object_id'], + value[_id]['category_id']) + assert success_req.status == hug.HTTP_200 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 == 404 + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_object_assignment("", "id1", "111", "data_id1") + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" + assert '400: Policy Unknown' == str(exception_info.value) # --------------------------------------------------------------------------- # action_categories_test -def get_action_assignment(client, policy_id): - req = client.get("/policies/{}/action_assignments".format(policy_id)) +def get_action_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/action_assignments".format(policy_id), headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def add_action_assignment(client): +def add_action_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -211,70 +357,113 @@ def add_action_assignment(client): "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'}) + req = hug.test.post(assignments, "/policies/{}/action_assignments".format(policy_id), + body=data, + headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def add_action_assignment_without_cat_id(client): +def add_action_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} data = { "id": "action_id", "category_id": "", "data_id": "data_id" } - req = client.post("/policies/{}/action_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/action_assignments".format("1111"), + body=data, headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def delete_action_assignment(client, policy_id, action_id, cat_id, data_id): - req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_id, action_id, cat_id, data_id)) +def delete_action_assignment(policy_id, action_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/action_assignments/{}/{}/{}".format( + policy_id, action_id, cat_id, data_id), headers=auth_headers) return req def test_get_action_assignment(): 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 + req, action_assignment = get_action_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(action_assignment, dict) assert "action_assignments" in action_assignment def test_add_action_assignment(): - client = utilities.register_client() - req, action_assignment = add_action_assignment(client) - assert req.status_code == 200 + req, action_assignment = add_action_assignment() + assert req.status == hug.HTTP_200 assert "action_assignments" in action_assignment # def test_add_action_assignment_without_cat_id(): # client = utilities.register_client() # req, action_assignment = add_action_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_delete_action_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_action_assignment() - req, action_assignment = get_action_assignment(client, policy_id) + req, action_assignment = get_action_assignment(policy_id) value = action_assignment["action_assignments"] id = list(value.keys())[0] - success_req = delete_action_assignment(client, - policy_id, + success_req = delete_action_assignment(policy_id, value[id]['action_id'], value[id]['category_id'], value[id]['assignments'][0]) - assert success_req.status_code == 200 + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id, + value[id]['action_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id, + value[id]['action_id'], + value[id]['category_id']) + assert success_req.status == hug.HTTP_200 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 == 404 + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_action_assignment("", "id1", "111", "data_id1") + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" + assert '400: Policy Unknown' == str(exception_info.value) # --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_assignemnt.py b/moon_manager/tests/unit_python/api/test_assignemnt.py deleted file mode 100644 index 22c727af..00000000 --- a/moon_manager/tests/unit_python/api/test_assignemnt.py +++ /dev/null @@ -1,270 +0,0 @@ -import api.utilities as utilities -import json -from helpers import data_builder as builder -from uuid import uuid4 - - -# subject_categories_test - - -def get_subject_assignment(client, policy_id): - req = client.get("/policies/{}/subject_assignments".format(policy_id)) - subject_assignment = utilities.get_json(req.data) - return req, subject_assignment - - -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": 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'}) - subject_assignment = utilities.get_json(req.data) - 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(): - client = utilities.register_client() - req, subject_assignment = add_subject_assignment(client) - assert req.status_code == 200 - assert isinstance(subject_assignment, dict) - assert "subject_assignments" in subject_assignment - - -def test_add_subject_assignment_without_cat_id(): - client = utilities.register_client() - 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(): - 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) - assert "subject_assignments" in subject_assignment - - -def test_delete_subject_assignment(): - client = utilities.register_client() - 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] - success_req = delete_subject_assignment(client, policy_id, value[id]['subject_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -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 == 404 - - -# --------------------------------------------------------------------------- - -# object_categories_test - - -def get_object_assignment(client, policy_id): - req = client.get("/policies/{}/object_assignments".format(policy_id)) - object_assignment = utilities.get_json(req.data) - return req, object_assignment - - -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": "object_id", - "category_id": "", - "data_id": "data_id" - } - 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 - - -def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id): - req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_id, obj_id, cat_id, data_id)) - return req - - -def test_get_object_assignment(): - 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 - assert isinstance(object_assignment, dict) - assert "object_assignments" in object_assignment - - -def test_add_object_assignment(): - client = utilities.register_client() - req, object_assignment = add_object_assignment(client) - assert req.status_code == 200 - assert "object_assignments" in object_assignment - - -def test_add_object_assignment_without_cat_id(): - client = utilities.register_client() - 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 = 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] - success_req = delete_object_assignment(client, policy_id, value[id]['object_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -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 == 404 - - -# --------------------------------------------------------------------------- - -# action_categories_test - - -def get_action_assignment(client, policy_id): - req = client.get("/policies/{}/action_assignments".format(policy_id)) - action_assignment = utilities.get_json(req.data) - return req, action_assignment - - -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": "action_id", - "category_id": "", - "data_id": "data_id" - } - 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 - - -def delete_action_assignment(client, policy_id, action_id, cat_id, data_id): - req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_id, action_id, cat_id, data_id)) - return req - - -def test_get_action_assignment(): - 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 - assert isinstance(action_assignment, dict) - assert "action_assignments" in action_assignment - - -def test_add_action_assignment(): - client = utilities.register_client() - req, action_assignment = add_action_assignment(client) - assert req.status_code == 200 - assert "action_assignments" in action_assignment - - -def test_add_action_assignment_without_cat_id(): - client = utilities.register_client() - 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 = 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] - success_req = delete_action_assignment(client, policy_id, value[id]['action_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -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 == 404 - -# --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_auth.py b/moon_manager/tests/unit_python/api/test_auth.py new file mode 100644 index 00000000..ee59bf5e --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_auth.py @@ -0,0 +1,71 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_204, HTTP_401 +import hug +import base64 +from uuid import uuid4 +from helpers import data_builder as builder + + +def test_get_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + assert get_api_key_for_user("admin") == req.data + headers = {"x-api-key": key} + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_200 + + +def test_del_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + headers = {"x-api-key": key} + req = hug.test.delete(auth, 'auth/', headers=headers) + assert req.status == HTTP_204 + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_401 + assert not get_api_key_for_user("admin") + + +def test_readd_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + headers = {"x-api-key": key} + req = hug.test.delete(auth, 'auth/', headers=headers) + assert req.status == HTTP_204 + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + new_key = req.data + headers = {"x-api-key": new_key} + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_200 + assert get_api_key_for_user("admin") + assert get_api_key_for_user("admin") == new_key + assert get_api_key_for_user("admin") != key + diff --git a/moon_manager/tests/unit_python/api/test_data.py b/moon_manager/tests/unit_python/api/test_data.py index 433f69e6..019a8b45 100644 --- a/moon_manager/tests/unit_python/api/test_data.py +++ b/moon_manager/tests/unit_python/api/test_data.py @@ -1,59 +1,83 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + -import api.utilities as utilities import json -from helpers import data_builder as builder from uuid import uuid4 +import hug +import pytest +from helpers import data_builder as builder +from helpers import policy_helper +from moon_utilities import exceptions + + # subject_categories_test -def get_subject_data(client, policy_id, category_id=None): +def get_subject_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/subject_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/subject_data".format(policy_id), headers=auth_headers) else: - req = client.get("/policies/{}/subject_data/{}".format(policy_id, category_id)) - subject_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/subject_data/{}".format(policy_id, category_id), headers=auth_headers) + subject_data = req.data return req, subject_data -def add_subject_data(client, name): +def add_subject_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + 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 = { + body = { "name": name, "description": "description of {}".format(name) } - 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) + req = hug.test.post(data, "/policies/{}/subject_data/{}".format(policy_id, subject_category_id), + body=json.dumps(body), + headers={'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + subject_data = req.data return req, subject_data -def delete_subject_data(client, policy_id, category_id, data_id): - req = client.delete("/policies/{}/subject_data/{}/{}".format(policy_id,category_id,data_id)) +def delete_subject_data(policy_id, category_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/subject_data/{}/{}".format(policy_id, category_id, + data_id), headers=auth_headers) return req def test_get_subject_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, subject_data = get_subject_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, subject_data = get_subject_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(subject_data, dict) assert "subject_data" in subject_data def test_add_subject_data(): - client = utilities.register_client() - req, subject_data = add_subject_data(client, "testuser") - assert req.status_code == 200 + req, subject_data = add_subject_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(subject_data, dict) value = subject_data["subject_data"]['data'] assert "subject_data" in subject_data @@ -62,73 +86,97 @@ def test_add_subject_data(): assert value[id]['description'] == "description of {}".format("testuser") +def test_add_subject_data_invalid_name(): + with pytest.raises(exceptions.DataContentError) as exception_info: + req, subject_data = add_subject_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError) as exception_info: + req, subject_data = add_subject_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + + def test_delete_subject_data(): - client = utilities.register_client() - subject_category_id, object_category_id, action_category_id, meta_rule_id,policy_id = builder.create_new_policy() - data_id = builder.create_subject_data(policy_id,subject_category_id) - success_req = delete_subject_data(client, policy_id, subject_category_id, data_id ) - assert success_req.status_code == 200 + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + data_id = builder.create_subject_data(policy_id, subject_category_id) + success_req = delete_subject_data(policy_id, subject_category_id, data_id) + assert success_req.status == hug.HTTP_200 def test_add_subject_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, subject_data = add_subject_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_data = add_subject_data("<a>") + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_delete_subject_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_subject_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_subject_data("", "", "") + assert success_req.status == hug.HTTP_405 + # --------------------------------------------------------------------------- # object_categories_test -def get_object_data(client, policy_id, category_id=None): +def get_object_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/object_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/object_data".format(policy_id), headers=auth_headers) else: - req = client.get("/policies/{}/object_data/{}".format(policy_id, category_id)) - object_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/object_data/{}".format(policy_id, category_id), headers=auth_headers) + object_data = req.data return req, object_data -def add_object_data(client, name): +def add_object_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + 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 = { + body = { "name": name, "description": "description of {}".format(name) } - 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) + req = hug.test.post(data, "/policies/{}/object_data/{}".format(policy_id, object_category_id), + body=json.dumps(body), headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + object_data = req.data return req, object_data -def delete_object_data(client, policy_id, category_id, data_id): - req = client.delete("/policies/{}/object_data/{}/{}".format(policy_id, category_id, data_id)) +def delete_object_data(policy_id, category_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/object_data/{}/{}".format(policy_id, category_id, + data_id), headers=auth_headers) return req def test_get_object_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, object_data = get_object_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, object_data = get_object_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(object_data, dict) assert "object_data" in object_data def test_add_object_data(): - client = utilities.register_client() - req, object_data = add_object_data(client, "testuser") - assert req.status_code == 200 + req, object_data = add_object_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(object_data, dict) value = object_data["object_data"]['data'] assert "object_data" in object_data @@ -137,75 +185,100 @@ def test_add_object_data(): assert value[_id]['description'] == "description of {}".format("testuser") -def test_delete_object_data(): - client = utilities.register_client() +def test_add_object_data_invalid_name(): + with pytest.raises(exceptions.DataContentError) as exception_info: + req, object_data = add_object_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError): + req, object_data = add_object_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + +def test_delete_object_data(): subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() data_id = builder.create_object_data(policy_id, object_category_id) - - success_req = delete_object_data(client, policy_id, data_id, object_category_id) - assert success_req.status_code == 200 + success_req = delete_object_data(policy_id, data_id, object_category_id) + assert success_req.status == hug.HTTP_200 def test_add_object_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, subject_data = add_object_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_data = add_object_data("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_delete_object_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_object_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_object_data("", "", "") + assert success_req.status == hug.HTTP_405 + # --------------------------------------------------------------------------- # action_categories_test -def get_action_data(client, policy_id, category_id=None): +def get_action_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/action_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/action_data".format(policy_id), + headers=auth_headers) else: - req = client.get("/policies/{}/action_data/{}".format(policy_id, category_id)) - action_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/action_data/{}".format(policy_id, category_id), + headers=auth_headers) + action_data = req.data return req, action_data -def add_action_data(client, name): +def add_action_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + 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 = { + body = { "name": name, "description": "description of {}".format(name) } - 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) + req = hug.test.post(data, "/policies/{}/action_data/{}".format(policy_id, action_category_id), + body=json.dumps(body), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + action_data = req.data return req, action_data -def delete_action_data(client, policy_id, categorgy_id, data_id): - req = client.delete("/policies/{}/action_data/{}/{}".format(policy_id, categorgy_id, data_id)) +def delete_action_data(policy_id, categorgy_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/action_data/{}/{}".format(policy_id, categorgy_id, + data_id), headers=auth_headers) return req def test_get_action_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, action_data = get_action_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, action_data = get_action_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(action_data, dict) assert "action_data" in action_data def test_add_action_data(): - client = utilities.register_client() - req, action_data = add_action_data(client, "testuser") - assert req.status_code == 200 + req, action_data = add_action_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(action_data, dict) value = action_data["action_data"]['data'] assert "action_data" in action_data @@ -214,26 +287,35 @@ def test_add_action_data(): assert value[id]['description'] == "description of {}".format("testuser") -def test_delete_action_data(): - client = utilities.register_client() +def test_add_action_data_invalid_name(): - subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() - data_id = builder.create_action_data(policy_id, action_category_id) + with pytest.raises(exceptions.DataContentError)as exception_info: + req, action_data = add_action_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError) as exception_info: + req, action_data = add_action_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) - success_req = delete_action_data(client, policy_id, data_id, action_category_id) - assert success_req.status_code == 200 +def test_delete_action_data(): + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + data_id = builder.create_action_data(policy_id, action_category_id) + success_req = delete_action_data(policy_id, data_id, action_category_id) + assert success_req.status == hug.HTTP_200 def test_add_action_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, action_data = add_action_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_data = add_action_data("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_delete_action_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_action_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_action_data("", "", "") + assert success_req.status == hug.HTTP_405 # --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_import.py b/moon_manager/tests/unit_python/api/test_import.py deleted file mode 100644 index af5f753a..00000000 --- a/moon_manager/tests/unit_python/api/test_import.py +++ /dev/null @@ -1,510 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import api.utilities as utilities -import api.test_unit_models as test_models -import api.test_policies as test_policies -import api.test_meta_data as test_categories -import api.test_data as test_data -import api.test_meta_rules as test_meta_rules -import api.test_assignement as test_assignments -import api.test_rules as test_rules -import api.import_export_utilities as import_export_utilities - -import json - - -MODEL_WITHOUT_META_RULES = [ - {"models": [{"name": "test model", "description": "", "meta_rules": []}]}, - {"models": [{"name": "test model", "description": "new description", "meta_rules": [], "override": True}]}, - {"models": [{"name": "test model", "description": "description not taken into account", "meta_rules": [], "override": False}]} - ] - -POLICIES = [ - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "new description not taken into account", "model": {"name" : "test model"}, "mandatory": True}]}, - {"policies": [{"name": "test policy", "genre": "not authz ?", "description": "generates an exception", "model": {"name" : "test model"}, "override": True}]}, - {"models": [{"name": "test model", "description": "", "meta_rules": []}], "policies": [{"name": "test policy", "genre": "not authz ?", "description": "changes taken into account", "model": {"name" : "test model"}, "override": True}]}, -] - -SUBJECTS = [{"subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"subjects": [{"name": "testuser", "description": "new description of the subject", "extra": {"email": "new-email@test.com"}, "policies": [{"name": "test other policy"}]}]}, - {"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"}]}]}, -] - - -ACTIONS = [{"actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"actions": [{"name": "test action", "description": "new description of the action", "extra": {"test": "test extra"}, "policies": [{"name": "test other policy"}]}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": [{"name": "test policy"}]}]}] - - -SUBJECT_CATEGORIES = [{"subject_categories": [{"name": "test subject categories", "description": "subject category description"}]}, - {"subject_categories": [{"name": "test subject categories", "description": "new subject category description"}]}] - - -OBJECT_CATEGORIES = [{"object_categories": [{"name": "test object categories", "description": "object category description"}]}, - {"object_categories": [{"name": "test object categories", "description": "new object category description"}]}] - - -ACTION_CATEGORIES = [{"action_categories": [{"name": "test action categories", "description": "action category description"}]}, - {"action_categories": [{"name": "test action categories", "description": "new action category description"}]}] - -# meta_rules import is needed otherwise the search for data do not work !!! -PRE_DATA = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "good meta rule"}, {"name": "other good meta rule"}]}], - "policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}, {"name": "other test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}, {"name": "other test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}, {"name": "other test action categories", "description": "action category description"}], - "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"}]}, - {"name": "other good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "other test subject categories"}], "object_categories": [{"name": "other test object categories"}], "action_categories": [{"name": "other test action categories"}]}]} - -SUBJECT_DATA = [{"subject_data": [{"name": "not valid subject data", "description": "", "policies": [{}], "category": {}}]}, - {"subject_data": [{"name": "not valid subject data", "description": "", "policies": [{}], "category": {"name": "test subject categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "subject_data": [{"name": "one valid subject data", "description": "description", "policies": [{}], "category": {"name": "test subject categories"}}]}, - {"subject_data": [{"name": "valid subject data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}]}, - {"subject_data": [{"name": "valid subject data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test subject categories"}}]}] - -OBJECT_DATA = [{"object_data": [{"name": "not valid object data", "description": "", "policies": [{}], "category": {}}]}, - {"object_data": [{"name": "not valid object data", "description": "", "policies": [{}], "category": {"name": "test object categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "object_data": [{"name": "one valid object data", "description": "description", "policies": [{}], "category": {"name": "test object categories"}}]}, - {"object_data": [{"name": "valid object data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}]}, - {"object_data": [{"name": "valid object data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test object categories"}}]}] - - -ACTION_DATA = [{"action_data": [{"name": "not valid action data", "description": "", "policies": [{}], "category": {}}]}, - {"action_data": [{"name": "not valid action data", "description": "", "policies": [{}], "category": {"name": "test action categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "action_data": [{"name": "one valid action data", "description": "description", "policies": [{}], "category": {"name": "test action categories"}}]}, - {"action_data": [{"name": "valid action data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}]}, - {"action_data": [{"name": "valid action data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test action categories"}}]}] - - -PRE_META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}]} - -META_RULES = [{"meta_rules" :[{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "not valid category"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]}, - {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "not valid category"}], "action_categories": [{"name": "test action categories"}]}]}, - {"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"}]}], - "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"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}], - "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": [{"name": "test policy"}]}], - "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}], - "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": [{"name": "test policy"}]}], - "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"}]}], - "subject_data": [{"name": "subject data", "description": "test subject data", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "object data", "description": "test object data", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "action_data": [{"name": "action data", "description": "test action data", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}]} - - -SUBJECT_ASSIGNMENTS = [{"subject_assignments": [{"subject": {"name": "unknonw"}, "category" : {"name": "test subject categories"}, "assignments": [{"name": "subject data"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "unknown"}, "assignments": [{"name": "subject data"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category" : {"name": "test subject categories"}, "assignments": [{"name": "unknwon"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "test subject categories"}, "assignments": [{"name": "subject data"}]}]}] - -OBJECT_ASSIGNMENTS = [{"object_assignments": [{"object": {"name": "unknown"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "object data"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "unknown"}, "assignments": [{"name": "object data"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "unknown"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "object data"}]}]}] - -ACTION_ASSIGNMENTS = [{"action_assignments": [{"action": {"name": "unknown"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "action data"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "unknown"}, "assignments": [{"name": "action data"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "unknown"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "action data"}]}]}] - -RULES = [{"rules": [{"meta_rule": {"name": "unknown meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "unknown policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "unknown subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "unknown object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "unknown action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}] - - -def test_import_models_without_new_meta_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - counter = 0 - for models_description in MODEL_WITHOUT_META_RULES: - req = client.post("/import", content_type='application/json', data=json.dumps(models_description)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - req, models = test_models.get_models(client) - models = models["models"] - assert len(list(models.keys())) == 1 - values = list(models.values()) - assert values[0]["name"] == "test model" - if counter == 0: - assert len(values[0]["description"]) == 0 - if counter == 1 or counter == 2: - assert values[0]["description"] == "new description" - counter = counter + 1 - import_export_utilities.clean_all(client) - - -def test_import_policies(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - counter = -1 - for policy_description in POLICIES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(policy_description)) - try: - data = utilities.get_json(req.data) - assert data == "Import ok !" - except Exception: - assert counter == 2 # this is an expected failure - continue - - req, policies = test_policies.get_policies(client) - policies = policies["policies"] - assert len(list(policies.keys())) == 1 - values = list(policies.values()) - assert values[0]["name"] == "test policy" - if counter < 3: - assert values[0]["genre"] == "authz" - assert values[0]["description"] == "description" - else: - assert values[0]["genre"] == "not authz ?" - assert values[0]["description"] == "changes taken into account" - assert len(values[0]["model_id"]) > 0 - import_export_utilities.clean_all(client) - - -def test_import_subject_object_action(): - client = utilities.register_client() - type_elements = ["object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = 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 - clean_method = import_export_utilities.clean_objects - name = "test object" - key_extra = "test" - value_extra = "test extra" - else: - elements = ACTIONS - clean_method = import_export_utilities.clean_actions - name = "test action" - key_extra = "test" - value_extra = "test extra" - - for element in elements: - counter = counter + 1 - if counter == 2 or counter == 4: - clean_method(client) - - - if counter == 3: - req = client.patch("/{}s/{}".format(type_element,perimeter_id), content_type='application/json', - data=json.dumps( - element["{}s".format(type_element)][0])) - else : - req = client.post("/import", content_type='application/json', - data=json.dumps(element)) - if counter < 2: - assert req.status_code == 500 - continue - - try: - data = utilities.get_json(req.data) - except Exception as e: - assert False - #assert counter < 2 # Â this is an expected failure - #continue - - if counter != 3: - assert data == "Import ok !" - get_elements = utilities.get_json(client.get("/"+type_element + "s").data) - get_elements = get_elements[type_element + "s"] - - perimeter_id = list(get_elements.keys())[0] - - assert len(list(get_elements.keys())) == 1 - values = list(get_elements.values()) - assert values[0]["name"] == name - if counter == 2 or counter == 4: - assert values[0]["description"] == "description of the " + type_element - #assert not values[0]["extra"] - if counter == 3: - 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) - - -def test_import_subject_object_action_categories(): - client = utilities.register_client() - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = SUBJECT_CATEGORIES - get_method = test_categories.get_subject_categories - elif type_element == "object": - elements = OBJECT_CATEGORIES - get_method = test_categories.get_object_categories - else: - elements = ACTION_CATEGORIES - get_method = test_categories.get_action_categories - - for element in elements: - req = client.post("/import", content_type='application/json', data=json.dumps(element)) - counter = counter + 1 - data = utilities.get_json(req.data) - assert data == "Import ok !" - req, get_elements = get_method(client) - get_elements = get_elements[type_element + "_categories"] - assert len(list(get_elements.keys())) == 1 - values = list(get_elements.values()) - assert values[0]["name"] == "test " + type_element + " categories" - assert values[0]["description"] == type_element + " category description" - - -def test_import_meta_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - # import some categories - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_META_RULES)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - counter = -1 - for meta_rule in META_RULES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(meta_rule)) - if counter != 3: - assert req.status_code == 500 - continue - else: - data = utilities.get_json(req.data) - assert data == "Import ok !" - assert req.status_code == 200 - - req, meta_rules = test_meta_rules.get_meta_rules(client) - meta_rules = meta_rules["meta_rules"] - key = list(meta_rules.keys())[0] - assert isinstance(meta_rules,dict) - assert meta_rules[key]["name"] == "good meta rule" - assert meta_rules[key]["description"] == "valid meta rule" - assert len(meta_rules[key]["subject_categories"]) == 1 - assert len(meta_rules[key]["object_categories"]) == 1 - assert len(meta_rules[key]["action_categories"]) == 1 - - subject_category_key = meta_rules[key]["subject_categories"][0] - object_category_key = meta_rules[key]["object_categories"][0] - action_category_key = meta_rules[key]["action_categories"][0] - - req, sub_cat = test_categories.get_subject_categories(client) - sub_cat = sub_cat["subject_categories"] - assert sub_cat[subject_category_key]["name"] == "test subject categories" - - req, ob_cat = test_categories.get_object_categories(client) - ob_cat = ob_cat["object_categories"] - assert ob_cat[object_category_key]["name"] == "test object categories" - - req, ac_cat = test_categories.get_action_categories(client) - ac_cat = ac_cat["action_categories"] - assert ac_cat[action_category_key]["name"] == "test action categories" - - import_export_utilities.clean_all(client) - - -def test_import_subject_object_action_assignments(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_ASSIGNMENTS)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - counter = -1 - if type_element == "subject": - datas = SUBJECT_ASSIGNMENTS - get_method = test_assignments.get_subject_assignment - elif type_element == "object": - datas = OBJECT_ASSIGNMENTS - get_method = test_assignments.get_object_assignment - else: - datas = ACTION_ASSIGNMENTS - get_method = test_assignments.get_action_assignment - - for assignments in datas: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(assignments)) - if counter != 3: - assert req.status_code == 500 - continue - else: - assert data == "Import ok !" - assert req.status_code == 200 - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, get_assignments = get_method(client, policy_key) - get_assignments = get_assignments[type_element+"_assignments"] - assert len(get_assignments) == 1 - - -def test_import_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_ASSIGNMENTS)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - counter = -1 - for rule in RULES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(rule)) - - if counter < 5: - assert req.status_code == 500 - continue - - assert req.status_code == 200 - - req, rules = test_rules.test_get_rules() - rules = rules["rules"] - rules = rules["rules"] - assert len(rules) == 1 - rules = rules[0] - assert rules["enabled"] - assert rules["instructions"]["decision"] == "grant" - - req, meta_rules = test_meta_rules.get_meta_rules(client) - assert meta_rules["meta_rules"][list(meta_rules["meta_rules"].keys())[0]]["name"] == "good meta rule" - - -def test_import_subject_object_action_data(): - client = utilities.register_client() - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_DATA)) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = SUBJECT_DATA - get_method = test_data.get_subject_data - get_categories = test_categories.get_subject_categories - elif type_element == "object": - elements = OBJECT_DATA - get_method = test_data.get_object_data - get_categories = test_categories.get_object_categories - else: - elements = ACTION_DATA - get_method = test_data.get_action_data - get_categories = test_categories.get_action_categories - - for element in elements: - req = client.post("/import", content_type='application/json', data=json.dumps(element)) - counter = counter + 1 - if counter == 0 or counter == 1: - assert req.status_code == 500 - continue - assert req.status_code == 200 - data = utilities.get_json(req.data) - assert data == "Import ok !" - - req, policies = test_policies.get_policies(client) - policies = policies["policies"] - req, categories = get_categories(client) - categories = categories[type_element + "_categories"] - case_tested = False - for policy_key in policies.keys(): - policy = policies[policy_key] - for category_key in categories: - 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... - get_elements = get_elements[type_element+"_data"] - if len(get_elements[0]["data"]) == 0: - continue - - if policy["name"] == "test policy": - assert len(get_elements) == 1 - el = get_elements[0] - assert isinstance(el["data"], dict) - if counter == 2: - assert len(el["data"].keys()) == 1 - el = el["data"][list(el["data"].keys())[0]] - if "value" in el: - el = el["value"] - assert el["name"] == "one valid " + type_element + " data" - if counter == 3: - assert len(el["data"].keys()) == 2 - el1 = el["data"][list(el["data"].keys())[0]] - el2 = el["data"][list(el["data"].keys())[1]] - if "value" in el1: - el1 = el1["value"] - el2 = el2["value"] - assert (el1["name"] == "one valid " + type_element + " data" and el2["name"] == "valid " + type_element + " data") or (el2["name"] == "one valid " + type_element + " data" and el1["name"] == "valid " + type_element + " data") - assert el1["description"] == "description" - assert el2["description"] == "description" - - case_tested = True - - if policy["name"] == "test other policy": - if counter == 4: - assert len(get_elements) == 1 - el = get_elements[0] - assert isinstance(el["data"], dict) - assert len(el["data"].keys()) == 1 - el = el["data"][list(el["data"].keys())[0]] - if "value" in el: - el = el["value"] - assert el["name"] == "valid " + type_element + " data" - assert el["description"] == "new description" - case_tested = True - - assert case_tested is True - - -def test_clean(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - #restore the database as previously - utilities.get_policy_id() diff --git a/moon_manager/tests/unit_python/api/test_export.py b/moon_manager/tests/unit_python/api/test_json_export.py index ac8e8d17..8de394c9 100644 --- a/moon_manager/tests/unit_python/api/test_export.py +++ b/moon_manager/tests/unit_python/api/test_json_export.py @@ -1,55 +1,55 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + import json import api.utilities as utilities -import api.import_export_utilities as import_export_utilities - +import helpers.import_export_helper as import_export_helper +import hug MODEL_WITHOUT_META_RULES = {"models": [{"name": "test model", "description": "model description", "meta_rules": []}]} -POLICIES = {"models": [{"name": "test model", "description": "", "meta_rules": []}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}]} +DATA = {"subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], + "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], + "action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}] + } -SUBJECTS_OBJECTS_ACTIONS = {"models": [{"name": "test model", "description": "", "meta_rules": []}], +META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], + "object_categories": [{"name": "test object categories", "description": "object category description"}], + "action_categories": [{"name": "test action categories", "description": "action action description"}], + "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_OBJECTS_ACTIONS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name":"meta rule"}]}], "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], "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"}]}]} - + "actions": [{"name": "test action", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}], + **META_RULES + } SUBJECT_OBJECT_ACTION_CATEGORIES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], "object_categories": [{"name": "test object categories", "description": "object category description"}], "action_categories": [{"name": "test action categories", "description": "action category description"}]} -SUBJECT_OBJECT_ACTION_DATA = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "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"}]}]} - - -META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}], - "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"}]}]} - +SUBJECT_OBJECT_ACTION_DATA = {**SUBJECTS_OBJECTS_ACTIONS, + **DATA + } +POLICIES = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], + "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], + **META_RULES, + } -ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "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"}]}], +ASSIGNMENTS = {**POLICIES, + **DATA, "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "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"}]}], @@ -57,34 +57,37 @@ ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules" "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"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "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"}]}], +RULES = {**POLICIES, + **DATA, "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "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 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}] + "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}] } def test_export_models(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(MODEL_WITHOUT_META_RULES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + # import_export_helper.clean_all() + + req = hug.test.post(json_import, "/import", body=json.dumps( + MODEL_WITHOUT_META_RULES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in MODEL_WITHOUT_META_RULES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -99,14 +102,20 @@ def test_export_models(): def test_export_policies(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(POLICIES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + POLICIES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in POLICIES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -124,14 +133,20 @@ def test_export_policies(): def test_export_subject_object_action(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECTS_OBJECTS_ACTIONS)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECTS_OBJECTS_ACTIONS) ,headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECTS_OBJECTS_ACTIONS.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -160,14 +175,20 @@ def test_export_subject_object_action(): def test_export_subject_object_action_categories(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECT_OBJECT_ACTION_CATEGORIES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECT_OBJECT_ACTION_CATEGORIES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECT_OBJECT_ACTION_CATEGORIES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -182,14 +203,20 @@ def test_export_subject_object_action_categories(): def test_export_subject_object_action_data(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECT_OBJECT_ACTION_DATA)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECT_OBJECT_ACTION_DATA), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECT_OBJECT_ACTION_DATA.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -208,14 +235,20 @@ def test_export_subject_object_action_data(): def test_export_assignments(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(ASSIGNMENTS)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + ASSIGNMENTS), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in ASSIGNMENTS.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -239,18 +272,24 @@ 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) + import_export_helper.clean_all() def test_export_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(RULES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + RULES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in RULES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data assert "rules" in data["content"] @@ -258,8 +297,8 @@ def test_export_rules(): assert len(data["content"]["rules"]) == 1 rule = data["content"]["rules"][0] assert "instructions" in rule - assert "decision" in rule["instructions"] - assert rule["instructions"]["decision"] == "grant" + assert "decision" in rule["instructions"][0] + assert rule["instructions"][0]["decision"] == "grant" assert "enabled" in rule assert rule["enabled"] assert "meta_rule" in rule diff --git a/moon_manager/tests/unit_python/api/test_json_import.py b/moon_manager/tests/unit_python/api/test_json_import.py new file mode 100644 index 00000000..3195eca3 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_json_import.py @@ -0,0 +1,832 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import api.test_models as test_models +import api.test_policies as test_policies +import api.test_meta_data as test_categories +import api.test_data as test_data +import api.test_meta_rules as test_meta_rules +import api.test_assignement as test_assignments +import api.test_rules as test_rules +import helpers.import_export_helper as import_export_helper +import helpers.policy_helper as policy_helper +import hug +import json +import pytest +from moon_utilities import exceptions + + +MODEL_WITHOUT_META_RULES = [ + {"models": [{"name": "test model", "description": "", "meta_rules": []}]}, + {"models": [{"name": "test model", "description": "new description", "meta_rules": [], + "override": True}]}, + {"models": [{"name": "test model", "description": "description not taken into account", + "meta_rules": [], "override": False}]} +] + +POLICIES = [ + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}]}, + {"policies": [{"name": "test policy", "genre": "authz", + "description": "new description not taken into account", + "model": {"name": "test model"}, "mandatory": True}]}, + {"policies": [ + {"name": "test policy", "genre": "not authz ?", "description": "generates an exception", + "model": {"name": "test model"}, "override": True}]}, + {"models": [{"name": "test model", "description": "", "meta_rules": []}], "policies": [ + {"name": "test policy", "genre": "not authz ?", "description": "changes taken into account", + "model": {"name": "test model"}, "override": True}]}, +] + +SUBJECTS = [{"subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {}, "mandatory": True}], "subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"subjects": [{"name": "testuser", "description": "new description of the subject", + "extra": {"email": "new-email@test.com"}, + "policies": [{"name": "test other policy"}]}]}, + {"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"}]}]}, +] + +ACTIONS = [{"actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {}, "mandatory": True}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"actions": [{"name": "test action", "description": "new description of the action", + "extra": {"test": "test extra"}, + "policies": [{"name": "test other policy"}]}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": [{"name": "test policy"}]}]}] + +SUBJECT_CATEGORIES = [{"subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}]}, + {"subject_categories": [{"name": "test subject categories", + "description": "new subject category description"}]}] + +OBJECT_CATEGORIES = [{"object_categories": [ + {"name": "test object categories", "description": "object category description"}]}, + {"object_categories": [{"name": "test object categories", + "description": "new object category description"}]}] + +ACTION_CATEGORIES = [{"action_categories": [ + {"name": "test action categories", "description": "action category description"}]}, + {"action_categories": [{"name": "test action categories", + "description": "new action category description"}]}] + +# meta_rules import is needed otherwise the search for data do not work !!! +PRE_DATA = {"models": [{"name": "test model", "description": "", + "meta_rules": [{"name": "good meta rule"}, + {"name": "other good meta rule"}]}], + "policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], + "subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}, + {"name": "other test subject categories", + "description": "subject category description"}], + "object_categories": [ + {"name": "test object categories", "description": "object category description"}, + {"name": "other test object categories", + "description": "object category description"}], + "action_categories": [ + {"name": "test action categories", "description": "action category description"}, + {"name": "other test action categories", + "description": "action category description"}], + "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"}]}, + {"name": "other good meta rule", "description": "valid meta rule", + "subject_categories": [{"name": "other test subject categories"}], + "object_categories": [{"name": "other test object categories"}], + "action_categories": [{"name": "other test action categories"}]}]} + +SUBJECT_DATA = [{"subject_data": [ + {"name": "not valid subject data", "description": "", "policies": [{}], "category": {}}]}, + {"subject_data": [ + {"name": "not valid subject data", "description": "", "policies": [{}], + "category": {"name": "test subject categories"}}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "subject_data": [ + {"name": "one valid subject data", "description": "description", + "policies": [{}], "category": {"name": "test subject categories"}}]}, + {"subject_data": [{"name": "valid subject data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test subject categories"}}]}, + {"subject_data": [{"name": "valid subject data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test subject categories"}}]}] + +OBJECT_DATA = [{"object_data": [ + {"name": "not valid object data", "description": "", "policies": [{}], "category": {}}]}, + {"object_data": [ + {"name": "not valid object data", "description": "", "policies": [{}], + "category": {"name": "test object categories"}}]}, + {"policies": [{"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "object_data": [ + {"name": "one valid object data", "description": "description", "policies": [{}], + "category": {"name": "test object categories"}}]}, + {"object_data": [{"name": "valid object data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test object categories"}}]}, + {"object_data": [{"name": "valid object data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test object categories"}}]}] + +ACTION_DATA = [{"action_data": [ + {"name": "not valid action data", "description": "", "policies": [{}], "category": {}}]}, + {"action_data": [ + {"name": "not valid action data", "description": "", "policies": [{}], + "category": {"name": "test action categories"}}]}, + {"policies": [{"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "action_data": [ + {"name": "one valid action data", "description": "description", "policies": [{}], + "category": {"name": "test action categories"}}]}, + {"action_data": [{"name": "valid action data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test action categories"}}]}, + {"action_data": [{"name": "valid action data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test action categories"}}]}] + +PRE_META_RULES = {"subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}], + "object_categories": [{"name": "test object categories", + "description": "object category description"}], + "action_categories": [{"name": "test action categories", + "description": "object action description"}]} + +META_RULES = [{"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", + "subject_categories": [{"name": "not valid category"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "test action categories"}]}]}, + {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "not valid category"}], + "action_categories": [{"name": "test action categories"}]}]}, + {"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"}]}], + "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"}], + "action_categories": [{"name": "test action categories", + "description": "object action description"}], + "subjects": [{"name": "testuser", "description": "description of the subject", + "extra": {}, "policies": [{"name": "test policy"}]}], + "objects": [{"name": "test object", "description": "description of the object", + "extra": {}, "policies": [{"name": "test policy"}]}], + "actions": [{"name": "test action", "description": "description of the action", + "extra": {}, "policies": [{"name": "test policy"}]}], + "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"}]}], + "subject_data": [{"name": "subject data", "description": "test subject data", + "policies": [{"name": "test policy"}], + "category": {"name": "test subject categories"}}], + "object_data": [{"name": "object data", "description": "test object data", + "policies": [{"name": "test policy"}], + "category": {"name": "test object categories"}}], + "action_data": [{"name": "action data", "description": "test action data", + "policies": [{"name": "test policy"}], + "category": {"name": "test action categories"}}]} + +SUBJECT_ASSIGNMENTS = [ + {"subject_assignments": [ + {"subject": {"name": "unknown"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "subject data"}]}], + "exception": exceptions.InvalidJson + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "subject data"}]}], + "exception": exceptions.UnknownName + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "subject data"}]}], + "exception": None + }] + +OBJECT_ASSIGNMENTS = [ + {"object_assignments": [ + {"object": {"name": "unknown"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "object data"}]}], + "exception": exceptions.InvalidJson + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "object data"}]}], + "exception": exceptions.UnknownName + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "object data"}]}], + "exception": None + }] + +ACTION_ASSIGNMENTS = [ + {"action_assignments": [ + {"action": {"name": "unknown"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "action data"}]}], + "exception": exceptions.InvalidJson + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "action data"}]}], + "exception": exceptions.UnknownName + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "action data"}]}], + "exception": None + }] + +RULES = [{"rules": [{"meta_rule": {"name": "unknown meta rule"}, "policy": {"name": "test " + "policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "unknown " + "policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "unknown subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "unknown object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "unknown action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}] + + +def test_import_models_without_new_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + counter = 0 + for models_description in MODEL_WITHOUT_META_RULES: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(models_description) + , headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in models_description.keys()) + req, models = test_models.get_models() + models = models["models"] + assert len(list(models.keys())) == 1 + values = list(models.values()) + assert values[0]["name"] == "test model" + if counter == 0: + assert len(values[0]["description"]) == 0 + if counter == 1 or counter == 2: + assert values[0]["description"] == "new description" + counter = counter + 1 + import_export_helper.clean_all() + + +def test_import_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + counter = -1 + for policy_description in POLICIES: + counter = counter + 1 + from moon_manager.api import json_import + if counter == 2: + with pytest.raises(exceptions.UnknownName): + req = hug.test.post(json_import, "/import", body=json.dumps(policy_description), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(policy_description), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in policy_description.keys()) + + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers) + policies = req.data + policies = policies["policies"] + assert len(list(policies.keys())) == 1 + values = list(policies.values()) + assert values[0]["name"] == "test policy" + if counter < 3: + assert values[0]["genre"] == "authz" + assert values[0]["description"] == "description" + else: + assert values[0]["genre"] == "not authz ?" + assert values[0]["description"] == "changes taken into account" + assert len(values[0]["model_id"]) > 0 + import_export_helper.clean_all() + + +def test_import_subject_object_action(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["object", "action"] + perimeter_id = None + + for type_element in type_elements: + import_export_helper.clean_all() + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECTS + clean_method = import_export_helper.clean_subjects + name = "testuser" + key_extra = "email" + value_extra = "new-email@test.com" + elif type_element == "object": + elements = OBJECTS + clean_method = import_export_helper.clean_objects + name = "test object" + key_extra = "test" + value_extra = "test extra" + else: + elements = ACTIONS + clean_method = import_export_helper.clean_actions + name = "test action" + key_extra = "test" + value_extra = "test extra" + + for element in elements: + counter = counter + 1 + if counter == 2 or counter == 4: + clean_method() + + from moon_manager.api import perimeter + if counter == 3: + req = hug.test.patch(perimeter, "/{}s/{}".format(type_element, perimeter_id), + body=json.dumps(element["{}s".format(type_element)][0]), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + elif counter < 2: + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/{}s/{}".format(type_element, perimeter_id), + body=json.dumps(element["{}s".format(type_element)][0]), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Perimeter content is invalid.' == str(exception_info.value) + continue + else: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(element), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + try: + data = req.data + except Exception as e: + assert False + # assert counter < 2 # Â this is an expected failure + # continue + + if counter != 3: + assert any(e in data for e in element["{}s".format(type_element)][0].keys()) #NOTE: logs are skipped for some elements + + from moon_manager.api import perimeter + get_elements = hug.test.get(perimeter, "/" + type_element + "s", headers=auth_headers ).data + get_elements = get_elements[type_element + "s"] + + perimeter_id = list(get_elements.keys())[0] + + assert len(list(get_elements.keys())) == 1 + values = list(get_elements.values()) + assert values[0]["name"] == name + if counter == 2 or counter == 4: + assert values[0]["description"] == "description of the " + type_element + # assert not values[0]["extra"] + if counter == 3: + 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_helper.clean_all() + + +def test_import_subject_object_action_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + import_export_helper.clean_all() + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECT_CATEGORIES + get_method = test_categories.get_subject_categories + elif type_element == "object": + elements = OBJECT_CATEGORIES + get_method = test_categories.get_object_categories + else: + elements = ACTION_CATEGORIES + get_method = test_categories.get_action_categories + + for element in elements: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(element), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")} ) + counter = counter + 1 + data = req.data + assert all(e in data for e in element.keys()) + req, get_elements = get_method() + get_elements = get_elements[type_element + "_categories"] + assert len(list(get_elements.keys())) == 1 + values = list(get_elements.values()) + assert values[0]["name"] == "test " + type_element + " categories" + assert values[0]["description"] == type_element + " category description" + + +def test_import_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + # import some categories + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_META_RULES), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in PRE_META_RULES.keys()) + + counter = -1 + for meta_rule in META_RULES: + counter = counter + 1 + if counter != 3: + with pytest.raises(exceptions.UnknownName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(meta_rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Unknown Name.' == str(exception_info.value) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(meta_rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in meta_rule.keys()) + assert req.status == hug.HTTP_200 + + req, meta_rules = test_meta_rules.get_meta_rules() + meta_rules = meta_rules["meta_rules"] + key = list(meta_rules.keys())[0] + assert isinstance(meta_rules, dict) + assert meta_rules[key]["name"] == "good meta rule" + assert meta_rules[key]["description"] == "valid meta rule" + assert len(meta_rules[key]["subject_categories"]) == 1 + assert len(meta_rules[key]["object_categories"]) == 1 + assert len(meta_rules[key]["action_categories"]) == 1 + + subject_category_key = meta_rules[key]["subject_categories"][0] + object_category_key = meta_rules[key]["object_categories"][0] + action_category_key = meta_rules[key]["action_categories"][0] + + req, sub_cat = test_categories.get_subject_categories() + sub_cat = sub_cat["subject_categories"] + assert sub_cat[subject_category_key]["name"] == "test subject categories" + + req, ob_cat = test_categories.get_object_categories() + ob_cat = ob_cat["object_categories"] + assert ob_cat[object_category_key]["name"] == "test object categories" + + req, ac_cat = test_categories.get_action_categories() + ac_cat = ac_cat["action_categories"] + assert ac_cat[action_category_key]["name"] == "test action categories" + + import_export_helper.clean_all() + + +def test_import_subject_object_action_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_ASSIGNMENTS), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")} ) + data = req.data + assert any(e in data for e in PRE_ASSIGNMENTS.keys()) #NOTE: note assignment logs are skipped + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + counter = -1 + if type_element == "subject": + datas = SUBJECT_ASSIGNMENTS + get_method = test_assignments.get_subject_assignment + elif type_element == "object": + datas = OBJECT_ASSIGNMENTS + get_method = test_assignments.get_object_assignment + else: + datas = ACTION_ASSIGNMENTS + get_method = test_assignments.get_action_assignment + + for assignments in datas: + counter = counter + 1 + my_exception = assignments.pop("exception") + if my_exception: + with pytest.raises(my_exception) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(assignments), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + assert '400:' in str(exception_info.value) + else: + req = hug.test.post(json_import, "/import", body=json.dumps(assignments), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + assert len(assignments.keys()) > 0 #NOTE logs for assignments are skipped + assert req.status == hug.HTTP_200 + req = test_policies.get_policies(auth_headers=auth_headers) + policies = req.data + for policy_key in policies["policies"]: + req, get_assignments = get_method(policy_key) + get_assignments = get_assignments[type_element + "_assignments"] + assert len(get_assignments) == 1 + + +def test_import_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_ASSIGNMENTS), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in PRE_ASSIGNMENTS.keys()) + + counter = -1 + for rule in RULES: + counter = counter + 1 + from moon_manager.api import json_import + if counter < 5: + with pytest.raises(exceptions.UnknownName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + # assert req.status == hug.HTTP_400 + assert '400: Unknown Name.' == str(exception_info.value) + continue + req = hug.test.post(json_import, "/import", body=json.dumps(rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + assert req.status == hug.HTTP_200 + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policies = test_policies.get_policies(auth_headers=auth_headers).data + for policy in policies['policies']: + if policies['policies'][policy]['name'] == rule['rules'][0]['policy']['name']: + policy_id = policy + break + + req, rules = test_rules.test_get_rules(policy_id) + rules = rules["rules"] + rules = rules["rules"] + assert len(rules) == 1 + rules = rules[0] + assert rules["enabled"] + assert rules["instructions"][0]["decision"] == "grant" + + req, meta_rules = test_meta_rules.get_meta_rules() + assert meta_rules["meta_rules"][list(meta_rules["meta_rules"].keys())[0]][ + "name"] == "good meta rule" + + +def test_import_subject_object_action_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + import_export_helper.clean_all() + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_DATA), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECT_DATA + get_method = test_data.get_subject_data + get_categories = test_categories.get_subject_categories + elif type_element == "object": + elements = OBJECT_DATA + get_method = test_data.get_object_data + get_categories = test_categories.get_object_categories + else: + elements = ACTION_DATA + get_method = test_data.get_action_data + get_categories = test_categories.get_action_categories + + for element in elements: + from moon_manager.api import json_import + counter = counter + 1 + if counter == 0 or counter == 1: + with pytest.raises(exceptions.MissingIdOrName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(element), headers={ + 'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Missing ID or Name.' == str(exception_info.value) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(element), headers={ + 'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + assert req.status == hug.HTTP_200 + data = req.data + assert all(e in data for e in element.keys()) + + req = test_policies.get_policies(auth_headers=auth_headers) + policies = req.data + policies = policies["policies"] + req, categories = get_categories() + categories = categories[type_element + "_categories"] + case_tested = False + for policy_key in policies.keys(): + policy = policies[policy_key] + for category_key in categories: + req, get_elements = get_method(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... + get_elements = get_elements[type_element + "_data"] + if len(get_elements[0]["data"]) == 0: + continue + + if policy["name"] == "test policy": + assert len(get_elements) == 1 + el = get_elements[0] + assert isinstance(el["data"], dict) + if counter == 2: + assert len(el["data"].keys()) == 1 + el = el["data"][list(el["data"].keys())[0]] + if "value" in el: + el = el["value"] + assert el["name"] == "one valid " + type_element + " data" + if counter == 3: + assert len(el["data"].keys()) == 2 + el1 = el["data"][list(el["data"].keys())[0]] + el2 = el["data"][list(el["data"].keys())[1]] + if "value" in el1: + el1 = el1["value"] + el2 = el2["value"] + assert (el1["name"] == "one valid " + type_element + " data" and el2[ + "name"] == "valid " + type_element + " data") or (el2[ + "name"] == "one valid " + type_element + " data" and + el1[ + "name"] == "valid " + type_element + " data") + assert el1["description"] == "description" + assert el2["description"] == "description" + + case_tested = True + + if policy["name"] == "test other policy": + if counter == 4: + assert len(get_elements) == 1 + el = get_elements[0] + assert isinstance(el["data"], dict) + assert len(el["data"].keys()) == 1 + el = el["data"][list(el["data"].keys())[0]] + if "value" in el: + el = el["value"] + assert el["name"] == "valid " + type_element + " data" + assert el["description"] == "new description" + case_tested = True + + assert case_tested is True + + +def test_clean(): + import_export_helper.clean_all() + # restore the database as previously + policy_helper.add_policies() diff --git a/moon_manager/tests/unit_python/api/test_keystone.py b/moon_manager/tests/unit_python/api/test_keystone.py new file mode 100644 index 00000000..5ed08ca7 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_keystone.py @@ -0,0 +1,63 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def create_project(tenant_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].create_project(**tenant_dict) + + +def list_projects(): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].get_projects() + + +def create_user(subject_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].add_item(**subject_dict) + + +def test_create_project(): + tenant_dict = { + "description": "test_project", + "domain": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + project = create_project(tenant_dict) + assert project + assert project.get('name') == tenant_dict.get('name') + +# TODO TO BE UPDATED +# def test_create_project_without_name(): +# tenant_dict = { +# "description": "test_project", +# "domain_id": ['domain_id_1'], +# "enabled": True, +# "is_domain": False, +# } +# with pytest.raises(Exception) as exception_info: +# create_project(tenant_dict) +# assert '400: Keystone project error' == str(exception_info.value) + + +def test_create_user(): + subject_dict = { + "password": "password", + "domain": ['domain_id_1'], + "enabled": True, + "project": 'test_project', + "name": 'user_id_1' + } + user = create_user(subject_dict) + assert user diff --git a/moon_manager/tests/unit_python/api/test_meta_data.py b/moon_manager/tests/unit_python/api/test_meta_data.py index e6cb0833..1d37ab70 100644 --- a/moon_manager/tests/unit_python/api/test_meta_data.py +++ b/moon_manager/tests/unit_python/api/test_meta_data.py @@ -1,305 +1,370 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import json -import api.utilities as utilities from helpers import data_builder from uuid import uuid4 - +import pytest +from moon_utilities import exceptions # subject_categories_test -def get_subject_categories(client): - req = client.get("/subject_categories") - subject_categories = utilities.get_json(req.data) +def get_subject_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/subject_categories", headers=auth_headers ) + subject_categories = req.data return req, subject_categories -def add_subject_categories(client, name): +def add_subject_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + 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) + req = hug.test.post(meta_data, "/subject_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + + subject_categories = req.data return req, subject_categories -def delete_subject_categories(client, name): - request, subject_categories = get_subject_categories(client) +def delete_subject_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, subject_categories = get_subject_categories() 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 + return hug.test.delete(meta_data, "/subject_categories/{}".format(key), headers=auth_headers ) + return hug.test.delete(meta_data, "/subject_categories/{}".format(name), headers=auth_headers ) def test_get_subject_categories(): - client = utilities.register_client() - req, subject_categories = get_subject_categories(client) - assert req.status_code == 200 + req, subject_categories = get_subject_categories() + assert req.status == hug.HTTP_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 + name = "testuser" + uuid4().hex + req, subject_categories = add_subject_categories(name) + assert req.status == hug.HTTP_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") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_subject_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, subject_categories = add_subject_categories(client, name) - assert req.status_code == 200 - req, subject_categories = add_subject_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Subject Category Existing' + req, subject_categories = add_subject_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.SubjectCategoryExisting) as exception_info: + req, subject_categories = add_subject_categories(name) + assert '409: Subject Category Existing' == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Subject Category Existing' def test_add_subject_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_subject_categories(" ") + assert '400: Category Name Invalid' == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_subject_categories_with_empty_name(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_categories = add_subject_categories("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_add_subject_categories_with_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "test<z>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_categories = add_subject_categories("test<z>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_subject_categories(): - client = utilities.register_client() - req = delete_subject_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + add_subject_categories(name) + req = delete_subject_categories(name) + assert req.status == hug.HTTP_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" + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req = delete_subject_categories(uuid4().hex) + assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert 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) +def get_object_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/object_categories", headers=auth_headers ) + object_categories = req.data return req, object_categories -def add_object_categories(client, name): +def add_object_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + 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) + req = hug.test.post(meta_data, "/object_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) + object_categories = req.data return req, object_categories -def delete_object_categories(client, name): - request, object_categories = get_object_categories(client) +def delete_object_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, object_categories = get_object_categories() 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 + return hug.test.delete(meta_data, "/object_categories/{}".format(key), + headers=auth_headers ) + return hug.test.delete(meta_data, "/object_categories/{}".format(name), headers=auth_headers ) def test_get_object_categories(): - client = utilities.register_client() - req, object_categories = get_object_categories(client) - assert req.status_code == 200 + req, object_categories = get_object_categories() + assert req.status == hug.HTTP_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 + name="testuser"+uuid4().hex + req, object_categories = add_object_categories(name) + assert req.status == hug.HTTP_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") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_object_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, object_categories = add_object_categories(client, name) - assert req.status_code == 200 - req, object_categories = add_object_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Object Category Existing' + req, object_categories = add_object_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ObjectCategoryExisting) as exception_info: + req, object_categories = add_object_categories(name) + assert "409: Object Category Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Object Category Existing' def test_add_object_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_object_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_object_categories(" ") + assert "400: Category Name Invalid" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_object_categories_with_empty_name(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, object_categories = add_object_categories("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_add_object_categories_with_name_contain_space(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "test<a>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, object_categories = add_object_categories("test<a>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_object_categories(): - client = utilities.register_client() - req = delete_object_categories(client, "testuser") - assert req.status_code == 200 + name = uuid4().hex + add_object_categories(name) + req = delete_object_categories(name) + assert req.status == hug.HTTP_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" + with pytest.raises(exceptions.ObjectCategoryUnknown) as exception_info: + req = delete_object_categories(uuid4().hex) + assert "400: Object Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert 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) +def get_action_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/action_categories", headers=auth_headers ) + action_categories = req.data return req, action_categories -def add_action_categories(client, name): +def add_action_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + 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) + req = hug.test.post(meta_data, "/action_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) + action_categories = req.data return req, action_categories -def delete_action_categories(client, name): - request, action_categories = get_action_categories(client) +def delete_action_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, action_categories = get_action_categories() 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 + return hug.test.delete(meta_data, "/action_categories/{}".format(key), headers=auth_headers ) + return hug.test.delete(meta_data, "/action_categories/{}".format(name), headers=auth_headers ) def test_get_action_categories(): - client = utilities.register_client() - req, action_categories = get_action_categories(client) - assert req.status_code == 200 + req, action_categories = get_action_categories() + assert req.status == hug.HTTP_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 + name = "testuser" + uuid4().hex + req, action_categories = add_action_categories(name) + assert req.status == hug.HTTP_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") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_action_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, action_categories = add_action_categories(client, name) - assert req.status_code == 200 - req, action_categories = add_action_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Action Category Existing' + req, action_categories = add_action_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ActionCategoryExisting) as exception_info: + req, action_categories = add_action_categories(name) + assert "409: Action Category Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Action Category Existing' def test_add_action_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_action_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_action_categories(" ") + assert "400: Category Name Invalid" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_action_categories_with_empty_name(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_categories = add_action_categories("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_add_action_categories_with_name_contain_space(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "test<a>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_categories = add_action_categories("test<a>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_action_categories(): - client = utilities.register_client() - req = delete_action_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + add_action_categories(name) + req = delete_action_categories(name) + assert req.status == hug.HTTP_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" + with pytest.raises(exceptions.ActionCategoryUnknown) as exception_info: + req = delete_action_categories(uuid4().hex) + assert "400: Action Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "400: Action Category Unknown" def test_delete_data_categories_connected_to_meta_rule(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() - client = utilities.register_client() - req = client.delete("/subject_categories/{}".format(subject_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Subject Category With Meta Rule Error' - - req = client.delete("/object_categories/{}".format(object_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Object Category With Meta Rule Error' - - req = client.delete("/action_categories/{}".format(action_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Action Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteSubjectCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/subject_categories/{}".format(subject_category_id), + headers=auth_headers ) + assert "400: Subject Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Subject Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteObjectCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/object_categories/{}".format(object_category_id), headers=auth_headers) + assert "400: Object Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Object Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteActionCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/action_categories/{}".format(action_category_id), headers=auth_headers) + assert "400: Action Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Action Category With Meta Rule Error' diff --git a/moon_manager/tests/unit_python/api/test_meta_rules.py b/moon_manager/tests/unit_python/api/test_meta_rules.py index 634f19da..6c6797f5 100644 --- a/moon_manager/tests/unit_python/api/test_meta_rules.py +++ b/moon_manager/tests/unit_python/api/test_meta_rules.py @@ -1,17 +1,42 @@ -import json +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import api.utilities as utilities from helpers import category_helper from helpers import data_builder +from helpers import policy_helper +from helpers import model_helper +from helpers import meta_rule_helper from uuid import uuid4 +import pytest +from moon_utilities import exceptions + +def get_meta_rules(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_meta_rules(client): - req = client.get("/meta_rules") + req = hug.test.get(meta_rules, "/meta_rules", headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def add_meta_rules(client, name, data=None): +def add_meta_rules(name, data=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not data: subject_category = category_helper.add_subject_category( value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) @@ -29,26 +54,34 @@ def add_meta_rules(client, name, data=None): "object_categories": [object_category_id], "action_categories": [action_category_id] } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(meta_rules, "/meta_rules", body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def add_meta_rules_without_category_ids(client, name): +def add_meta_rules_without_category_ids(name): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + data = { "name": name + uuid4().hex, "subject_categories": [], "object_categories": [], "action_categories": [] } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(meta_rules, "/meta_rules", body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def update_meta_rules(client, name, metaRuleId, data=None): +def update_meta_rules(name, metaRuleId, data=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not data: subject_category = category_helper.add_subject_category( value={"name": "subject category name update" + uuid4().hex, @@ -69,13 +102,17 @@ def update_meta_rules(client, name, metaRuleId, data=None): "action_categories": [action_category_id] } - req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(meta_rules, "/meta_rules/{}".format(metaRuleId), body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def update_meta_rules_with_categories(client, name, data=None, meta_rule_id=None): +def update_meta_rules_with_categories(name, data=None, meta_rule_id=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not meta_rule_id: subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { @@ -85,63 +122,87 @@ def update_meta_rules_with_categories(client, name, data=None, meta_rule_id=None "action_categories": [action_category_id] } - req = client.patch("/meta_rules/{}".format(meta_rule_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(meta_rules, "/meta_rules/{}".format(meta_rule_id), body=data, + headers=auth_headers) 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(): +def delete_meta_rules(name): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, meta_rules_data = get_meta_rules() + for key, value in meta_rules_data['meta_rules'].items(): if value['name'] == name: - return client.delete("/meta_rules/{}".format(key)) + return hug.test.delete(meta_rules, "/meta_rules/{}".format(key), headers=auth_headers) + +def delete_meta_rules_without_id(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def delete_meta_rules_without_id(client): - req = client.delete("/meta_rules/{}".format("")) + req = hug.test.delete(meta_rules, "/meta_rules/{}".format(""), headers=auth_headers) return req def test_get_meta_rules(): - client = utilities.register_client() - req, meta_rules = get_meta_rules(client) - assert req.status_code == 200 + req, meta_rules = get_meta_rules() + assert req.status == hug.HTTP_200 assert isinstance(meta_rules, dict) assert "meta_rules" in meta_rules def test_add_meta_rules(): - client = utilities.register_client() meta_rule_name = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name) + assert req.status == hug.HTTP_200 assert isinstance(meta_rules, dict) value = list(meta_rules["meta_rules"].values())[0] assert "meta_rules" in meta_rules assert value['name'] == meta_rule_name +def test_add_meta_rules_space_name(): + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules(" ") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' + + +def test_add_meta_rules_empty_name(): + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules("") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' + + def test_add_two_meta_rules_with_same_categories_combination(): - client = utilities.register_client() meta_rule_name = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name) + data = None + assert req.status == hug.HTTP_200 for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name: data = meta_rules['meta_rules'][meta_rule_id] + assert data data['name'] = uuid4().hex - req, meta_rules = add_meta_rules(client, name=data['name'], data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Meta Rule Existing' + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req, meta_rules = add_meta_rules(name=data['name'], data=data) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Meta Rule Existing' def test_add_three_meta_rules_with_different_combination_but_similar_items(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name1) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1) + assert req.status == hug.HTTP_200 for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name1: data = meta_rules['meta_rules'][meta_rule_id] @@ -149,7 +210,7 @@ def test_add_three_meta_rules_with_different_combination_but_similar_items(): meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name2: @@ -161,12 +222,11 @@ def test_add_three_meta_rules_with_different_combination_but_similar_items(): data['name'] = uuid4().hex - req, meta_rules = add_meta_rules(client, name=data['name'], data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(name=data['name'], data=data) + assert req.status == hug.HTTP_200 def test_add_two_meta_rules_with_different_combination_but_similar_items(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex meta_rule_name2 = uuid4().hex @@ -200,8 +260,8 @@ def test_add_two_meta_rules_with_different_combination_but_similar_items(): "object_categories": [object_category_id1, object_category_id2], "action_categories": [action_category_id1, action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 data = { "name": meta_rule_name2, "subject_categories": [subject_category_id2], @@ -209,87 +269,147 @@ def test_add_two_meta_rules_with_different_combination_but_similar_items(): "action_categories": [action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 + + +# This test Succeed as it's okay to have empty id in adding meta rule, as it is not attached to model yet +def test_add_meta_rules_with_empty_subject_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('subject') + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + # assert req.status == hug.HTTP_200 + assert str(exception_info.value) == "400: Subject Category Unknown" + + +def test_add_meta_rules_with_empty_object_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('object') + with pytest.raises(exceptions.ObjectCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + assert str(exception_info.value) == "400: Object Category Unknown" + + +def test_add_meta_rules_with_empty_action_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('action') + with pytest.raises(exceptions.ActionCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + assert str(exception_info.value) == "400: Action Category Unknown" def test_add_meta_rule_with_existing_name_error(): - client = utilities.register_client() name = uuid4().hex - req, meta_rules = add_meta_rules(client, name) - assert req.status_code == 200 - req, meta_rules = add_meta_rules(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Meta Rule Existing' + req, meta_rules = add_meta_rules(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req, meta_rules = add_meta_rules(name) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Meta Rule Existing' def test_add_meta_rules_with_forbidden_char_in_name(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, meta_rules = add_meta_rules("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_add_meta_rules_with_blank_name(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Meta Rule Error' + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules("") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' def test_add_meta_rules_without_subject_categories(): - client = utilities.register_client() name_meta_rule = uuid4().hex - req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule) - assert req.status_code == 200 + req, meta_rules = add_meta_rules_without_category_ids(name_meta_rule) + assert req.status == hug.HTTP_200 def test_delete_meta_rules(): - client = utilities.register_client() name_meta_rule = uuid4().hex - req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule) + req, meta_rules = add_meta_rules_without_category_ids(name_meta_rule) meta_rule_id = next(iter(meta_rules['meta_rules'])) - req = delete_meta_rules(client, meta_rules['meta_rules'][meta_rule_id]['name']) - assert req.status_code == 200 + req = delete_meta_rules(meta_rules['meta_rules'][meta_rule_id]['name']) + assert req.status == hug.HTTP_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" + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req = delete_meta_rules_without_id() + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Meta Rule Unknown" def test_update_meta_rules(): - client = utilities.register_client() - req = add_meta_rules(client, "testuser") + name = "testuser" + uuid4().hex + req = add_meta_rules(name) + meta_rule_id = list(req[1]['meta_rules'])[0] + req_update = update_meta_rules(name, meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + delete_meta_rules("testuser") + get_meta_rules() + + +def test_update_meta_rules_empty_name(): + req = add_meta_rules("testuser" + uuid4().hex) + meta_rule_id = list(req[1]['meta_rules'])[0] + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req_update = update_meta_rules("", meta_rule_id) + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Meta Rule Error' + + +def test_update_meta_rules_space_name(): + req = add_meta_rules("testuser" + uuid4().hex) 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) + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req_update = update_meta_rules(" ", meta_rule_id) + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Meta Rule Error' def test_update_meta_rule_with_combination_existed(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name1) + req, meta_rules = add_meta_rules(meta_rule_name1) meta_rule_id1 = next(iter(meta_rules['meta_rules'])) data1 = meta_rules['meta_rules'][meta_rule_id1] meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) meta_rule_id2 = next(iter(meta_rules['meta_rules'])) data2 = meta_rules['meta_rules'][meta_rule_id2] data1['name'] = data2['name'] - req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2, - data=data1) - assert req_update[0].status_code == 409 - assert req_update[1]['message']== '409: Meta Rule Existing' + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req_update = update_meta_rules(name=meta_rule_name2, metaRuleId=meta_rule_id2, + data=data1) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_409 + # assert req_update[1]['message'] == '409: Meta Rule Existing' def test_update_meta_rule_with_different_combination_but_same_data(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex subject_category = category_helper.add_subject_category( value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) @@ -316,47 +436,46 @@ def test_update_meta_rule_with_different_combination_but_same_data(): "object_categories": [object_category_id1, object_category_id2], "action_categories": [action_category_id1, action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) meta_rule_id2 = next(iter(meta_rules['meta_rules'])) data2 = { "name": meta_rule_name2, "subject_categories": [subject_category_id1, subject_category_id2], "object_categories": [object_category_id1], - "action_categories": [action_category_id1,action_category_id2] + "action_categories": [action_category_id1, action_category_id2] } - req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2, + req_update = update_meta_rules(name=meta_rule_name2, metaRuleId=meta_rule_id2, data=data2) - assert req_update[0].status_code == 200 + assert req_update[0].status == hug.HTTP_200 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" + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req_update = update_meta_rules("testuser", "") + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "400: Meta Rule Unknown" def test_update_meta_rules_without_name(): - client = utilities.register_client() - req_update = update_meta_rules(client, "<br/>", "1234567") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)[ - "message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req_update = update_meta_rules("<br/>", "1234567") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "Key: 'name', [Forbidden characters in string]" def test_update_meta_rules_without_categories(): - client = utilities.register_client() - req_update = update_meta_rules_with_categories(client, "testuser") - assert req_update[0].status_code == 200 + req_update = update_meta_rules_with_categories("testuser" + uuid4().hex) + assert req_update[0].status == hug.HTTP_200 def test_update_meta_rules_with_empty_categories(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -364,14 +483,73 @@ def test_update_meta_rules_with_empty_categories(): "object_categories": [""], "action_categories": [""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' + + +def test_update_meta_rules_with_blank_subject_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [], + "object_categories": [object_category_id], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_blank_object_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [subject_category_id], + "object_categories": [], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_blank_action_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [subject_category_id], + "object_categories": [object_category_id], + "action_categories": [] + } + req_update = update_meta_rules_with_categories("testuser", data=data, meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Subject Category Unknown' + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_empty_subject_category(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser", + "subject_categories": [""], + "object_categories": [object_category_id], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' def test_update_meta_rules_with_empty_action_category(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -379,14 +557,15 @@ def test_update_meta_rules_with_empty_action_category(): "object_categories": [object_category_id], "action_categories": [""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Action Category Unknown' + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Action Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Action Category Unknown' def test_update_meta_rules_with_empty_object_category(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -394,14 +573,16 @@ def test_update_meta_rules_with_empty_object_category(): "object_categories": [""], "action_categories": [action_category_id] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Object Category Unknown' + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + # assert "400: Object Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Object Category Unknown' def test_update_meta_rules_with_categories_and_one_empty(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -409,7 +590,98 @@ def test_update_meta_rules_with_categories_and_one_empty(): "object_categories": [object_category_id, ""], "action_categories": [action_category_id, ""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Subject Category Unknown' + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' + + +def test_add_one_meta_rules_with_different_combination_but_similar_items(): + meta_rule_name1 = uuid4().hex + + subject_category = category_helper.add_subject_category( + value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) + subject_category_id1 = list(subject_category.keys())[0] + + object_category = category_helper.add_object_category( + value={"name": "object category name" + uuid4().hex, "description": "description 1"}) + object_category_id1 = list(object_category.keys())[0] + + action_category = category_helper.add_action_category( + value={"name": "action category name" + uuid4().hex, "description": "description 1"}) + action_category_id1 = list(action_category.keys())[0] + + subject_category = category_helper.add_subject_category( + value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) + subject_category_id2 = list(subject_category.keys())[0] + + object_category = category_helper.add_object_category( + value={"name": "object category name" + uuid4().hex, "description": "description 1"}) + object_category_id2 = list(object_category.keys())[0] + + action_category = category_helper.add_action_category( + value={"name": "action category name" + uuid4().hex, "description": "description 1"}) + action_category_id2 = list(action_category.keys())[0] + + data = { + "name": meta_rule_name1, + "subject_categories": [subject_category_id1, subject_category_id2], + "object_categories": [object_category_id1, object_category_id2], + "action_categories": [action_category_id1, action_category_id2] + } + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 + + value = { + "name": "name_model", + "description": "test", + "meta_rules": [next(iter(meta_rules['meta_rules']))] + } + mode_id = next(iter(model_helper.add_model(value=value))) + + value = { + "name": "test_policy" + uuid4().hex, + "model_id": mode_id, + "genre": "authz", + "description": "test", + } + + policy_id = next(iter(policy_helper.add_policies(value=value))) + + data_id_1 = data_builder.create_subject_data(policy_id, subject_category_id1) + data_id_2 = data_builder.create_subject_data(policy_id, subject_category_id2) + data_id_3 = data_builder.create_object_data(policy_id, object_category_id2) + data_id_4 = data_builder.create_object_data(policy_id, object_category_id1) + data_id_5 = data_builder.create_action_data(policy_id, action_category_id1) + data_id_5 = data_builder.create_action_data(policy_id, action_category_id2) + + from moon_utilities.auth_functions import get_api_key_for_user + from falcon import HTTP_200, HTTP_400, HTTP_405, HTTP_409 + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + + req = hug.test.delete(policy, "policies/{}".format(policy_id), headers=auth_headers) + assert req.status == HTTP_200 + + +def test_update_meta_rules_with_blank_action_categories_assigned_to_used_model(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import meta_rules + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policies_list = policy_helper.add_policies_with_model() + policy_id = list(policies_list.keys())[0] + model_id = policies_list[policy_id]['model_id'] + models_list = model_helper.get_models(model_id=model_id) + meta_rule_id = models_list[model_id]["meta_rules"][0] + meta_rules_list = meta_rule_helper.get_meta_rules(meta_rule_id=meta_rule_id); + data = meta_rules_list[meta_rule_id] + + data["action_categories"] = [] + + with pytest.raises(exceptions.MetaRuleUpdateError) as exception_info: + hug.test.patch(meta_rules, "/meta_rules/{}".format(meta_rule_id), body=data, + headers=auth_headers) + assert "400: Meta_Rule Update Error" == str(exception_info.value) diff --git a/moon_manager/tests/unit_python/api/test_models.py b/moon_manager/tests/unit_python/api/test_models.py new file mode 100644 index 00000000..569fe1b4 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_models.py @@ -0,0 +1,475 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import json +import hug +import pytest +from moon_utilities import exceptions +from helpers import data_builder as builder +from helpers import policy_helper +from helpers import model_helper +from uuid import uuid4 + + +def get_models(): + from moon_manager.api import models + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(models, "/models", headers=auth_headers) + models = req.data + return req, models + + +def add_models(name, headers, data=None, ): + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + if not data: + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def update_model(name, model_id, headers): + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + headers['Content-Type'] = 'application/json' + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + if req.status == hug.HTTP_405: + return req + models = req.data + return req, models + + +def add_model_without_meta_rules_ids(name, headers): + from moon_manager.api import models + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def add_model_with_empty_meta_rule_id(name, headers): + from moon_manager.api import models + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [""] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def update_model_without_meta_rules_ids(model_id, headers): + from moon_manager.api import models + name = "model_id" + uuid4().hex + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + headers['Content-Type'] = 'application/json' + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def delete_models(name, headers): + request, models = get_models() + for key, value in models['models'].items(): + if value['name'] == name: + from moon_manager.api import models + req = hug.test.delete(models, "/models/{}".format(key), headers=headers) + break + return req + + +def delete_models_without_id(headers): + from moon_manager.api import models + req = hug.test.delete(models, "/models/{}".format(""), headers=headers) + return req + + +def clean_models(headers): + req, models = get_models() + for key, value in models['models'].items(): + print(key) + print(value) + from moon_manager.api import models + hug.test.delete(models, "/models/{}".format(key), headers=headers) + + +def test_delete_model_assigned_to_policy(): + policy_name = "testuser" + uuid4().hex + req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(req.keys())[0] + data = { + "name": policy_name, + "description": "description of {}".format(policy_name), + "model_id": model_id, + "genre": "genre" + } + from moon_manager.api import policy + from moon_manager.api import models + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + hug.test.post(policy, "/policies", body=json.dumps(data), headers=headers) + with pytest.raises(exceptions.DeleteModelWithPolicy) as exception_info: + req = hug.test.delete(models, "/models/{}".format(model_id), headers={"X-Api-Key": + get_api_key_for_user("admin")}) + assert "400: Model With Policy Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Model With Policy Error' + + +def test_get_models(): + req, models = get_models() + assert req.status == hug.HTTP_200 + assert isinstance(models, dict) + assert "models" in models + + +def test_add_models(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, models = add_models("testuser", auth_headers) + assert req.status == hug.HTTP_200 + assert isinstance(models, dict) + model_id = list(models["models"])[0] + assert "models" in models + assert models['models'][model_id]['name'] == "testuser" + assert models['models'][model_id]["description"] == "description of {}".format("testuser") + + +def test_add_models_with_meta_rule_has_blank_subject(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="subject") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_add_models_with_meta_rule_has_blank_object(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="object") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_add_models_with_meta_rule_has_blank_action(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="action") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_delete_models(): + name = uuid4().hex + "testuser" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + add_models(name, auth_headers) + req = delete_models(name, headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_update_models_with_assigned_policy(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + value = { + "name": "test_policy" + uuid4().hex, + "model_id": model_id, + "description": "test", + } + policy_helper.add_policies(value=value) + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + "meta_rules": [] + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + with pytest.raises(exceptions.DeleteModelWithPolicy) as exception_info: + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert "400: Model With Policy Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Model With Policy Error" + + +def test_update_models_with_no_assigned_policy(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + "meta_rules": [] + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert req.status == hug.HTTP_200 + + +def test_update_models_without_meta_rule_key(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Meta Rule Unknown" + + +def test_delete_models_without_id(): + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_models_without_id(headers=headers) + assert req.status == hug.HTTP_405 + + +def test_add_model_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, models = add_models("<br/>", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_add_model_with_name_contain_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, models = add_models("test<br>user", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_add_model_with_name_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ModelContentError) as exception_info: + req, models = add_models(" ", headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Model Unknown' + + +def test_add_model_with_empty_meta_rule_id(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req, meta_rules = add_model_with_empty_meta_rule_id("testuser", headers=auth_headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Unknown' + + +def test_add_model_with_existed_name(): + name = uuid4().hex + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, models = add_models(name, headers=auth_headers) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ModelExisting) as exception_info: + req, models = add_models(name, headers=auth_headers) + assert "409: Model Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Model Error' + + +def test_add_model_with_existed_meta_rules_list(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = uuid4().hex + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + name = uuid4().hex + req, models = add_models(name=name, headers=auth_headers, data=data) + assert req.status == hug.HTTP_200 + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + with pytest.raises(exceptions.ModelExisting) as exception_info: + req, models = add_models(name=name, headers=auth_headers, data=data) + assert "409: Model Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Model Error' + + +def test_add_model_without_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, meta_rules = add_model_without_meta_rules_ids("testuser", headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_update_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + req_update = update_model("testuser", model_id, headers=auth_headers) + assert req_update[0].status == hug.HTTP_200 + model_id = list(req_update[1]["models"])[0] + assert req_update[1]["models"][model_id]["meta_rules"][0] is not None + delete_models("testuser", headers=auth_headers) + + +def test_update_model_name_with_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + with pytest.raises(exceptions.ModelContentError) as exception_info: + req_update = update_model(" ", model_id, headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]["message"] == '400: Model Unknown' + + +def test_update_model_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ModelContentError) as exception_info: + req_update = update_model("", model_id, headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Model Unknown' + + +def test_update_meta_rules_without_id(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req_update = update_model("testuser", "", headers=auth_headers) + assert req_update.status == hug.HTTP_405 + + +def test_update_meta_rules_without_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req_update = update_model("<a></a>", "1234567", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_update_meta_rules_without_meta_rules(): + value = { + "name": "mls_model_id" + uuid4().hex, + "description": "test", + "meta_rules": [] + } + model = model_helper.add_model(value=value) + model_id = list(model.keys())[0] + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req_update = update_model_without_meta_rules_ids(model_id, headers=auth_headers) + assert req_update[0].status == hug.HTTP_200 diff --git a/moon_manager/tests/unit_python/api/test_nova.py b/moon_manager/tests/unit_python/api/test_nova.py new file mode 100644 index 00000000..10118cc3 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_nova.py @@ -0,0 +1,58 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def create_project(tenant_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["objects"][0].create_project(**tenant_dict) + + +def list_projects(): + from moon_manager.pip_driver import InformationManager + return InformationManager["objects"][0].get_projects() + + +def list_objects(): + from moon_manager.pip_driver import InformationManager + print(f"IM : {InformationManager['objects'][0].driver.__dict__}") + return InformationManager["objects"][0].get_items() + + +def test_create_project(): + tenant_dict = { + "description": "test_project", + "domain": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + project = create_project(tenant_dict) + assert project + assert project.get('name') == tenant_dict.get('name') + + +def test_list_objects(): + objects = list_objects() + assert objects + assert objects["servers"][0].get('name') == "vm1" + +# TODO TO BE UPDATED +# def test_create_project_without_name(): +# tenant_dict = { +# "description": "test_project", +# "domain_id": ['domain_id_1'], +# "enabled": True, +# "is_domain": False, +# } +# with pytest.raises(Exception) as exception_info: +# create_project(tenant_dict) +# assert '400: Keystone project error' == str(exception_info.value) diff --git a/moon_manager/tests/unit_python/api/test_pdp.py b/moon_manager/tests/unit_python/api/test_pdp.py index 53a87b21..32b75726 100644 --- a/moon_manager/tests/unit_python/api/test_pdp.py +++ b/moon_manager/tests/unit_python/api/test_pdp.py @@ -1,48 +1,135 @@ -import json -import api.utilities as utilities -from helpers import data_builder as builder -from uuid import uuid4 +# Software Name: MOON +# Version: 5.4 -def get_pdp(client): - req = client.get("/pdp") - pdp = utilities.get_json(req.data) - return req, pdp +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. -def add_pdp(client, data): - req = client.post("/pdp", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - pdp = utilities.get_json(req.data) - return req, pdp +from falcon import HTTP_200, HTTP_400, HTTP_405 +import hug +import pytest +from moon_utilities import exceptions +from uuid import uuid4 +from helpers import data_builder as builder -def update_pdp(client, data, pdp_id): - req = client.patch("/pdp/{}".format(pdp_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - pdp = utilities.get_json(req.data) - return req, pdp +def test_get_pdp(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "pdps" in req.data -def delete_pdp(client, key): - req = client.delete("/pdp/{}".format(key)) - return req +def test_add_pdp_invalid_security_pipeline(mocker): + from moon_manager.api import pdp + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + 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_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + data_no_project_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": None, + "description": "description of testuser" + } + data_no_project = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": None, + "description": "description of testuser" + } + + req = hug.test.post(pdp, "pdp/", data_no_project_no_pipeline, headers=auth_headers) + assert req.status == HTTP_200 + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.post(pdp, "pdp/", data_no_pipeline, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) -def delete_pdp_without_id(client): - req = client.delete("/pdp/{}".format("")) - return req + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.post(pdp, "pdp/", data_no_project, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) +def test_update_pdp_invalid_security_pipeline(mocker): + from moon_manager.api import pdp + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + 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_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + data_no_project_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": None, + "description": "description of testuser" + } + data_no_project = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": None, + "description": "description of testuser" + } -def test_get_pdp(): - client = utilities.register_client() - req, pdp = get_pdp(client) - assert req.status_code == 200 - assert isinstance(pdp, dict) - assert "pdps" in pdp + data_valid = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + req = hug.test.post(pdp, "pdp/", data_valid, headers=auth_headers) + assert req.status == HTTP_200 + pip_id = list(req.data['pdps'])[0] + + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_project_no_pipeline, headers=auth_headers) + assert req.status == HTTP_200 + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_pipeline, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) -def test_add_pdp(): + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_project, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) + +def test_add_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) 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, @@ -50,71 +137,182 @@ def test_add_pdp(): meta_rule_name="meta_rule_1" + uuid4().hex, model_name="model1" + uuid4().hex) data = { - "name": "testuser", + "name": "testuser" + uuid4().hex, "security_pipeline": [policy_id], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, pdp = add_pdp(client, data) - assert req.status_code == 200 - assert isinstance(pdp, dict) - value = list(pdp["pdps"].values())[0] - assert "pdps" in pdp - assert value['name'] == "testuser" - assert value["description"] == "description of {}".format("testuser") - assert value["keystone_project_id"] == "keystone_project_id" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + found = False + assert "pdps" in req.data + for value in req.data["pdps"].values(): + if value['name'] == data['name']: + found = True + assert value["description"] == "description of {}".format("testuser") + assert value["vim_project_id"] == "vim_project_id" + break + assert found -def test_delete_pdp(): - client = utilities.register_client() - request, pdp = get_pdp(client) - success_req = None - for key, value in pdp['pdps'].items(): - if value['name'] == "testuser": - success_req = delete_pdp(client, key) - break - assert success_req - assert success_req.status_code == 200 +def test_add_pdp_name_existed(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = 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) + name = "testuser" + uuid4().hex + data = { + "name": name, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = 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) -def test_add_pdp_with_forbidden_char_in_user(): data = { - "name": "<a>", - "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "keystone_project_id", + "name": name, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid4().hex, + "description": "description of testuser" + uuid4().hex + } + with pytest.raises(exceptions.PdpExisting) as exception_info: + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert "409: Pdp Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Pdp Error' + + +def test_add_pdp_policy_used(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = 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" + uuid4().hex, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, models = add_pdp(client, data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + + name_uuid = "testuser" + uuid4().hex + data = { + "name": name_uuid, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id " + name_uuid, + "description": "description of testuser " + name_uuid + } + with pytest.raises(exceptions.PdpInUse) as exception_info: + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert "400: Pdp Inuse" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Pdp Conflict' -def test_add_pdp_with_forbidden_char_in_keystone(): + +def test_delete_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + 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"], - "keystone_project_id": "<a>", + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, meta_rules = add_pdp(client, data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'keystone_project_id', [Forbidden characters in string]" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + success_req = None + for key, value in req.data['pdps'].items(): + if value['name'] == data['name']: + success_req = hug.test.delete(pdp, 'pdp/{}'.format(key), headers=auth_headers) + break + assert success_req + assert success_req.status == HTTP_200 + +# Fixme: should re-enabled the input validation for those tests +# def test_add_pdp_with_forbidden_char_in_user(): +# data = { +# "name": "<a>", +# "security_pipeline": ["policy_id_1", "policy_id_2"], +# "vim_project_id": "vim_project_id", +# "description": "description of testuser" +# } +# req = hug.test.post(pdp, "pdp/", data) +# assert req.status == HTTP_400 +# print(req.data) +# assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" +# +# +# def test_add_pdp_with_forbidden_char_in_keystone(): +# data = { +# "name": "testuser", +# "security_pipeline": ["policy_id_1", "policy_id_2"], +# "vim_project_id": "<a>", +# "description": "description of testuser" +# } +# req = hug.test.post(pdp, "pdp/", data) +# assert req.status == 400 +# assert req.data["message"] == "Key: 'vim_project_id', [Forbidden characters in string]" -def test_update_pdp(): + +def test_update_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) 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) + 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], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } @@ -125,40 +323,157 @@ def test_update_pdp(): meta_rule_name="meta_rule_1" + uuid4().hex, model_name="model1" + uuid4().hex) data_update = { - "name": "testuser", + "name": "testuser_updated", "security_pipeline": [policy_id_update], - "keystone_project_id": "keystone_project_id_update", - "description": "description of testuser" + "vim_project_id": "vim_project_id_update", + "description": "description of testuser_updated" } - client = utilities.register_client() - req = add_pdp(client, data_add) - pdp_id = list(req[1]['pdps'])[0] - req_update = update_pdp(client, data_update, pdp_id) - assert req_update[0].status_code == 200 - value = list(req_update[1]["pdps"].values())[0] - assert value["keystone_project_id"] == "keystone_project_id_update" - request, pdp = get_pdp(client) - for key, value in pdp['pdps'].items(): + req = hug.test.post(pdp, "pdp/", data_add, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data_update, headers=auth_headers) + assert req_update.status == HTTP_200 + value = list(req_update.data["pdps"].values())[0] + assert value["vim_project_id"] == data_update["vim_project_id"] + assert value["description"] == data_update["description"] + assert value["name"] == data_update['name'] + assert value["security_pipeline"] == data_update['security_pipeline'] + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + for key, value in req.data['pdps'].items(): if value['name'] == "testuser": - delete_pdp(client, key) + hug.test.delete(pdp, 'pdp/{}'.format(key), headers=auth_headers) break -def test_update_pdp_without_id(): - client = utilities.register_client() - req_update = update_pdp(client, "testuser", "") - 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_id(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + req = hug.test.patch(pdp, "pdp/", "testuser", headers=auth_headers) + assert req.status == HTTP_405 + # assert req.data["message"] == 'Invalid Key :name not found' -def test_update_pdp_without_user(): +def test_update_pdp_without_user(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) data = { "name": "", "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req_update = update_pdp(client, data, "<a>") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)["message"] == "Forbidden characters in string" + req = hug.test.patch(pdp, "pdp/<a>", data, headers=auth_headers) + assert req.status == HTTP_400 + print(req.data) + assert req.data["errors"] == {'uuid': 'Invalid UUID provided'} + + +def test_update_pdp_name_existed(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = 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) + uuid1 = uuid4().hex + data1 = { + "name": "testuser1" + uuid1, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id" + uuid1, + "description": "description of testuser1" + uuid1 + } + req = hug.test.post(pdp, "pdp/", data1, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = 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) + + uuid2 = uuid4().hex + data2 = { + "name": "testuser2" + uuid2, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid2, + "description": "description of testuser2" + uuid2 + } + req = hug.test.post(pdp, "pdp/", data2, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + for item in list(req.data['pdps']): + if req.data['pdps'][item]['name']==data2['name']: + pdp_id=item + break + data2['name'] = data1['name'] + with pytest.raises(exceptions.PdpExisting) as exception_info: + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data2, headers=auth_headers) + # assert req_update.data['message'] == '409: Pdp Error' + assert "409: Pdp Error" == str(exception_info.value) + + + +def test_update_pdp_policy_used(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = 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) + uuid1 = uuid4().hex + data1 = { + "name": "testuser1" + uuid1, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id" + uuid1, + "description": "description of testuser1" + uuid1 + } + req = hug.test.post(pdp, "pdp/", data1, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = 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) + + uuid2 = uuid4().hex + data2 = { + "name": "testuser2" + uuid2, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid2, + "description": "description of testuser2" + uuid2 + } + req = hug.test.post(pdp, "pdp/", data2, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + for item in list(req.data['pdps']): + if req.data['pdps'][item]['name']==data2['name']: + pdp_id=item + break + data2['security_pipeline'] = data1['security_pipeline'] + + with pytest.raises(exceptions.PdpInUse) as exception_info: + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data2, headers=auth_headers) + assert "400: Pdp Inuse" == str(exception_info.value) + # assert req_update.data['message'] == '409: Pdp Conflict' + + diff --git a/moon_manager/tests/unit_python/api/test_perimeter.py b/moon_manager/tests/unit_python/api/test_perimeter.py index ff7b09d7..c741adf7 100644 --- a/moon_manager/tests/unit_python/api/test_perimeter.py +++ b/moon_manager/tests/unit_python/api/test_perimeter.py @@ -1,19 +1,39 @@ -# import moon_manager -# import moon_manager.api -import json +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import api.utilities as utilities from helpers import data_builder as builder import helpers.policy_helper as policy_helper from uuid import uuid4 +import pytest +from moon_utilities import exceptions + +def get_subjects(subject_id=None): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_subjects(client): - req = client.get("/subjects") + if not subject_id: + req = hug.test.get(perimeter, 'subjects/', headers=auth_headers) + else: + req = hug.test.get(perimeter, 'subjects/{}'.format(subject_id), headers=auth_headers) subjects = utilities.get_json(req.data) return req, subjects -def add_subjects(client, policy_id, name, perimeter_id=None, data=None): +def add_subjects(policy_id, name, perimeter_id=None, data=None, auth_headers=None): + from moon_manager.api import perimeter if not data: name = name + uuid4().hex data = { @@ -23,44 +43,44 @@ def add_subjects(client, policy_id, name, perimeter_id=None, data=None): "email": "{}@moon".format(name) } if not perimeter_id: - req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/subjects".format(policy_id), + body=data, headers=auth_headers) else: - req = client.post("/policies/{}/subjects/{}".format(policy_id, perimeter_id), - data=json.dumps( - data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/subjects/{}".format(policy_id, perimeter_id), + body=data, headers=auth_headers) subjects = utilities.get_json(req.data) return req, subjects -def delete_subjects_without_perimeter_id(client): - req = client.delete("/subjects/{}".format("")) +def delete_subjects_without_perimeter_id(auth_headers=None): + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/subjects/{}".format(""), headers=auth_headers) return req def test_perimeter_get_subject(): - client = utilities.register_client() - req, subjects = get_subjects(client) - assert req.status_code == 200 + req, subjects = get_subjects() + assert req.status == hug.HTTP_200 assert isinstance(subjects, dict) assert "subjects" in subjects def test_perimeter_add_subject(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] name = "testuser" @@ -71,13 +91,15 @@ def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - add_subjects(client, policy_id1, data['name'], perimeter_id=perimeter_id, data=data) + add_subjects(policy_id1, data['name'], perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] - req, subjects = add_subjects(client, policy_id2, data['name'], - perimeter_id=perimeter_id, data=data) + req, subjects = add_subjects(policy_id2, data['name'], + perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] assert len(value['policy_list']) == 2 @@ -86,20 +108,25 @@ def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): def test_perimeter_add_same_subject_perimeter_id_with_different_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex - add_subjects(client, policy_id1, "testuser", perimeter_id=perimeter_id) + add_subjects(policy_id1, "testuser", perimeter_id=perimeter_id, auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] - req, subjects = add_subjects(client, policy_id2, "testuser", perimeter_id=perimeter_id) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, subjects = add_subjects(policy_id2, "testuser", perimeter_id=perimeter_id, + auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_subject_name_with_new_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex @@ -110,8 +137,8 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id, - data=data) + req, subjects = add_subjects(policy_id1, None, perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] value = list(subjects["subjects"].values())[0] @@ -121,9 +148,9 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): "password": "password for {}".format(value['name']), "email": "{}@moon".format(value['name']) } - req, subjects = add_subjects(client, policy_id2, None, data=data) + req, subjects = add_subjects(policy_id2, None, data=data, auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] assert len(value['policy_list']) == 2 @@ -132,7 +159,8 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): def test_perimeter_add_same_subject_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex @@ -143,8 +171,8 @@ def test_perimeter_add_same_subject_name_with_same_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id, - data=data) + req, subjects = add_subjects(policy_id1, None, perimeter_id=perimeter_id, + data=data, auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] data = { "name": value['name'], @@ -152,31 +180,46 @@ def test_perimeter_add_same_subject_name_with_same_policy_id(): "password": "password for {}".format(value['name']), "email": "{}@moon".format(value['name']) } - req, subjects = add_subjects(client, policy_id1, None, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, subjects = add_subjects(policy_id1, None, data=data, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_subject_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] name = "testuser" + uuid4().hex data = { - "name": name, + "name": name + uuid4().hex, "description": "description of {}".format(name), "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id, name, data=data) + subj_id = "b34e5a29-5494-4cc5-9356-daa244b8c254" + req, subjects = get_subjects(subj_id) + if subjects['subjects']: + for __policy_id in subjects['subjects'][subj_id]['policy_list']: + req = hug.test.delete(perimeter, + "/policies/{}/subjects/{}".format(__policy_id, subj_id), + headers=auth_headers) + req, subjects = add_subjects(policy_id, name, data=data, auth_headers=auth_headers) perimeter_id = list(subjects["subjects"].values())[0]['id'] - req, subjects = add_subjects(client, policy_id, name, perimeter_id=perimeter_id, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, subjects = add_subjects(policy_id, name, perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_subject_invalid_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] name = "testuser" @@ -186,103 +229,121 @@ def test_perimeter_add_subject_invalid_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id + "0", "testuser", data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, subjects = add_subjects( policy_id + "0", "testuser", data, auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' -def test_perimeter_add_subject_policy_id_none(): - client = utilities.register_client() - name = "testuser" - data = { - "name": name + uuid4().hex, - "description": "description of {}".format(name), - "password": "password for {}".format(name), - "email": "{}@moon".format(name) - } - req, subjects = add_subjects(client, None, "testuser", data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' +def test_perimeter_add_subject_blank_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + policies = policy_helper.add_policies() + policy_id = list(policies.keys())[0] + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format(policy_id), body={'test':"aa"}, + headers=auth_headers) + assert "Invalid Key :name not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :name not found' def test_perimeter_add_subject_with_forbidden_char_in_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<a>", "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', [Forbidden characters in string]" + subj_id = "a34e5a29-5494-4cc5-9356-daa244b8c888" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format(subj_id), body=data, + headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_perimeter_update_subject_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_subject_description(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update", } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_subject_description_and_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update", 'name': value1['name'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + from moon_manager.api import perimeter + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_subject_wrong_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -290,64 +351,83 @@ def test_perimeter_update_subject_wrong_id(): "name": name, "description": "description of {}".format('testuser'), } - req, subjects = add_subjects(client, policy_id=policy_id1, name='testuser', data=data) + req, subjects = add_subjects(policy_id=policy_id1, name='testuser', data=data, + auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id + "wrong"), + body=data, headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_update_subject_name_with_existed_one(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name1 = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id1 = uuid4().hex - req, subjects = add_subjects(client, policy_id=policy_id1, name=name1, - perimeter_id=perimeter_id1) + req, subjects = add_subjects(policy_id=policy_id1, name=name1, + perimeter_id=perimeter_id1, auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id2 = uuid4().hex name2 = 'testuser' + uuid4().hex - req, subjects = add_subjects(client, policy_id=policy_id1, name=name2, - perimeter_id=perimeter_id2) + req, subjects = add_subjects(policy_id=policy_id1, name=name2, + perimeter_id=perimeter_id2, auth_headers=auth_headers) data = { 'name': value1['name'], } - req = client.patch("/subjects/{}".format(perimeter_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 + with pytest.raises(exceptions.SubjectExisting) as exception_info: + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id2), body=data, + headers=auth_headers) + assert "409: Subject Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 def test_perimeter_delete_subject(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) subject_id = list(subjects["subjects"].values())[0]["id"] - req = client.delete("/policies/{}/subjects/{}".format(policy_id, subject_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/subjects/{}".format(policy_id, subject_id), + headers=auth_headers) + assert req.status == hug.HTTP_200 def test_perimeter_delete_subjects_without_perimeter_id(): - client = utilities.register_client() - req = delete_subjects_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Subject Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + with pytest.raises(exceptions.SubjectUnknown) as exception_info: + req = delete_subjects_without_perimeter_id(auth_headers) + assert "400: Subject Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Subject Unknown" -def get_objects(client): - req = client.get("/objects") +def get_objects(): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(perimeter, "/objects", headers=auth_headers) objects = utilities.get_json(req.data) return req, objects -def add_objects(client, name, policyId=None, data=None, perimeter_id=None): +def add_objects(name, policyId=None, data=None, perimeter_id=None, auth_headers=None): + from moon_manager.api import perimeter if not policyId: subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, @@ -361,59 +441,70 @@ def add_objects(client, name, policyId=None, data=None, perimeter_id=None): "description": "description of {}".format(name), } if not perimeter_id: - req = client.post("/policies/{}/objects/".format(policyId), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/objects/".format(policyId), body=data, + headers=auth_headers) else: - req = client.post("/policies/{}/objects/{}".format(policyId, perimeter_id), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/objects/{}".format(policyId, perimeter_id), + body=data, headers=auth_headers) + objects = utilities.get_json(req.data) return req, objects -def delete_objects_without_perimeter_id(client): - req = client.delete("/objects/{}".format("")) +def delete_objects_without_perimeter_id(auth_headers=None): + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/objects/{}".format(""), headers=auth_headers) return req def test_perimeter_get_object(): - client = utilities.register_client() - req, objects = get_objects(client) - assert req.status_code == 200 + + req, objects = get_objects() + assert req.status == hug.HTTP_200 assert isinstance(objects, dict) assert "objects" in objects def test_perimeter_add_object(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects("testuser", auth_headers=auth_headers) value = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value['name'] def test_perimeter_add_object_with_wrong_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser", policyId='wrong') - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, objects = add_objects("testuser", policyId='wrong', auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_object_with_policy_id_none(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser" + uuid4().hex, "description": "description of {}".format("testuser"), } - req = client.post("/policies/{}/objects/".format(None), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format(None), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_same_object_name_with_new_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects("testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -421,16 +512,17 @@ def test_perimeter_add_same_object_name_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_object_perimeter_id_with_new_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects( "testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -438,17 +530,18 @@ def test_perimeter_add_same_object_perimeter_id_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value1['id']) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value1['id'],auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_object_perimeter_id_with_different_name(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects( "testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -456,14 +549,17 @@ def test_perimeter_add_same_object_perimeter_id_with_different_name(): "name": value1['name'] + 'different', "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_object_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -471,16 +567,20 @@ def test_perimeter_add_same_object_name_with_same_policy_id(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) value = list(objects["objects"].values())[0] - assert req.status_code == 200 - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_object_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -488,16 +588,21 @@ def test_perimeter_add_same_object_perimeter_id_with_existed_policy_id_in_list() "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects( 'testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value = list(objects["objects"].values())[0] - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value['id']) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value['id'], auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_update_object_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -505,26 +610,30 @@ def test_perimeter_update_object_name(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_object_description(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -532,26 +641,30 @@ def test_perimeter_update_object_description(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_object_description_and_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -559,7 +672,8 @@ def test_perimeter_update_object_description_and_name(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] @@ -567,19 +681,21 @@ def test_perimeter_update_object_description_and_name(): 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_object_wrong_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -587,7 +703,8 @@ def test_perimeter_update_object_wrong_id(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] @@ -595,13 +712,17 @@ def test_perimeter_update_object_wrong_id(): 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id + "wrong"), body=data, + headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 def test_perimeter_update_object_name_with_existed_one(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -609,7 +730,8 @@ def test_perimeter_update_object_name_with_existed_one(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data1) + req, objects = add_objects('testuser', policyId=policy_id1, data=data1, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] name = 'testuser' + uuid4().hex @@ -618,7 +740,8 @@ def test_perimeter_update_object_name_with_existed_one(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data2) + req, objects = add_objects('testuser', policyId=policy_id1, data=data2, + auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] perimeter_id2 = value2['id'] @@ -626,59 +749,113 @@ def test_perimeter_update_object_name_with_existed_one(): data3 = { 'name': value1['name'] } - req = client.patch("/objects/{}".format(perimeter_id2), data=json.dumps(data3), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Object Existing' + with pytest.raises(exceptions.ObjectExisting) as exception_info: + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id2), body=data3, + headers=auth_headers) + assert "409: Object Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Object Existing' def test_perimeter_add_object_without_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<br/>", "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', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_perimeter_add_object_blank_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body={}, headers=auth_headers) + assert "Invalid Key :name not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :name not found' def test_perimeter_add_object_with_name_contain_spaces(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "test<a>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', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), body=data, + headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_perimeter_add_object_with_name_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + data = { + "name": " ", + "description": "description of {}".format("test user"), + } + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body =data, headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_delete_object(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] object_id = builder.create_object(policy_id) - req = client.delete("/policies/{}/objects/{}".format(policy_id, object_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/objects/{}".format(policy_id, object_id), headers=auth_headers) + + assert req.status == hug.HTTP_200 def test_perimeter_delete_objects_without_perimeter_id(): - client = utilities.register_client() - req = delete_objects_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Object Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ObjectUnknown) as exception_info: + req = delete_objects_without_perimeter_id(auth_headers=auth_headers) + assert "400: Object Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Object Unknown" -def get_actions(client): - req = client.get("/actions") + +def get_actions(): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(perimeter, "/actions", headers=auth_headers) actions = utilities.get_json(req.data) return req, actions -def add_actions(client, name, policy_id=None, data=None, perimeter_id=None): +def add_actions(name, policy_id=None, data=None, perimeter_id=None, auth_headers=None): + from moon_manager.api import perimeter if not policy_id: 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, @@ -693,60 +870,72 @@ def add_actions(client, name, policy_id=None, data=None, perimeter_id=None): "description": "description of {}".format(name), } if not perimeter_id: - req = client.post("/policies/{}/actions/".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/actions/".format(policy_id), body=data, + headers=auth_headers) else: - req = client.post("/policies/{}/actions/{}".format(policy_id, perimeter_id), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/actions/{}".format(policy_id, perimeter_id), + body=data, headers=auth_headers) actions = utilities.get_json(req.data) return req, actions -def delete_actions_without_perimeter_id(client): - req = client.delete("/actions/{}".format("")) +def delete_actions_without_perimeter_id(auth_headers=None): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/actions/{}".format(""), headers=auth_headers) return req def test_perimeter_get_actions(): - client = utilities.register_client() - req, actions = get_actions(client) - assert req.status_code == 200 + + req, actions = get_actions() + + assert req.status == hug.HTTP_200 assert isinstance(actions, dict) assert "actions" in actions def test_perimeter_add_actions(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, actions = add_actions("testuser", auth_headers=auth_headers) value = list(actions["actions"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value['name'] def test_perimeter_add_action_with_wrong_policy_id(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser", policy_id="wrong") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, actions = add_actions("testuser", policy_id="wrong", auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_action_with_policy_id_none(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser" + uuid4().hex, "description": "description of {}".format("testuser"), } - req = client.post("/policies/{}/actions/".format(None), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions/".format(None), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_same_action_name_with_new_policy_id(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -754,16 +943,18 @@ def test_perimeter_add_same_action_name_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data) + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + auth_headers=auth_headers) value2 = list(action["actions"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_action_perimeter_id_with_new_policy_id(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -771,17 +962,19 @@ def test_perimeter_add_same_action_perimeter_id_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) value2 = list(action["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_action_perimeter_id_with_different_name(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -789,240 +982,323 @@ def test_perimeter_add_same_action_perimeter_id_with_different_name(): "name": value1['name'] + 'different', "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_action_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] - req, action = add_actions(client, "testuser", policy_id=policy_id1) + req, action = add_actions("testuser", policy_id=policy_id1, auth_headers=auth_headers) value1 = list(action["actions"].values())[0] data = { "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_action_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] - req, action = add_actions(client, "testuser", policy_id=policy_id1) + req, action = add_actions("testuser", policy_id=policy_id1, auth_headers=auth_headers) value1 = list(action["actions"].values())[0] data = { "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_actions_without_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<a>", "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', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_perimeter_add_actions_with_name_contain_spaces(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "test<a>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', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_add_subjects_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "description": "description of {}".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"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_add_objects_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "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"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_add_action_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "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"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_perimeter_update_action_name(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_actions_description(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_actions_description_and_name(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_action_wrong_id(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id + "wrong"), body=data, + headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_update_action_name_with_existed_one(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] - req, actions = add_actions(client, "testuser") + req, actions = add_actions("testuser", auth_headers=auth_headers) value2 = list(actions["actions"].values())[0] perimeter_id2 = value2['id'] data = { 'name': value1['name'], } - req = client.patch("/actions/{}".format(perimeter_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Action Existing' + with pytest.raises(exceptions.ActionExisting) as exception_info: + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id2), body=data, + headers=auth_headers) + assert "409: Action Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Action Existing' def test_perimeter_delete_actions(): - client = utilities.register_client() - + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] action_id = builder.create_action(policy_id) - req = client.delete("/policies/{}/actions/{}".format(policy_id, action_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/actions/{}".format(policy_id, action_id), + headers=auth_headers) -def test_delete_subject_without_policy(): - client = utilities.register_client() + assert req.status == hug.HTTP_200 + +def test_delete_subject_assigned_to_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + from moon_manager.db_driver import PolicyManager policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] + subject_id = builder.create_subject(policy_id) + PolicyManager.delete_policy(moon_user_id="admin", policy_id=policy_id) + PolicyManager.delete_subject(moon_user_id="admin", policy_id=None ,perimeter_id=subject_id) - action_id = builder.create_action(policy_id) + req = hug.test.get(perimeter, "subjects/{}".format(subject_id), headers=auth_headers) + assert req.data['subjects'] == {} - req = client.delete("/subjects/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" +def test_delete_subject_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + policies = policy_helper.add_policies() + policy_id = list(policies.keys())[0] -def test_delete_objects_without_policy(): - client = utilities.register_client() + subject_id = builder.create_subject(policy_id) + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/subjects/{}".format(subject_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" + +def test_delete_objects_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - action_id = builder.create_action(policy_id) + object_id = builder.create_object(policy_id) - req = client.delete("/objects/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/objects/{}".format(object_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" -def test_delete_actions_without_policy(): - client = utilities.register_client() +def test_delete_actions_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] action_id = builder.create_action(policy_id) - req = client.delete("/actions/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/actions/{}".format(action_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_perimeter_delete_actions_without_perimeter_id(): - client = utilities.register_client() - req = delete_actions_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Action Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ActionUnknown) as exception_info: + req = delete_actions_without_perimeter_id(auth_headers=auth_headers) + assert "400: Action Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Action Unknown" diff --git a/moon_manager/tests/unit_python/api/test_perimeter_examples.py b/moon_manager/tests/unit_python/api/test_perimeter_examples.py new file mode 100644 index 00000000..0598629c --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_perimeter_examples.py @@ -0,0 +1,55 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +import json + + +# def test_local_perimeter_get_subject(): +# from moon_manager.api import perimeter +# subjects = perimeter.Subjects.get() +# assert isinstance(subjects, dict) +# assert "subjects" in subjects + + + +# def test_http_perimeter_post_subject(): +# from moon_manager.api import perimeter +# result = hug.test.post(perimeter, 'subjects/b34e5a2954944cc59356daa244b8c254', +# body={'name': 'ha'}, +# headers={'Content-Type': 'application/json'}) +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# +# def test_http_perimeter_get_subject_2(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'subjects/b34e5a29-5494-4cc5-9356-daa244b8c254') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# def test_http_perimeter_get_subject_3(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'policies/b34e5a29-5494-4cc5-9356-daa244b8c254/subjects/') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# +# def test_http_perimeter_get_subject_4(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'policies/b34e5a29-5494-4cc5-9356-daa244b8c254/subjects/b34e5a29-5494-4cc5-9356-daa244b8c254') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data diff --git a/moon_manager/tests/unit_python/api/test_policies.py b/moon_manager/tests/unit_python/api/test_policies.py index 76161d53..a07ba725 100644 --- a/moon_manager/tests/unit_python/api/test_policies.py +++ b/moon_manager/tests/unit_python/api/test_policies.py @@ -1,23 +1,32 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON -import json +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_400, HTTP_405, HTTP_409 +import hug from uuid import uuid4 -import api.utilities as utilities +import pytest +from moon_utilities import exceptions from helpers import model_helper from helpers import policy_helper -from helpers import data_builder -def get_policies(client): - req = client.get("/policies") - policies = utilities.get_json(req.data) - return req, policies +def get_policies(auth_headers): + from moon_manager.api import policy + req = hug.test.get(policy, "policies", headers=auth_headers) + return req -def add_policies(client, name): +def add_policies(name, auth_headers): + from moon_manager.api import policy req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -26,106 +35,153 @@ def add_policies(client, name): "model_id": model_id, "genre": "genre" } - req = client.post("/policies", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policies = utilities.get_json(req.data) - return req, policies + req = hug.test.post(policy, "policies", data, headers=auth_headers) + return req -def delete_policies_without_id(client): - req = client.delete("/policies/{}".format("")) +def delete_policies_without_id(auth_headers): + from moon_manager.api import policy + req = hug.test.delete(policy, "policies/{}".format(""), headers=auth_headers) return req def test_get_policies(): - client = utilities.register_client() - req, policies = get_policies(client) - assert req.status_code == 200 - assert isinstance(policies, dict) - assert "policies" in policies + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = get_policies(auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "policies" in req.data def test_add_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} 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) - value = list(policies["policies"].values())[0] - assert "policies" in policies + req = add_policies(policy_name, auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + value = list(req.data["policies"].values())[0] + assert "policies" in req.data assert value['name'] == policy_name assert value["description"] == "description of {}".format(policy_name) def test_add_policies_without_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() data = { "name": policy_name, "description": "description of {}".format(policy_name), "model_id": "", "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) - assert req.status_code == 200 + assert req.status == HTTP_200 def test_add_policies_with_same_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = uuid4().hex policy_name = name - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 200 - assert isinstance(policies, dict) - value = list(policies["policies"].values())[0] - assert "policies" in policies + req = add_policies(policy_name, auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + value = list(req.data["policies"].values())[0] + assert "policies" in req.data assert value['name'] == policy_name assert value["description"] == "description of {}".format(policy_name) - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req = add_policies(policy_name, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_add_policy_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policy_name = "" - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Content Error' + with pytest.raises(exceptions.PolicyContentError) as exception_info: + req = add_policies(policy_name, auth_headers=auth_headers) + assert "400: Policy Content Error" == str(exception_info.value) + # assert req.status == HTTP_400 + # assert req.data["message"] == '400: Policy Content Error' -def test_update_policies_with_model(): +def test_add_policy_with_model_has_no_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import policy + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policy_name = "testuser" + uuid4().hex - client = utilities.register_client() + req = model_helper.add_model_without_meta_rule() + model_id = list(req.keys())[0] data = { "name": policy_name, "description": "description of {}".format(policy_name), - "model_id": "", + "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + hug.test.post(policy, "policies/", data, headers=auth_headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + + +def test_add_policy_with_model_has_blank_subject_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import policy + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policy_name = "testuser" + uuid4().hex + req = model_helper.add_model_with_blank_subject_meta_rule() model_id = list(req.keys())[0] data = { - "name": policy_name + "-2", + "name": policy_name, "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 - assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2' + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + hug.test.post(policy, "policies/", data, headers=auth_headers) + assert "400: Meta Rule Error" == str(exception_info.value) + + + +# FIXME: uncomment when model API is re-inserted +# def test_update_policies_with_model(): +# from moon_manager.api import policy +# policy_name = "testuser" + uuid4().hex +# data = { +# "name": policy_name, +# "description": "description of {}".format(policy_name), +# "model_id": "", +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id = next(iter(req.data['policies'])) +# req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.data.keys())[0] +# data = { +# "name": policy_name + "-2", +# "description": "description of {}".format(policy_name), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.patch("policies/{}".format(policy_id), data) +# assert req.status == HTTP_200 +# assert req.data['policies'][policy_id]['name'] == policy_name + '-2' def test_update_policies_name_success(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -134,9 +190,8 @@ def test_update_policies_name_success(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": policy_name + "-2", @@ -144,26 +199,24 @@ def test_update_policies_name_success(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 - assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2' + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert req.status == HTTP_200 + assert req.data['policies'][policy_id]['name'] == policy_name + '-2' -def test_update_policies_model_unused(): +def test_update_blank_policies_with_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = uuid4().hex - client = utilities.register_client() - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(req.keys())[0] data = { "name": policy_name, "description": "description of {}".format(policy_name), - "model_id": model_id, + "model_id": "", "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -172,55 +225,82 @@ def test_update_policies_model_unused(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert req.status == HTTP_200 -def test_update_policy_name_with_existed_one(): - policy_name1 = "testuser" + uuid4().hex - client = utilities.register_client() +def test_update_policies_model_unused(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + policy_name = uuid4().hex req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { - "name": policy_name1, - "description": "description of {}".format(policy_name1), + "name": policy_name, + "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id1 = next(iter(utilities.get_json(req.data)['policies'])) - - policy_name2 = "testuser" + uuid4().hex - client = utilities.register_client() + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { - "name": policy_name2, - "description": "description of {}".format(policy_name2), + "name": policy_name, + "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id2 = next(iter(utilities.get_json(req.data)['policies'])) - data = { - "name": policy_name1, - "description": "description of {}".format(policy_name1), - "model_id": model_id, - "genre": "genre" - } - req = client.patch("/policies/{}".format(policy_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyUpdateError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy update error" == str(exception_info.value) + + +# FIXME: uncomment when model API is re-inserted +# def test_update_policy_name_with_existed_one(): +# from moon_manager.api import policy +# policy_name1 = "testuser" + uuid4().hex +# req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.keys())[0] +# data = { +# "name": policy_name1, +# "description": "description of {}".format(policy_name1), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id1 = next(iter(req.data['policies'])) +# +# policy_name2 = "testuser" + uuid4().hex +# eq = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.data.keys())[0] +# data = { +# "name": policy_name2, +# "description": "description of {}".format(policy_name2), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id2 = next(iter(req.data['policies'])) +# +# data = { +# "name": policy_name1, +# "description": "description of {}".format(policy_name1), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.patch(policy, "policies/{}".format(policy_id2), data) +# assert req.status == HTTP_409 +# assert req.data["message"] == '409: Policy Already Exists' def test_update_policies_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -229,9 +309,8 @@ def test_update_policies_with_empty_name(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": "", @@ -239,15 +318,18 @@ def test_update_policies_with_empty_name(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Content Error' + with pytest.raises(exceptions.PolicyContentError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy Content Error" == str(exception_info.value) + # assert req.status == HTTP_400 + # assert req.data["message"] == '400: Policy Content Error' def test_update_policies_with_blank_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -256,9 +338,8 @@ def test_update_policies_with_blank_model(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": policy_name, @@ -267,76 +348,77 @@ def test_update_policies_with_blank_model(): "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 + with pytest.raises(exceptions.PolicyUpdateError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy update error" == str(exception_info.value) -def test_update_policies_connected_to_rules_with_blank_model(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.get("/policies") - data = utilities.get_json(req.data) - for policy_obj_id in data['policies']: - if policy_obj_id == policy_id: - policy = data['policies'][policy_obj_id] - policy['model_id'] = '' - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(policy), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy update error' +# FIXME: uncomment when model API is re-inserted +# def test_update_policies_connected_to_rules_with_blank_model(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.get(policy, "policies") +# for policy_obj_id in req.data['policies']: +# if policy_obj_id == policy_id: +# policy = req.data['policies'][policy_obj_id] +# policy['model_id'] = '' +# req = hug.test.patch("/policies/{}".format(policy_id), req.data) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy update error' def test_delete_policies(): - client = utilities.register_client() - - policy = policy_helper.add_policies() - policy_id = list(policy.keys())[0] - - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 200 - - -def test_delete_policy_with_dependencies_rule(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Rule Error' - - -def test_delete_policy_with_dependencies_subject_data(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.delete("/policies/{}/rules/{}".format(policy_id, next(iter(rules['rules'])))) - assert req.status_code == 200 - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Data Error' - - -def test_delete_policy_with_dependencies_perimeter(): - client = utilities.register_client() - policy = policy_helper.add_policies() - policy_id = next(iter(policy)) - - data = { - "name": 'testuser'+uuid4().hex, - "description": "description of {}".format(uuid4().hex), - "password": "password for {}".format(uuid4().hex), - "email": "{}@moon".format(uuid4().hex) - } - req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 200 - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Perimeter Error' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + _policy = policy_helper.add_policies() + policy_id = list(_policy.keys())[0] + req = hug.test.delete(policy, "policies/{}".format(policy_id), headers=auth_headers) + assert req.status == HTTP_200 + + +# FIXME: uncomment when rule API is re-inserted +# def test_delete_policy_with_dependencies_rule(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Rule Error' + + +# FIXME: uncomment when perimeter API is re-inserted +# def test_delete_policy_with_dependencies_subject_data(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.delete(policy, "policies/{}/rules/{}".format(policy_id, next(iter(rules['rules'])))) +# assert req.status == HTTP_200 +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Data Error' + + +# FIXME: uncomment when perimeter API is re-inserted +# def test_delete_policy_with_dependencies_perimeter(): +# from moon_manager.api import policy +# _policy = policy_helper.add_policies() +# policy_id = next(iter(_policy)) +# +# data = { +# "name": 'testuser'+uuid4().hex, +# "description": "description of {}".format(uuid4().hex), +# "password": "password for {}".format(uuid4().hex), +# "email": "{}@moon".format(uuid4().hex) +# } +# req = hug.test.post(policy, "policies/{}/subjects".format(policy_id), data) +# +# assert req.status == HTTP_200 +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Perimeter Error' def test_delete_policies_without_id(): - client = utilities.register_client() - req = delete_policies_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_policies_without_id(auth_headers=auth_headers) + assert req.status == HTTP_405 diff --git a/moon_manager/tests/unit_python/api/test_rules.py b/moon_manager/tests/unit_python/api/test_rules.py index a3c21839..2bb7a96f 100644 --- a/moon_manager/tests/unit_python/api/test_rules.py +++ b/moon_manager/tests/unit_python/api/test_rules.py @@ -1,114 +1,317 @@ -import api.utilities as utilities +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import pytest +from moon_utilities import exceptions import json from helpers import data_builder as builder -from uuid import uuid4 from helpers import policy_helper +from helpers import rules_helper +import hug + +def get_rules(policy_id): + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_rules(client, policy_id): - req = client.get("/policies/{}/rules".format(policy_id)) - rules = utilities.get_json(req.data) + req = hug.test.get(rules, "/policies/{}/rules".format(policy_id), headers=auth_headers) + rules = req.data return req, rules -def add_rules_without_policy_id(client): +def add_rules_without_policy_id(headers): + from moon_manager.api import rules subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() data = { "meta_rule_id": meta_rule_id, "rule": [subject_category_id, object_category_id, action_category_id], - "instructions": ( + "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) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(None), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def add_rules_without_meta_rule_id(client, policy_id): +def add_rules_without_meta_rule_id(policy_id, headers): + from moon_manager.api import rules data = { "meta_rule_id": "", "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def add_rules_without_rule(client, policy_id): +def add_rules_without_rule(policy_id, headers): + from moon_manager.api import rules data = { "meta_rule_id": "meta_rule_id1", - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def delete_rules(client, policy_id, meta_rule_id): - req = client.delete("/policies/{}/rules/{}".format(policy_id, meta_rule_id)) +def delete_rules(policy_id, meta_rule_id, headers): + from moon_manager.api import rules + req = hug.test.delete(rules, "/policies/{}/rules/{}".format(policy_id, meta_rule_id), + headers=headers) return req -def test_get_rules(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, rules = get_rules(client, policy_id) - assert req.status_code == 200 +def update_rule(policy_id, rule_id, instructions, headers): + from moon_manager.api import rules + req = hug.test.patch(rules, "/policies/{}/rules/{}".format(policy_id, rule_id), + headers=headers, + body=instructions) + return req + + +def test_add_rules_with_invalid_decision_instructions(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + + data = { + "meta_rule_id": meta_rule_id, + "rule": [subject_category_id, object_category_id, action_category_id], + "instructions": [ + {"decision": "invalid"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.RuleContentError) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: Rule Error" == str(exception_info.value) + + +def test_add_rules_with_meta_rule_not_linked_with_policy_model(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + policy_id = builder.create_new_policy()[-1] + meta_rule_id = builder.create_new_meta_rule()[-1] + + data = { + "meta_rule_id": meta_rule_id, + "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.MetaRuleNotLinkedWithPolicyModel) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: MetaRule Not Linked With Model - Policy" == str(exception_info.value) + + +def test_add_rules_with_invalid_rule(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + + 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": [obj_data_id, sub_data_id, act_data_id], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.RuleContentError) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: Rule Error" == str(exception_info.value) + + +def test_add_rules_with_no_given_decision_instructions(policy_id=None): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + 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": [], + "enabled": True + } + + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + + assert req.status == hug.HTTP_200 + + default_instruction = {"decision": "grant"} + rules = req.data['rules'] + rule_id = next(iter(req.data['rules'])) + assert rules[rule_id]["instructions"][0] == default_instruction + + +def test_get_rules(policy_id=None): + if policy_id == None: + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + + req, rules = get_rules(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(rules, dict) assert "rules" in rules return req, rules def test_add_rules(): - client = utilities.register_client() - req, rules, policy = builder.add_rules(client, ) - assert req.status_code == 200 + req, rules, policy = builder.add_rules() + assert req.status == hug.HTTP_200 def test_add_rules_without_policy_id(): - client = utilities.register_client() - req, rules = add_rules_without_policy_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + from moon_manager.api import rules + + subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() + data = { + "meta_rule_id": meta_rule_id, + "rule": [subject_category_id, object_category_id, action_category_id], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + headers = rules_helper.get_headers() + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(rules, "/policies/{}/rules".format(None), body=json.dumps(data), + headers=headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert 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 == 400 +# assert req.status == 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 == 400 - assert json.loads(req.data)["message"] == 'Invalid Key :rule not found' + from moon_utilities.auth_functions import get_api_key_for_user + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req, rules = add_rules_without_rule(policy_id, headers=auth_headers) + assert "Invalid Key :rule not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :rule not found' + + +def test_update_rule_without_body(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + req = update_rule(policy_id, rule_id, instructions=None, headers=auth_headers) + + assert req.status == hug.HTTP_400 + + +def test_update_rule_without_instructions_in_body(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + data = {"instruction": [ # faute de frappe + {"decision": "deny"}, + ]} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + req = update_rule(policy_id, rule_id, instructions=None, headers=auth_headers) + + assert req.status == hug.HTTP_400 + + +def test_update_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + data = {"instructions": [ + {"decision": "deny"}, + ]} + req = update_rule(policy_id, rule_id, data, headers=auth_headers) + + rules = get_rules(policy_id)[1]['rules']['rules'] + + rule = None + for rule_ in rules: + if rule_['id'] == rule_id: + rule = rule_ + break + + assert req.status == hug.HTTP_200 and rule['instructions'][0]['decision'] == "deny" def test_delete_rules_with_invalid_parameters(): - client = utilities.register_client() - req = delete_rules(client, "", "") - assert req.status_code == 404 - # assert json.loads(req.data)["message"] == 'Invalid Key :rule not found' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_rules("", "", headers=auth_headers) + assert req.status == hug.HTTP_405 def test_delete_rules_without_policy_id(): - client = utilities.register_client() + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} 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) @@ -116,14 +319,15 @@ def test_delete_rules_without_policy_id(): data = { "meta_rule_id": meta_rule_id, "rule": [sub_data_id, obj_data_id, act_data_id], - "instructions": ( + "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) + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + req, added_rules = get_rules(policy_id) id = list(added_rules["rules"]["rules"])[0]["id"] - rules = delete_rules(client, None, id) - assert rules.status_code == 200 + rules = delete_rules(None, id, headers=auth_headers) + assert rules.status == hug.HTTP_200 diff --git a/moon_manager/tests/unit_python/api/test_slaves.py b/moon_manager/tests/unit_python/api/test_slaves.py new file mode 100644 index 00000000..29d5e62e --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_slaves.py @@ -0,0 +1,90 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_400, HTTP_405 +import hug +from uuid import uuid4 +from helpers import data_builder as builder + + +def test_get_slaves(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + req = hug.test.get(slave, 'slaves/', headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "slaves" in req.data + for slave in req.data.get("slaves"): + assert "name" in slave + assert "description" in slave + assert "status" in slave + assert "server_ip" in slave + assert "port" in slave + + +def test_add_slave(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:10000") + mocker.patch("subprocess.Popen", return_value=True) + data = { + "name": "test_slave_" + uuid4().hex, + "description": "description of test_slave" + } + req = hug.test.post(slave, "slave/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + found = False + assert "slaves" in req.data + for value in req.data["slaves"].values(): + assert "name" in value + assert "description" in value + assert "api_key" in value + assert "process" in value + assert "log" in value + assert "extra" in value + if value['name'] == data['name']: + found = True + assert value["description"] == "description of test_slave" + assert "port" in value.get("extra") + assert "status" in value.get("extra") + assert "server_ip" in value.get("extra") + break + assert found + + +def test_delete_slave(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:10000") + mocker.patch("subprocess.Popen", return_value=True) + data = { + "name": "test_slave_" + uuid4().hex, + "description": "description of test_slave" + } + req = hug.test.post(slave, "slave/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + req = hug.test.get(slave, 'slaves/', headers=auth_headers) + success_req = None + for key, value in req.data['slaves'].items(): + if value['name'] == data['name']: + success_req = hug.test.delete(slave, 'slave/{}'.format(key), headers=auth_headers) + break + assert success_req + assert success_req.status == HTTP_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 deleted file mode 100644 index 6e93ed28..00000000 --- a/moon_manager/tests/unit_python/api/test_unit_models.py +++ /dev/null @@ -1,352 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import json -import api.utilities as utilities -from helpers import data_builder as builder -from helpers import policy_helper -from helpers import model_helper -from uuid import uuid4 - - -def get_models(client): - req = client.get("/models") - models = utilities.get_json(req.data) - return req, models - - -def add_models(client, name, data=None): - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - - if not data: - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def update_model(client, name, model_id): - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def add_model_without_meta_rules_ids(client, name): - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def add_model_with_empty_meta_rule_id(client, name): - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [""] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def update_model_without_meta_rules_ids(client, model_id): - name = "model_id" + uuid4().hex - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def delete_models(client, name): - request, models = get_models(client) - for key, value in models['models'].items(): - if value['name'] == name: - req = client.delete("/models/{}".format(key)) - break - return req - - -def delete_models_without_id(client): - req = client.delete("/models/{}".format("")) - return req - - -def test_delete_model_assigned_to_policy(): - policy_name = "testuser" + uuid4().hex - client = utilities.register_client() - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(req.keys())[0] - data = { - "name": policy_name, - "description": "description of {}".format(policy_name), - "model_id": model_id, - "genre": "genre" - } - req = client.post("/policies", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - req = client.delete("/models/{}".format(model_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Model With Policy Error' - - -def clean_models(): - client = utilities.register_client() - req, models = get_models(client) - for key, value in models['models'].items(): - print(key) - print(value) - client.delete("/models/{}".format(key)) - - -def test_get_models(): - client = utilities.register_client() - req, models = get_models(client) - assert req.status_code == 200 - assert isinstance(models, dict) - assert "models" in models - - -def test_add_models(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "testuser") - assert req.status_code == 200 - assert isinstance(models, dict) - model_id = list(models["models"])[0] - assert "models" in models - assert models['models'][model_id]['name'] == "testuser" - assert models['models'][model_id]["description"] == "description of {}".format("testuser") - - -def test_delete_models(): - client = utilities.register_client() - req = delete_models(client, "testuser") - assert req.status_code == 200 - - -def test_update_models_with_assigned_policy(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - value = { - "name": "test_policy" + uuid4().hex, - "model_id": model_id, - "description": "test", - } - policy = policy_helper.add_policies(value=value) - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Model With Policy Error" - - -def test_update_models_with_no_assigned_policy(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 200 - - -def test_add_models_with_meta_rule_key(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Invalid Key :meta_rules not found" - - -def test_delete_models_without_id(): - client = utilities.register_client() - req = delete_models_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Model Unknown" - - -def test_add_model_with_empty_name(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "<br/>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_add_model_with_name_contain_space(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "test<br>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_add_model_with_name_space(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Model Unknown' - - -def test_add_model_with_empty_meta_rule_id(): - clean_models() - client = utilities.register_client() - req, meta_rules = add_model_with_empty_meta_rule_id(client, "testuser") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Meta Rule Unknown' - - -def test_add_model_with_existed_name(): - clean_models() - client = utilities.register_client() - name = uuid4().hex - req, models = add_models(client, name) - assert req.status_code == 200 - req, models = add_models(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Model Error' - - -def test_add_model_with_existed_meta_rules_list(): - clean_models() - client = utilities.register_client() - name = uuid4().hex - - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - name = uuid4().hex - req, models = add_models(client=client, name=name, data=data) - assert req.status_code == 200 - - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req, models = add_models(client=client, name=name, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Model Error' - - -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 == 200 - # assert json.loads(req.data)["message"] == "Key: 'meta_rules', [Empty Container]" - - -def test_update_model(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, "testuser", model_id) - assert req_update[0].status_code == 200 - 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") - - -def test_update_model_name_with_space(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, " ", model_id) - assert req_update[0].status_code == 400 - assert req_update[1]["message"] == '400: Model Unknown' - - -def test_update_model_with_empty_name(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, "", model_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Model Unknown' - - -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 == 400 - assert json.loads(req_update[0].data)["message"] == "400: Model Unknown" - - -def test_update_meta_rules_without_name(): - client = utilities.register_client() - req_update = update_model(client, "<a></a>", "1234567") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)[ - "message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_update_meta_rules_without_meta_rules(): - value = { - "name": "mls_model_id" + uuid4().hex, - "description": "test", - "meta_rules": [] - } - model = model_helper.add_model(value=value) - model_id = list(model.keys())[0] - client = utilities.register_client() - req_update = update_model_without_meta_rules_ids(client, model_id) - assert req_update[0].status_code == 200 diff --git a/moon_manager/tests/unit_python/api/utilities.py b/moon_manager/tests/unit_python/api/utilities.py index 2e51fec8..baf59a51 100644 --- a/moon_manager/tests/unit_python/api/utilities.py +++ b/moon_manager/tests/unit_python/api/utilities.py @@ -1,26 +1,16 @@ -import json -from uuid import uuid4 +# Software Name: MOON -def get_json(data): - return json.loads(data.decode("utf-8")) +# Version: 5.4 +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 -def register_client(): - import moon_manager.server - server = moon_manager.server.create_server() - client = server.app.test_client() - return client +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. -def 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 +import json +from uuid import uuid4 +def get_json(data): + return data;#json.loads(data.decode("utf-8")) diff --git a/moon_manager/tests/unit_python/conftest.py b/moon_manager/tests/unit_python/conftest.py index 90a27e54..702f3c19 100644 --- a/moon_manager/tests/unit_python/conftest.py +++ b/moon_manager/tests/unit_python/conftest.py @@ -1,254 +1,164 @@ -import base64 -import json -import logging +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import os import pytest import requests_mock +import yaml +import mock_keystone +import mock_nova +import mock_engine +import mock_slaves + + +__CONF = """ +database: + url: sqlite:////tmp/database_test.db + driver: moon_manager.plugins.sql + migration_dir: moon_manager.api.db.migrations + +management: + url: http://127.0.0.1:8000 + user: admin + password: admin + token_file: db.json + +orchestration: + driver: moon_manager.plugins.pyorchestrator + connection: local + slaves: + port: 10000...10100 + pipelines: + port: 20000...20100 + +information: + user: admin + password: p4ssw0rd + domain: default + project: admin + check_token: false + certificate: false + url: http://keystone:5000/v3 + subjects: + drivers: + moon_manager.plugins.moon_keystone_plugin: + url: http://keystone:5000/v3 + objects: + drivers: + moon_manager.plugins.moon_nova_plugin: + url: http://keystone:5000/compute/v2.1 + + global_attrs: + driver: moon_manager.plugins.global_attrs + attributes: + mode: + values: + - build + - run + default: run + url: file:/tmp/mode + #url: https://127.0.0.1:8080/mode + #url: mysql+pymysql://moon:p4sswOrd1@db/moon_mode + #url: sqlite:////tmp/database.db + #url: driver://moon_manager.plugins.my_plugin -CONF = { - "openstack": { - "keystone": { - "url": "http://keystone:5000/v3", - "user": "admin", - "check_token": False, - "password": "p4ssw0rd", - "domain": "default", - "certificate": False, - "project": "admin" - } - }, - "components": { - "wrapper": { - "bind": "0.0.0.0", - "port": 8080, - "container": "wukongsun/moon_wrapper:v4.3", - "timeout": 5, - "hostname": "wrapper" - }, - "manager": { - "bind": "0.0.0.0", - "port": 8082, - "container": "wukongsun/moon_manager:v4.3", - "hostname": "manager" - }, - "port_start": 31001, - "orchestrator": { - "bind": "0.0.0.0", - "port": 8083, - "container": "wukongsun/moon_orchestrator:v4.3", - "hostname": "orchestrator" - }, - "pipeline": { - "interface": { - "bind": "0.0.0.0", - "port": 8080, - "container": "wukongsun/moon_interface:v4.3", - "hostname": "interface" - }, - "authz": { - "bind": "0.0.0.0", - "port": 8081, - "container": "wukongsun/moon_authz:v4.3", - "hostname": "authz" - }, - } - }, - "logging": { - "handlers": { - "file": { - "filename": "/tmp/moon.log", - "class": "logging.handlers.RotatingFileHandler", - "level": "DEBUG", - "formatter": "custom", - "backupCount": 3, - "maxBytes": 1048576 - }, - "console": { - "class": "logging.StreamHandler", - "formatter": "brief", - "level": "INFO", - "stream": "ext://sys.stdout" - } - }, - "formatters": { - "brief": { - "format": "%(levelname)s %(name)s %(message)-30s" - }, - "custom": { - "format": "%(asctime)-15s %(levelname)s %(name)s %(message)s" - } - }, - "root": { - "handlers": [ - "console" - ], - "level": "ERROR" - }, - "version": 1, - "loggers": { - "moon": { - "handlers": [ - "console", - "file" - ], - "propagate": False, - "level": "DEBUG" - } - } - }, - "slave": { - "name": None, - "master": { - "url": None, - "login": None, - "password": None - } - }, - "docker": { - "url": "tcp://172.88.88.1:2376", - "network": "moon" - }, - "database": { - "url": "sqlite:///database.db", - # "url": "mysql+pymysql://moon:p4sswOrd1@db/moon", - "driver": "sql" - }, - "messenger": { - "url": "rabbit://moon:p4sswOrd1@messenger:5672/moon" - }, -} - -COMPONENTS = ( - "logging", - "openstack/keystone", - "database", - "slave", - "components/manager", - "components/orchestrator" -) - -PODS = { - "pods": { - "721760dd-de5f-11e7-8001-3863bbb766f3": [ - { - "pdp_id": "b3d3e18abf3340e8b635fd49e6634ccd", - "port": 8080, - "genre": "interface", - "name": "interface-paltry", - "keystone_project_id": "a64beb1cc224474fb4badd43173e7101", - "namespace": "moon", - "container": "wukongsun/moon_interface:v4.3" - }, - { - "pdp_id": "b3d3e18abf3340e8b635fd49e6634ccd", - "meta_rule_id": "f8f49a779ceb47b3ac810f01ef71b4e0", - "port": 8081, - "genre": "authz", - "name": "authz-economic", - "policy_id": "f8f49a779ceb47b3ac810f01ef71b4e0", - "keystone_project_id": "a64beb1cc224474fb4badd43173e7101", - "namespace": "moon", - "container": "wukongsun/moon_authz:v4.3" - } - ] - } -} - -SLAVES = { - "slaves": [ - { - "context": - { - "cluster": "kubernetes", - "user": "kubernetes-admin" - }, - "name": "kubernetes-admin@kubernetes", - "configured": True, - "wrapper_name": "mywrapper", - "ip": "NC", - "port": 31002, - "internal_port": 8080 - } - ] -} - - -def get_b64_conf(component=None): - if component in CONF: - return base64.b64encode( - json.dumps( - CONF[component]).encode('utf-8') + b"\n").decode('utf-8') - elif "/" in component: - key1, _, key2 = component.partition("/") - return base64.b64encode( - json.dumps( - CONF[key1][key2]).encode('utf-8') + b"\n").decode('utf-8') - else: - return base64.b64encode( - json.dumps(CONF).encode('utf-8') + b"\n").decode('utf-8') +plugins: + directory: /var/moon/plugins + +components: + manager: + port: 8080 + bind: 0.0.0.0 + hostname: manager + +logging: + version: 1 + + formatters: + brief: + format: "%(levelname)s %(name)s %(message)-30s" + custom: + format: "%(asctime)-15s %(levelname)s %(name)s %(message)s" + + handlers: + console: + class : logging.StreamHandler + formatter: custom + level : INFO + stream : ext://sys.stdout + file: + class : logging.handlers.RotatingFileHandler + formatter: custom + level : DEBUG + filename: /tmp/moon.log + maxBytes: 1048576 + backupCount: 3 + + loggers: + moon: + level: DEBUG + handlers: [console, file] + propagate: no + + root: + level: ERROR + handlers: [console] +""" @pytest.fixture(autouse=True) def no_requests(monkeypatch): """ Modify the response from Requests module """ + global manager_api_key with requests_mock.Mocker(real_http=True) as m: - for component in COMPONENTS: - m.register_uri( - 'GET', 'http://consul:8500/v1/kv/{}'.format(component), - json=[{'Key': component, 'Value': get_b64_conf(component)}] - ) - m.register_uri( - 'POST', 'http://keystone:5000/v3/auth/tokens', - headers={'X-Subject-Token': "111111111"} - ) - m.register_uri( - 'DELETE', 'http://keystone:5000/v3/auth/tokens', - headers={'X-Subject-Token': "111111111"} - ) - - 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( - requests_mock.ANY, '/v3/users', - additional_matcher=match_request_text, - json={"users": {}} - ) - m.register_uri( - 'POST', 'http://keystone:5000/v3/users/', - json={"users": [{"id": "1111111111111"}]} - ) - m.register_uri( - 'POST', 'http://orchestrator:8083/pods', - json=PODS, - headers={"content-type": "application/json"} - ) - m.register_uri( - 'GET', 'http://orchestrator:8083/pods', - json=PODS - ) - m.register_uri( - 'GET', 'http://localhost/slaves', - json=SLAVES - ) - m.register_uri( - 'DELETE', 'http://orchestrator:8083/pods/{}'.format(list([PODS['pods'].keys()])[0]), - headers={"content-type": "application/json"} - ) - - print("Start populating the DB.") - from python_moondb.db_manager import init_engine, main - engine = init_engine() - print("engine={}".format(engine)) - main("upgrade", logging.getLogger("db_manager"), engine) - print("End populating the DB.") - yield m + try: + os.remove("/tmp/database_test.db") + except FileNotFoundError: + pass + try: + os.remove("/tmp/moon.pwd") + except FileNotFoundError: + pass + print("Configure...") + from moon_manager.api.configuration import init_database, set_configuration + set_configuration(yaml.safe_load(__CONF)) + print("Create a new user") + from moon_utilities.auth_functions import add_user, init_db, get_api_key_for_user + init_db() + try: + user = add_user("admin", "admin") + manager_api_key = user["api_key"] + except KeyError: + print("User already exists") + manager_api_key = get_api_key_for_user("admin") + print("Initialize the database") + init_database() + from moon_manager import db_driver, orchestration_driver + + db_driver.init() + orchestration_driver.init() + + mock_keystone.register_keystone(m) + mock_nova.register_nova(m) + mock_engine.register_engine(m) + mock_slaves.register_slaves(m) -# @pytest.fixture(autouse=True, scope="session") -# def manage_database(): -# from moon_db.db_manager import init_engine, run -# engine = init_engine() -# run("upgrade", logging.getLogger("db_manager"), engine) -# yield -# print("Will close the DB") + from moon_manager.pip_driver import InformationManager + for category in InformationManager: + for manager in InformationManager[category]: + manager.set_auth() + + yield m + for category in InformationManager: + for manager in InformationManager[category]: + manager.unset_auth() diff --git a/moon_manager/tests/unit_python/helpers/__init__.py b/moon_manager/tests/unit_python/helpers/__init__.py index e69de29b..582be686 100644 --- a/moon_manager/tests/unit_python/helpers/__init__.py +++ b/moon_manager/tests/unit_python/helpers/__init__.py @@ -0,0 +1,11 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + diff --git a/moon_manager/tests/unit_python/helpers/assignment_helper.py b/moon_manager/tests/unit_python/helpers/assignment_helper.py index 22a56e38..05d13c46 100644 --- a/moon_manager/tests/unit_python/helpers/assignment_helper.py +++ b/moon_manager/tests/unit_python/helpers/assignment_helper.py @@ -1,49 +1,57 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + def get_action_assignments(policy_id, action_id=None, category_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 index 6c419ca8..bbb04e09 100644 --- a/moon_manager/tests/unit_python/helpers/category_helper.py +++ b/moon_manager/tests/unit_python/helpers/category_helper.py @@ -1,40 +1,47 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + 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) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_subject_category(moon_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) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_subject_categories(moon_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) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_object_category(moon_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) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_object_categories(moon_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) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_action_category(moon_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) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_action_categories(moon_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 index 91808cbe..e2799375 100644 --- a/moon_manager/tests/unit_python/helpers/data_builder.py +++ b/moon_manager/tests/unit_python/helpers/data_builder.py @@ -1,15 +1,21 @@ -# 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'. +# Software Name: MOON +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug 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 from uuid import uuid4 @@ -55,7 +61,7 @@ def create_pdp(policies_ids): value = { "name": "test_pdp", "security_pipeline": policies_ids, - "keystone_project_id": "keystone_project_id1", + "vim_project_id": "vim_project_id1", "description": "...", } return value @@ -96,7 +102,7 @@ def create_new_policy(subject_category_name=None, object_category_name=None, def create_new_meta_rule(subject_category_name=None, object_category_name=None, - action_category_name=None, meta_rule_name=None): + action_category_name=None, meta_rule_name=None, empty=None): if not subject_category_name: subject_category_name = "subjectCategory_" + uuid4().hex if not object_category_name: @@ -116,6 +122,12 @@ def create_new_meta_rule(subject_category_name=None, object_category_name=None, "object_categories": [object_category_id], "action_categories": [action_category_id] } + if empty == 'subject': + value["subject_categories"] = [] + if empty == 'object': + value["object_categories"] = [] + if empty == 'action': + value["action_categories"] = [] meta_rule = add_meta_rule(value=value) return subject_category_id, object_category_id, action_category_id, list(meta_rule.keys())[0] @@ -179,7 +191,10 @@ def create_action_data(policy_id, category_id): def get_policy_id_with_subject_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -193,13 +208,16 @@ def get_policy_id_with_subject_assignment(): "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'}) + response = hug.test.post(assignments, "/policies/{}/subject_assignments/".format(policy_id), + body=data, headers=auth_headers) return policy_id def get_policy_id_with_object_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -214,13 +232,16 @@ def get_policy_id_with_object_assignment(): "data_id": data_id } - client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + hug.test.post(assignments, "policies/{}/object_assignments".format(policy_id), body=data, + headers=auth_headers) return policy_id def get_policy_id_with_action_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + 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, @@ -234,12 +255,16 @@ def get_policy_id_with_action_assignment(): "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'}) + hug.test.post(assignments, "policies/{}/action_assignments".format(policy_id), body =data, + headers=auth_headers) return policy_id -def add_rules(client): +def add_rules(): + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + sub_id, obj_id, act_id, meta_rule_id, policy_id = create_new_policy("sub_cat" + uuid4().hex, "obj_cat" + uuid4().hex, "act_cat" + uuid4().hex) @@ -249,12 +274,10 @@ def add_rules(client): data = { "meta_rule_id": meta_rule_id, "rule": [sub_data_id, obj_data_id, act_data_id], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) - return req, rules, policy_id + req = hug.test.post(rules, "policies/{}/rules".format(policy_id), body=data, headers=auth_headers) + return req, req.data, policy_id diff --git a/moon_manager/tests/unit_python/helpers/data_helper.py b/moon_manager/tests/unit_python/helpers/data_helper.py index e1c05640..cb1ee38c 100644 --- a/moon_manager/tests/unit_python/helpers/data_helper.py +++ b/moon_manager/tests/unit_python/helpers/data_helper.py @@ -1,99 +1,106 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + 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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_action_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_action_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_action_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_action_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_action_data(moon_user_id="admin", policy_id=policy_id, data_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_object_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_object_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_object_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_object_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_object_data(moon_user_id="admin", policy_id=policy_id, data_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_subject_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.set_subject_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_subject_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_subject_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_subject_data(moon_user_id="admin", policy_id=policy_id, data_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_actions(moon_user_id="admin", policy_id=policy_id, perimeter_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_action(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_action(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_action("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_action(moon_user_id="admin", policy_id=policy_id, perimeter_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_objects(moon_user_id="admin", policy_id=policy_id, perimeter_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_object(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_object(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_object("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_object(moon_user_id="admin", policy_id=policy_id, perimeter_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_subjects(moon_user_id="admin", policy_id=policy_id, perimeter_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) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_subject(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_subject(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_subject("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_subject(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def get_available_metadata(policy_id): - from python_moondb.core import PolicyManager - return PolicyManager.get_available_metadata("", policy_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_available_metadata(moon_user_id="admin", policy_id=policy_id) diff --git a/moon_manager/tests/unit_python/helpers/import_export_helper.py b/moon_manager/tests/unit_python/helpers/import_export_helper.py new file mode 100644 index 00000000..1ba94fd0 --- /dev/null +++ b/moon_manager/tests/unit_python/helpers/import_export_helper.py @@ -0,0 +1,287 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from api import test_models as test_models +from api import test_policies as test_policies +from api import test_perimeter as test_perimeter +from api import test_meta_data as test_categories +from api import test_data as test_data +from api import test_meta_rules as test_meta_rules +from api import test_assignement as test_assignments +from api import test_rules as test_rules +import logging +import hug + +logger = logging.getLogger("moon.manager.test.api." + __name__) + + +def clean_models(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, models = test_models.get_models() + for key in models["models"]: + from moon_manager.api import models + hug.test.delete(models, "/models/{}".format(key), headers=auth_headers) + + +def clean_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for key in policies["policies"]: + from moon_manager.api import policy + req = hug.test.delete(policy, "/policies/{}".format(key), headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def clean_subjects(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + subjects = test_perimeter.get_subjects() + logger.info("subjects {}".format(subjects)) + for key in subjects[1]["subjects"]: + subject = subjects[1]["subjects"][key] + policy_keys = subject["policy_list"] + logger.info("subjects policy_keys {}".format(policy_keys)) + for policy_key in policy_keys: + from moon_manager.api import perimeter + hug.test.delete(perimeter, "/policies/{}/subjects/{}".format(policy_key, key), headers=auth_headers ) + hug.test.delete(perimeter, "/subjects/{}".format(key), headers=auth_headers) + + +def clean_objects(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + objects = test_perimeter.get_objects() + logger.info("objects {}".format(objects)) + for key in objects[1]["objects"]: + object_ = objects[1]["objects"][key] + policy_keys = object_["policy_list"] + logger.info("objects policy_keys {}".format(policy_keys)) + for policy_key in policy_keys: + from moon_manager.api import perimeter + hug.test.delete(perimeter, "/policies/{}/objects/{}".format(policy_key, key), headers=auth_headers ) + hug.test.delete(perimeter, "/objects/{}".format(key), headers=auth_headers) + +def clean_actions(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + actions = test_perimeter.get_actions() + logger.info("actions {}".format(actions)) + for key in actions[1]["actions"]: + action = actions[1]["actions"][key] + policy_keys = action["policy_list"] + logger.info("action policy_keys {}".format(policy_keys)) + from moon_manager.api import perimeter + for policy_key in policy_keys: + hug.test.delete(perimeter, "/policies/{}/actions/{}".format(policy_key, key), headers=auth_headers) + hug.test.delete(perimeter, "/actions/{}".format(key), headers=auth_headers) + + + +def clean_subject_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_subject_categories() + logger.info(categories) + for key in categories["subject_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/subject_categories/{}".format(key), headers=auth_headers) + + +def clean_object_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_object_categories() + logger.info(categories) + for key in categories["object_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/object_categories/{}".format(key), headers=auth_headers) + + +def clean_action_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_action_categories() + logger.info(categories) + for key in categories["action_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/action_categories/{}".format(key), headers=auth_headers) + + +def clean_subject_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + logger.info("clean_subject_data on {}".format(policies)) + for policy_key in policies["policies"]: + req, data = test_data.get_subject_data(policy_id=policy_key) + logger.info("============= data {}".format(data)) + for data_item in data["subject_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= Deleting {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/subject_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_object_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, data = test_data.get_object_data(policy_id=policy_key) + for data_item in data["object_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= object_data {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/object_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_action_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, data = test_data.get_action_data(policy_id=policy_key) + for data_item in data["action_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= action_data {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/action_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, meta_rules_obj = test_meta_rules.get_meta_rules() + meta_rules_obj = meta_rules_obj["meta_rules"] + for meta_rule_key in meta_rules_obj: + logger.info("clean_meta_rule.meta_rule_key={}".format(meta_rule_key)) + logger.info("clean_meta_rule.meta_rule={}".format(meta_rules_obj[meta_rule_key])) + from moon_manager.api import meta_rules + hug.test.delete(meta_rules, "/meta_rules/{}".format(meta_rule_key), headers=auth_headers) + + +def clean_subject_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_subject_assignment(policy_key) + for key in assignments["subject_assignments"]: + subject_key = assignments["subject_assignments"][key]["subject_id"] + cat_key = assignments["subject_assignments"][key]["category_id"] + data_keys = assignments["subject_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, + subject_key, cat_key, data_key), headers=auth_headers) + + +def clean_object_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_object_assignment(policy_key) + for key in assignments["object_assignments"]: + object_key = assignments["object_assignments"][key]["object_id"] + cat_key = assignments["object_assignments"][key]["category_id"] + data_keys = assignments["object_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/object_assignments/{}/{}/{}".format(policy_key, + object_key, cat_key, data_key), headers=auth_headers) + + +def clean_action_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_action_assignment(policy_key) + for key in assignments["action_assignments"]: + action_key = assignments["action_assignments"][key]["action_id"] + cat_key = assignments["action_assignments"][key]["category_id"] + data_keys = assignments["action_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/action_assignments/{}/{}/{}".format(policy_key, + action_key, cat_key, data_key), headers=auth_headers) + + +def clean_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, rules = test_rules.get_rules(policy_key) + rules = rules["rules"]["rules"] + for rule_key in rules: + from moon_manager.api import rules + hug.test.delete(rules, "/policies/{}/rules/{}".format(policy_key, rule_key["id"]), headers=auth_headers) + + +def clean_all(): + clean_rules() + + clean_subject_assignments() + clean_object_assignments() + clean_action_assignments() + + clean_subject_data() + clean_object_data() + clean_action_data() + + clean_actions() + clean_objects() + clean_subjects() + + clean_policies() + clean_models() + clean_meta_rule() + + clean_subject_categories() + clean_object_categories() + clean_action_categories() diff --git a/moon_manager/tests/unit_python/helpers/meta_rule_helper.py b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py index e882706b..0542d394 100644 --- a/moon_manager/tests/unit_python/helpers/meta_rule_helper.py +++ b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py @@ -1,18 +1,25 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + 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 + from moon_manager.db_driver 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) + 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", @@ -20,30 +27,58 @@ def set_meta_rule(meta_rule_id, value=None): "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) + return ModelManager.set_meta_rule(moon_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 + from moon_manager.db_driver 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) + 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, + "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) + return ModelManager.add_meta_rule(moon_user_id=None, meta_rule_id=meta_rule_id, value=value) + + +def get_body_meta_rule_with_empty_category_in_mid(type=None): + action_category_id1 = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id1 = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id1 = builder.create_object_category("object_category_id1" + uuid4().hex) + + action_category_id2 = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id2 = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id2 = builder.create_object_category("object_category_id1" + uuid4().hex) + value = { + "name": "MLS_meta_rule" + uuid4().hex, + "description": "test", + "subject_categories": [subject_category_id1], + "object_categories": [object_category_id1], + "action_categories": [action_category_id1] + } + if type == 'subject': + value['subject_categories'].append("") + if type == 'object': + value['object_categories'].append("") + if type == 'action': + value['action_categories'].append("") + + value['subject_categories'].append(subject_category_id2) + value['object_categories'].append(object_category_id2) + value['action_categories'].append(action_category_id2) + return 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) + from moon_manager.db_driver import ModelManager + return ModelManager.get_meta_rules(moon_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) + from moon_manager.db_driver import ModelManager + ModelManager.delete_meta_rule(moon_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 index 73808e03..ed705af8 100644 --- a/moon_manager/tests/unit_python/helpers/model_helper.py +++ b/moon_manager/tests/unit_python/helpers/model_helper.py @@ -1,19 +1,26 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + 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) + from moon_manager.db_driver import ModelManager + return ModelManager.get_models(moon_user_id=None, model_id=model_id) def add_model(model_id=None, value=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager if not value: subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id @@ -22,27 +29,53 @@ def add_model(model_id=None, value=None): "description": "test", "meta_rules": [meta_rule_id] } - return ModelManager.add_model(user_id=None, model_id=model_id, value=value) + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + + +def add_model_without_meta_rule(model_id=None, value=None): + from moon_manager.db_driver import ModelManager + if not value: + name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id + value = { + "name": name, + "description": "test", + "meta_rules": "" + } + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + + +def add_model_with_blank_subject_meta_rule(model_id=None, value=None): + from moon_manager.db_driver import ModelManager + if not value: + subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(empty='subject') + name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id + value = { + "name": name, + "description": "test", + "meta_rules": [meta_rule_id] + } + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + def delete_models(uuid=None, name=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver 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) + ModelManager.delete_model(moon_user_id=None, model_id=uuid) def delete_all_models(): - from python_moondb.core import ModelManager + from moon_manager.db_driver 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) + ModelManager.delete_model(moon_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) + from moon_manager.db_driver import ModelManager + return ModelManager.update_model(moon_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 index 3d169b06..e970961a 100644 --- a/moon_manager/tests/unit_python/helpers/pdp_helper.py +++ b/moon_manager/tests/unit_python/helpers/pdp_helper.py @@ -1,23 +1,31 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + def update_pdp(pdp_id, value): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager return PDPManager.update_pdp("", pdp_id, value) def delete_pdp(pdp_id): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager PDPManager.delete_pdp("", pdp_id) def add_pdp(pdp_id=None, value=None): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager return PDPManager.add_pdp("", pdp_id, value) def get_pdp(pdp_id=None): - from python_moondb.core import PDPManager + from moon_manager.db_driver 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 index eddd0b8d..ffd0d1bb 100644 --- a/moon_manager/tests/unit_python/helpers/policy_helper.py +++ b/moon_manager/tests/unit_python/helpers/policy_helper.py @@ -1,17 +1,25 @@ -# 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'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + from uuid import uuid4 +from helpers import model_helper def get_policies(): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_policies("admin") def add_policies(policy_id=None, value=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager if not value: value = { "name": "test_policy"+ uuid4().hex, @@ -19,11 +27,24 @@ def add_policies(policy_id=None, value=None): "genre": "authz", "description": "test", } - return PolicyManager.add_policy("admin", policy_id=policy_id, value=value) + return PolicyManager.add_policy(moon_user_id="admin", policy_id=policy_id, value=value) + + +def add_policies_with_model(policy_id=None, value=None): + from moon_manager.db_driver import PolicyManager + req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(req.keys())[0] + data = { + "name": "test_policy"+ uuid4().hex, + "description": "test", + "model_id": model_id, + "genre": "genre" + } + return PolicyManager.add_policy(moon_user_id="admin", policy_id=policy_id, value=data) def delete_policies(uuid=None, name=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager if not uuid: for policy_id, policy_value in get_policies(): if name == policy_value['name']: @@ -33,31 +54,31 @@ def delete_policies(uuid=None, name=None): def update_policy(policy_id, value): - from python_moondb.core import PolicyManager + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver 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 + from moon_manager.db_driver import PolicyManager if not value: value = { "rule": ("high", "medium", "vm-action"), - "instructions": ({"decision": "grant"}), + "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 + from moon_manager.db_driver import PolicyManager PolicyManager.delete_rule("", policy_id, rule_id) diff --git a/moon_manager/tests/unit_python/helpers/rules_helper.py b/moon_manager/tests/unit_python/helpers/rules_helper.py new file mode 100644 index 00000000..ce7e8bd2 --- /dev/null +++ b/moon_manager/tests/unit_python/helpers/rules_helper.py @@ -0,0 +1,18 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +def get_headers(): + from moon_utilities.auth_functions import get_api_key_for_user + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin"), + 'Content-Type': 'application/json'} + return auth_headers diff --git a/moon_manager/tests/unit_python/mock_engine.py b/moon_manager/tests/unit_python/mock_engine.py new file mode 100644 index 00000000..0685d376 --- /dev/null +++ b/moon_manager/tests/unit_python/mock_engine.py @@ -0,0 +1,19 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def register_engine(m): + for port in range(20000, 20010): + m.register_uri( + 'POST', 'http://127.0.0.1:{}/update'.format(port), + json={} + ) diff --git a/moon_manager/tests/unit_python/mock_keystone.py b/moon_manager/tests/unit_python/mock_keystone.py new file mode 100644 index 00000000..73e5681d --- /dev/null +++ b/moon_manager/tests/unit_python/mock_keystone.py @@ -0,0 +1,59 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +import requests_mock + + +def register_keystone(m): + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'DELETE', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'GET', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users/', + json={"users": [{ + "id": "b34e5a29-5494-4cc5-9356-daa244b8c254" + }]} + ) + + def match_request_text(request): + # request.url may be None, or '' prevents a TypeError. + return 'http://keystone:5000/v3/users?name=' in request.url + + m.register_uri( + requests_mock.ANY, '/v3/users', + additional_matcher=match_request_text, + json={"users": [{ + "id": "b34e5a29-5494-4cc5-9356-daa244b8c254" + }]} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/projects/', + json={ + "description": "test_project", + "domain_id": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + ) diff --git a/moon_manager/tests/unit_python/mock_nova.py b/moon_manager/tests/unit_python/mock_nova.py new file mode 100644 index 00000000..e898ad1a --- /dev/null +++ b/moon_manager/tests/unit_python/mock_nova.py @@ -0,0 +1,28 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +import requests_mock + + +def register_nova(m): + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'DELETE', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'GET', 'http://keystone:5000/compute/v2.1/servers', + json={"servers": [{"name": "vm1"}]} + ) + diff --git a/moon_manager/tests/unit_python/mock_slaves.py b/moon_manager/tests/unit_python/mock_slaves.py new file mode 100644 index 00000000..935bb0de --- /dev/null +++ b/moon_manager/tests/unit_python/mock_slaves.py @@ -0,0 +1,38 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +SLAVES = { + "slaves": { + "d464cc58a0cd46dea3191ba70f4e7df8": { + "name": "slave_test", + "address": "", + "description": "...", + "api_key": "e58a882a6b658a22660f00a0c273e7f6b4c4eb5abe54eccba2cae307905d67e3746537bd790c41887e11840c2d186b6d6eeec0e426bcfa7a872cc3417a35124a", + "log": "/tmp/moon_d464cc58a0cd46dea3191ba70f4e7df8.log", + "process": "/tmp/d464cc58a0cd46dea3191ba70f4e7df8.pid", + "extra": { + "description": "...", + "starttime": 1543851265.76279, + "port": 10001, + "server_ip": "127.0.0.1", + "status": "down" + } + } + } +} + + +def register_slaves(m): + m.register_uri( + 'GET', 'http://localhost/slaves', + json=SLAVES + ) diff --git a/moon_manager/tests/unit_python/plugins/__init__.py b/moon_manager/tests/unit_python/plugins/__init__.py new file mode 100644 index 00000000..1856aa2c --- /dev/null +++ b/moon_manager/tests/unit_python/plugins/__init__.py @@ -0,0 +1,12 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + diff --git a/moon_manager/tests/unit_python/plugins/test_global_attrs.py b/moon_manager/tests/unit_python/plugins/test_global_attrs.py new file mode 100644 index 00000000..603e03ae --- /dev/null +++ b/moon_manager/tests/unit_python/plugins/test_global_attrs.py @@ -0,0 +1,148 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +from moon_manager.pip_driver import AttrsManager +from moon_manager.api.configuration import get_configuration + + +def test_mode_add_get(): + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + value = AttrsManager.get_object(object_type="mode") + assert value["value"] == default_value + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + + +def test_mode_add_gets(): + default_value = \ + get_configuration("information")["global_attrs"]["attributes"]["mode"]["default"] + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + values = AttrsManager.get_objects() + assert "mode" in values + assert values["mode"]["value"] == default_value + assert isinstance(values["mode"], dict) + for key in ("id", "value", "default", "values"): + assert key in values["mode"] + assert values["mode"]["value"] == default_value + + +def test_mode_update(): + value = AttrsManager.update_object(object_id="build", object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + + +def test_mode_delete(): + value = AttrsManager.update_object(object_id="build", object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "run" + + +def test_hug_mode_add_get(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + + req = hug.test.delete(attributes, "/attributes/{}".format("mode"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + + +def test_hug_mode_update(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.put(attributes, "/attributes/{}/{}".format("mode", "build"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + + +def test_hug_mode_delete(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + + req = hug.test.put(attributes, "/attributes/{}/{}".format("mode", "build"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + req = hug.test.delete(attributes, "/attributes/{}".format("mode"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value diff --git a/moon_manager/tests/unit_python/requirements.txt b/moon_manager/tests/unit_python/requirements.txt index d6f190e4..e021a5fb 100644 --- a/moon_manager/tests/unit_python/requirements.txt +++ b/moon_manager/tests/unit_python/requirements.txt @@ -1,5 +1,11 @@ -flask -flask_cors -flask_restful -python_moondb==1.2.20 -python_moonutilities==1.4.20 +hug!=2.5.0 +moon_utilities +sqlalchemy +pymysql +pytest-mock +pytest-cov +requests_mock +tinydb +pytest +pytest-benchmark +pyaml |