Clean the code and fix some bugs 33/49933/1
authorThomas Duval <thomas.duval@orange.com>
Wed, 3 Jan 2018 13:13:11 +0000 (14:13 +0100)
committerThomas Duval <thomas.duval@orange.com>
Wed, 3 Jan 2018 13:13:11 +0000 (14:13 +0100)
Change-Id: I3516d001cb0792ca6b01a40b9d9d13efc3ba30f9

moon_authz/moon_authz/__init__.py
moon_authz/moon_authz/__main__.py
moon_authz/moon_authz/api/authorization.py
moon_authz/moon_authz/http_server.py
moon_authz/moon_authz/server.py
moon_authz/setup.py
moon_authz/tests/unit_python/mock_pods.py
moon_authz/tests/unit_python/test_authz.py

index 903c651..6f964a6 100644 (file)
@@ -3,4 +3,4 @@
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
 
-__version__ = "0.1.0"
+__version__ = "4.3.2"
index 699c008..2693f68 100644 (file)
@@ -1,4 +1,4 @@
-from moon_authz.server import main
+from moon_authz.server import create_server
 
-server = main()
+server = create_server()
 server.run()
index d7832ef..c83dd72 100644 (file)
@@ -3,30 +3,21 @@
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
 
-import binascii
 import itertools
 import pickle
-from uuid import uuid4
 import logging
-from python_moonutilities import exceptions
 import flask
 from flask import request
 from flask_restful import Resource
 
-# TODO (asteroide):
-# - end the dev of the context
-# - rebuild the authorization function according to the context
-# - call the next security function
-# - call the master if an element is absent
-
-LOG = logging.getLogger("moon.authz.api." + __name__)
+logger = logging.getLogger("moon.authz.api." + __name__)
 
 
 class Authz(Resource):
     """
     Endpoint for authz requests
     """
-    __version__ = "0.1.0"
+    __version__ = "4.3.1"
 
     __urls__ = (
         "/authz",
@@ -82,7 +73,7 @@ class Authz(Resource):
         return response
 
     def run(self):
-        LOG.info("self.context.pdp_set={}".format(self.context.pdp_set))
+        logger.info("self.context.pdp_set={}".format(self.context.pdp_set))
         result, message = self.__check_rules()
         if result:
             return self.__exec_instructions(result)
@@ -108,10 +99,10 @@ class Authz(Resource):
         for item in itertools.product(*scopes_list):
             req = list(item)
             for rule in self.cache.rules[self.context.current_policy_id]["rules"]:
-                LOG.info("rule={}".format(rule))
+                logger.info("rule={}".format(rule))
                 if req == rule['rule']:
                     return rule['instructions'], ""
-        LOG.warning("No rule match the request...")
+        logger.warning("No rule match the request...")
         return False, "No rule match the request..."
 
     def __update_subject_category_in_policy(self, operation, target):
@@ -119,7 +110,7 @@ class Authz(Resource):
         try:
             policy_name, category_name, data_name = target.split(":")
         except ValueError:
-            LOG.error("Cannot understand value in instruction ({})".format(target))
+            logger.error("Cannot understand value in instruction ({})".format(target))
             return False
         # pdp_set = self.payload["authz_context"]['pdp_set']
         for meta_rule_id in self.context.pdp_set:
@@ -131,7 +122,7 @@ class Authz(Resource):
                         subject_category_id = category_id
                         break
                 else:
-                    LOG.error("Cannot understand category in instruction ({})".format(target))
+                    logger.error("Cannot understand category in instruction ({})".format(target))
                     return False
                 subject_data_id = None
                 for data in PolicyManager.get_subject_data("admin", policy_id, category_id=subject_category_id):
@@ -142,7 +133,7 @@ class Authz(Resource):
                     if subject_data_id:
                         break
                 else:
-                    LOG.error("Cannot understand data in instruction ({})".format(target))
+                    logger.error("Cannot understand data in instruction ({})".format(target))
                     return False
                 if operation == "add":
                     self.payload["authz_context"]['pdp_set'][meta_rule_id]['target'][subject_category_id].append(
@@ -152,7 +143,7 @@ class Authz(Resource):
                         self.payload["authz_context"]['pdp_set'][meta_rule_id]['target'][subject_category_id].remove(
                             subject_data_id)
                     except ValueError:
-                        LOG.warning("Cannot remove role {} from target".format(data_name))
+                        logger.warning("Cannot remove role {} from target".format(data_name))
                 result = True
                 break
         return result
@@ -234,7 +225,7 @@ class Authz(Resource):
                 if key == "decision":
                     if instruction["decision"] == "grant":
                         self.context.current_state = "grant"
-                        LOG.info("__exec_instructions True {}".format(
+                        logger.info("__exec_instructions True {}".format(
                             self.context.current_state))
                         return True
                     else:
@@ -251,7 +242,7 @@ class Authz(Resource):
                         self.context.current_state = "deny"
                     else:
                         self.context.current_state = "passed"
-        LOG.info("__exec_instructions False {}".format(self.context.current_state))
+        logger.info("__exec_instructions False {}".format(self.context.current_state))
 
     # def __update_current_request(self):
     #     index = self.payload["authz_context"]["index"]
@@ -360,15 +351,15 @@ class Authz(Resource):
                     "args": self.payload}
         except Exception as e:
             try:
-                LOG.error(self.payload["authz_context"])
+                logger.error(self.payload["authz_context"])
             except KeyError:
-                LOG.error("Cannot find \"authz_context\" in context")
-            LOG.error(e, exc_info=True)
+                logger.error("Cannot find \"authz_context\" in context")
+            logger.error(e, exc_info=True)
             return {"authz": False,
                     "error": str(e),
                     "pdp_id": self.pdp_id,
                     "args": self.payload}
 
     def head(self, uuid=None, subject_name=None, object_name=None, action_name=None):
-        LOG.info("HEAD request")
+        logger.info("HEAD request")
         return "", 200
\ No newline at end of file
index d24a02c..836efbc 100644 (file)
@@ -3,9 +3,8 @@
 # license which can be found in the file 'LICENSE' in this package distribution
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
 
-from flask import Flask, request
-# from flask_cors import CORS, cross_origin
-from flask_restful import Resource, Api, reqparse
+from flask import Flask
+from flask_restful import Resource, Api
 import logging
 from moon_authz import __version__
 from moon_authz.api.authorization import Authz
@@ -61,6 +60,7 @@ class Server:
     def run(self):
         raise NotImplementedError()
 
+
 __API__ = (
     Authz,
  )
@@ -74,7 +74,8 @@ class Root(Resource):
     __methods = ("get", "post", "put", "delete", "options")
 
     def get(self):
-        tree = {"/": {"methods": ("get",), "description": "List all methods for that service."}}
+        tree = {"/": {"methods": ("get",),
+                      "description": "List all methods for that service."}}
         for item in __API__:
             tree[item.__name__] = {"urls": item.__urls__}
             _methods = []
@@ -101,8 +102,6 @@ class HTTPServer(Server):
         self.app = Flask(__name__)
         self._port = port
         self._host = host
-        # Todo : specify only few urls instead of *
-        # CORS(self.app)
         self.component_id = kwargs.get("component_id")
         self.keystone_project_id = kwargs.get("keystone_project_id")
         self.container_chaining = kwargs.get("container_chaining")
index 1919ebe..8715bd8 100644 (file)
@@ -4,15 +4,14 @@
 # or at 'http://www.apache.org/licenses/LICENSE-2.0'.
 
 import os
-from oslo_log import log as logging
+import logging
 from moon_authz.http_server import HTTPServer as Server
 from python_moonutilities import configuration
 
-LOG = logging.getLogger("moon.authz.server")
-DOMAIN = "moon_authz"
+logger = logging.getLogger("moon.authz.server")
 
 
-def main():
+def create_server():
     configuration.init_logging()
 
     component_id = os.getenv("UUID")
@@ -21,14 +20,16 @@ def main():
     pdp_id = os.getenv("PDP_ID")
     meta_rule_id = os.getenv("META_RULE_ID")
     keystone_project_id = os.getenv("KEYSTONE_PROJECT_ID")
-    LOG.info("component_type={}".format(component_type))
+    logger.info("component_type={}".format(component_type))
     conf = configuration.get_configuration("plugins/{}".format(component_type))
     conf["plugins/{}".format(component_type)]['id'] = component_id
-    hostname = conf["plugins/{}".format(component_type)].get('hostname', component_id)
+    hostname = conf["plugins/{}".format(component_type)].get('hostname',
+                                                             component_id)
     port = conf["plugins/{}".format(component_type)].get('port', tcp_port)
     bind = conf["plugins/{}".format(component_type)].get('bind', "0.0.0.0")
 
-    LOG.info("Starting server with IP {} on port {} bind to {}".format(hostname, port, bind))
+    logger.info("Starting server with IP {} on port {} bind to {}".format(
+        hostname, port, bind))
     server = Server(
         host=bind,
         port=int(port),
@@ -43,5 +44,10 @@ def main():
     return server
 
 
+def run():
+    server = create_server()
+    server.run()
+
+
 if __name__ == '__main__':
-    main()
+    run()
index c3ac33c..ad99b9f 100644 (file)
@@ -40,7 +40,7 @@ setup(
 
     entry_points={
         'console_scripts': [
-            'moon_authz = moon_authz.server:main',
+            'moon_authz = moon_authz.server:run',
         ],
     }
 
index 7488f4f..74801cd 100644 (file)
@@ -10,15 +10,15 @@ pdp_mock = {
         "keystone_project_id": "a64beb1cc224474fb4badd43173e7101"
     },
     "pdp_id1": {
-        "name": "...",
+        "name": "pdp_id1",
         "security_pipeline": ["policy_id_1", "policy_id_2"],
         "keystone_project_id": "keystone_project_id1",
         "description": "...",
     },
     "pdp_id12": {
-        "name": "...",
+        "name": "pdp_id2",
         "security_pipeline": ["policy_id_1", "policy_id_2"],
-        "keystone_project_id": "keystone_project_id1",
+        "keystone_project_id": "keystone_project_id2",
         "description": "...",
     }
 }
@@ -100,7 +100,7 @@ subject_mock = {
     "policy_id_2": {
         "subject_id": {
             "name": "subject_name",
-            "keystone_id": "keystone_project_id1",
+            "keystone_id": "keystone_project_id2",
             "description": "a description"
         }
     }
index f98abeb..50493c9 100644 (file)
@@ -12,9 +12,9 @@ def get_json(data):
 
 def test_authz_true(context):
     import moon_authz.server
-    from python_moonutilities.security_functions import Context
+    from python_moonutilities.context import Context
     from python_moonutilities.cache import Cache
-    server = moon_authz.server.main()
+    server = moon_authz.server.create_server()
     client = server.app.test_client()
     CACHE = Cache()
     CACHE.update()
@@ -33,9 +33,9 @@ def test_authz_true(context):
 
 def test_user_not_allowed(context):
     import moon_authz.server
-    from python_moonutilities.security_functions import Context
+    from python_moonutilities.context import Context
     from python_moonutilities.cache import Cache
-    server = moon_authz.server.main()
+    server = moon_authz.server.create_server()
     client = server.app.test_client()
     CACHE = Cache()
     CACHE.update()