Пример #1
0
 def __init__(self):
     super(Start, self).__init__()
     self.app = current_app
     self.service_registry_handler = ServiceRegistryHandler()
     self.request_timeout = current_app.config["TIMEOUT"]
     self.helper = Helpers(current_app.config)
     self.store_session = self.helper.store_session
Пример #2
0
 def __init__(self):
     super(Start, self).__init__()
     self.app = current_app
     self.service_registry_handler = ServiceRegistryHandler(current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"], current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
     self.request_timeout = current_app.config["TIMEOUT"]
     self.helper = Helpers(current_app.config)
     self.store_session = self.helper.store_session
Пример #3
0
 def __init__(self):
     super(ConsentFormHandler, self).__init__()
     self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
     self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
     self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
     self.timeout = current_app.config["TIMEOUT"]
     self.debug_mode = current_app.config["DEBUG_MODE"]
     try:
         self.AM = AccountManagerHandler(self.am_url, self.am_user, self.am_password, self.timeout)
     except Exception as e:
         debug_log.warn("Initialization of AccountManager failed. We will crash later but note it here.\n{}".format(repr(e)))
     self.SH = ServiceRegistryHandler(current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"], current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
     self.getService = self.SH.getService
     self.Helpers = Helpers(current_app.config)
     self.operator_url = current_app.config["OPERATOR_URL"]
Пример #4
0
    def gen_auth_token(self, auth_token_info):
        gen3 = {"generate": "RSA", "size": self.keysize, "kid": "Something went wrong, check helpers.py key generation"}
        operator_key = jwk.JWK(**gen3)
        try:
            with open(self.cert_key_path, "r") as cert_file:
                operator_key2 = jwk.JWK(**loads(load(cert_file)))
                operator_key = operator_key2
        except Exception as e:
            print(e)
            with open(self.cert_key_path, "w+") as cert_file:
                dump(operator_key.export(), cert_file, indent=2)
        slrt = SLR_tool()
        slrt.slr = auth_token_info
        debug_log.debug(dumps(slrt.get_SLR_payload(), indent=2))
        debug_log.debug(dumps(slrt.get_CR_payload(), indent=2))
        # JOSE header
        header = {"typ": "JWT",
                  "alg": "HS256"}
        # Claims
        srv_handler = ServiceRegistryHandler(self.service_registry_search_domain, self.service_registry_search_endpoint)
        payload = {"iss": self.operator_id,  # Operator ID,
                   "cnf": {"kid": slrt.get_source_cr_id()},
                   "aud": srv_handler.getService_url(slrt.get_source_service_id()),
                   "exp": int(time.time() + self.not_after_interval),
                   # datetime.fromtimestamp(time.time()+2592000).strftime("%Y-%m-%dT%H:%M:%S %Z"), # 30 days in seconds
                   # Experiation time of token on or after which token MUST NOT be accepted
                   "nbf": int(time.time()),
                   # datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S %Z"),  # The time before which token MUST NOT be accepted
                   "iat": int(time.time()),
                   # datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S %Z"),  # The time which the JWT was issued
                   "jti": str(guid()),  # JWT id claim provides a unique identifier for the JWT
                   "pi_id": slrt.get_source_cr_id(),  # Resource set id that was assigned in the linked Consent Record
                   }
        debug_log.debug(dumps(payload, indent=2))
        key = operator_key
        debug_log.debug(key.export())
        debug_log.debug(key.export_public())
        header = {"alg": "RS256"}

        token = jwt.JWT(header=header, claims=payload)
        token.make_signed_token(key)
        return token.serialize()
Пример #5
0
    def __init__(self):
        super(RegisterSur, self).__init__()
        self.app = current_app
        self.Helpers = Helpers(self.app.config)

        account_id = "ACC-ID-RANDOM"
        self.operator_key = self.Helpers.get_key()
        self.request_timeout = self.app.config["TIMEOUT"]

        self.payload = \
            {
                "version": "1.2",
                "link_id": "",
                "operator_id": account_id,
                "service_id": "",
                "surrogate_id": "",
                "operator_key": self.operator_key["pub"],
                "cr_keys": "",
                "iat": int(time.time()), # TODO: set to iat when Account version used supports it
            }
        debug_log.info(dumps(self.payload, indent=3))
        self.service_registry_handler = ServiceRegistryHandler(
            current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"],
            current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user,
                                            self.am_password, self.timeout)
        except Exception as e:
            debug_log.warn(
                "Initialization of AccountManager failed. We will crash later but note it here.\n{}"
                .format(repr(e)))

        self.query_db = self.Helpers.query_db
Пример #6
0
class ConsentFormHandler(Resource):
    def __init__(self):
        super(ConsentFormHandler, self).__init__()
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        self.debug_mode = current_app.config["DEBUG_MODE"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user, self.am_password, self.timeout)
        except Exception as e:
            debug_log.warn("Initialization of AccountManager failed. We will crash later but note it here.\n{}".format(repr(e)))
        self.SH = ServiceRegistryHandler(current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"], current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
        self.getService = self.SH.getService
        self.Helpers = Helpers(current_app.config)
        self.operator_url = current_app.config["OPERATOR_URL"]

    @error_handler
    def get(self, account_id):
        '''get
        :return: Returns Consent form to UI for user input.
        '''
        _consent_form = Consent_form_Out
        service_ids = request.args

        sq.task("Fetch services")
        sink = self.getService(service_ids["sink"])
        _consent_form["sink"]["service_id"] = sink["serviceId"]
        purposes = _consent_form["sink"]["dataset"][0]["purposes"] # TODO replace this once Service registry stops being stupid.
        _consent_form["sink"]["dataset"] = [] # Clear out template.
        for dataset in sink["serviceDescription"]["serviceDataDescription"][0]["dataset"]:
            item = {
                "dataset_id": dataset["datasetId"],
                "title": dataset["title"],
                "description": dataset["description"],
                "keyword": dataset["keyword"],
                "publisher": dataset["publisher"],
                "purposes": dataset["purpose"]
            }

            _consent_form["sink"]["dataset"].append(item)


        source = self.getService(service_ids["source"])
        _consent_form["source"]["service_id"] = source["serviceId"]
        _consent_form["source"]["dataset"] = [] # Clear out template.
        for dataset in source["serviceDescription"]["serviceDataDescription"][0]["dataset"]:
            item = {
                "dataset_id": dataset["datasetId"],
                "title": dataset["title"],
                "description": dataset["description"],
                "keyword": dataset["keyword"],
                "publisher": dataset["publisher"],
                "distribution": {
                    "distribution_id": dataset["distribution"][0]["distributionId"],
                    "access_url": "{}{}{}".format(source["serviceInstance"][0]["domain"],
                                                  source["serviceInstance"][0]["serviceAccessEndPoint"][
                                                      "serviceAccessURI"]
                                                  , dataset["distribution"][0]["accessURL"]),

                }
            }
            _consent_form["source"]["dataset"].append(item)


        sq.task("Generate RS_ID")

        source_domain = source["serviceInstance"][0]["domain"]
        source_access_uri = source["serviceInstance"][0]["serviceAccessEndPoint"]["serviceAccessURI"]
        rs_id = self.Helpers.gen_rs_id(source["serviceInstance"][0]["domain"])
        sq.task("Store RS_ID")
        _consent_form["source"]["rs_id"] = rs_id

        sq.reply_to("UI", msg="Consent Form+RS_ID")
        return _consent_form

    @error_handler
    def post(self, account_id):
        '''post
        :return: Returns 201 when consent has been created
        '''
        debug_log.info(dumps(request.json, indent=2))


        _consent_form = request.json
        sink_srv_id = _consent_form["sink"]["service_id"]
        source_srv_id = _consent_form["source"]["service_id"]

        sq.task("Validate RS_ID")
        if self.Helpers.validate_rs_id(_consent_form["source"]["rs_id"]):  # Validate RS_ID (RS_ID exists and not used before)
            self.Helpers.store_consent_form(_consent_form)  # Store Consent Form
        else:
            raise DetailedHTTPException(title="RS_ID Validation error.",
                                        detail="RS_ID could not be validated.",
                                        status=403)

        sq.send_to("Account Manager", "GET surrogate_id & slr_id")
        try:
            sink_sur = self.AM.getSUR_ID(sink_srv_id, account_id)
            source_sur = self.AM.getSUR_ID(source_srv_id, account_id)
        except AttributeError as e:
            raise DetailedHTTPException(status=502,
                                        title="It would seem initiating Account Manager Handler has failed.",
                                        detail="Account Manager might be down or unresponsive.",
                                        trace=traceback.format_exc(limit=100).splitlines())
        debug_log.info("sink_sur = {}".format(sink_sur))
        debug_log.info("source_sur = {}".format(source_sur))

        slr_id_sink, surrogate_id_sink = sink_sur["data"]["surrogate_id"]["attributes"]["servicelinkrecord_id"],\
                                         sink_sur["data"]["surrogate_id"]["attributes"]["surrogate_id"]  # Get slr and surrogate_id

        slr_id_source, surrogate_id_source = source_sur["data"]["surrogate_id"]["attributes"]["servicelinkrecord_id"],\
                                             source_sur["data"]["surrogate_id"]["attributes"]["surrogate_id"] # One for Sink, one for Source

        sink_keys = self.Helpers.get_service_keys(surrogate_id_sink)
        try:
            sink_key = loads(sink_keys[0])
        except IndexError as e:
            raise DetailedHTTPException(status=500,
                                        title="Fetching service keys for sink has failed.",
                                        detail="Couldn't find keys for surrogate id ({}).".format(surrogate_id_sink),
                                        trace=traceback.format_exc(limit=100).splitlines())
        debug_log.info("Sink keys:\n{}".format(dumps(sink_key, indent=2)))
        sink_pop_key = sink_key["pop_key"]
        # Generate common_cr for both sink and source.
        sq.task("Generate common CR")

        issued = int(time.time()) #datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
        not_before = int(time.time()) #datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") # TODO: This and not after are Optional, who says when to put them?
        not_after = int(time.time()+current_app.config["NOT_AFTER_INTERVAL"]) #datetime.fromtimestamp(time.time()+current_app.config["NOT_AFTER_INTERVAL"]).strftime("%Y-%m-%dT%H:%M:%SZ")
        operator_id = current_app.config["UID"]


        common_cr_source = self.Helpers.gen_cr_common(surrogate_id_source,
                                                      _consent_form["source"]["rs_id"],
                                                      slr_id_source,
                                                      issued,
                                                      not_before,
                                                      not_after,
                                                      source_srv_id,
                                                      operator_id,
                                                      "Source")

        common_cr_sink = self.Helpers.gen_cr_common(surrogate_id_sink,
                                                    _consent_form["source"]["rs_id"],
                                                    slr_id_sink,
                                                    issued,
                                                    not_before,
                                                    not_after,
                                                    sink_srv_id,
                                                    operator_id,
                                                    "Sink")

        sq.task("Generate ki_cr")
        ki_cr = self.Helpers.Gen_ki_cr(self)

        sq.task("Generate CR for sink")
        sink_cr = self.Helpers.gen_cr_sink(common_cr_sink, _consent_form, common_cr_source["cr_id"])

        sq.task("Generate CR for source")
        source_cr = self.Helpers.gen_cr_source(common_cr_source, _consent_form,
                                          sink_pop_key)

        sink_cr["cr"]["common_part"]["rs_description"] = source_cr["cr"]["common_part"]["rs_description"]

        debug_log.info(sink_cr)
        debug_log.info(source_cr)
        sq.task("Generate CSR's")
        sink_csr = self.Helpers.gen_csr(surrogate_id_sink, sink_cr["cr"]["common_part"]["cr_id"], "Active",
                                        "null")
        source_csr = self.Helpers.gen_csr(surrogate_id_source, source_cr["cr"]["common_part"]["cr_id"], "Active",
                                          "null")

        sq.send_to("Account Manager", "Send CR/CSR to sign and store")
        result = self.AM.signAndstore(sink_cr, sink_csr, source_cr, source_csr, account_id)

        # TODO: These are debugging and testing calls, remove them once operation is verified.
        if self.debug_mode:
            own_addr = self.operator_url #request.url_root.rstrip(request.script_root)
            debug_log.info("Our own address is: {}".format(own_addr))
            req = post(own_addr+"/api/1.2/cr/account_id/{}/service/{}/consent/{}/status/Disabled"
                          .format(surrogate_id_source, source_srv_id, common_cr_source["cr_id"]))

            debug_log.info("Changed csr status, request status ({}) reason ({}) and the following content:\n{}".format(
                req.status_code,
                req.reason,
                dumps(loads(req.content), indent=2)
            ))
            req = post(own_addr+"/api/1.2/cr/account_id/{}/service/{}/consent/{}/status/Active"
                          .format(surrogate_id_source, source_srv_id, common_cr_source["cr_id"]))
            debug_log.info("Changed csr status, request status ({}) reason ({}) and the following content:\n{}".format(
                req.status_code,
                req.reason,
                dumps(loads(req.content), indent=2)
            ))


        debug_log.info(dumps(result, indent=3))
        sink_cr = result["data"]["sink"]["consentRecord"]["attributes"]["cr"]
        sink_csr = result["data"]["sink"]["consentStatusRecord"]["attributes"]["csr"]

        source_cr = result["data"]["source"]["consentRecord"]["attributes"]["cr"]
        source_csr = result["data"]["source"]["consentStatusRecord"]["attributes"]["csr"]


        crs_csrs_payload = {"sink": {"cr": sink_cr, "csr": sink_csr},
                 "source": {"cr": source_cr, "csr": source_csr}}
        #logger.info("Going to Celery task")
        sq.send_to("Service_Components Mgmnt (Sink)", "Post CR-Sink, CSR-Sink")
        sq.send_to("Service_Components Mgmnt (Source)", "Post CR-Source, CSR-Source")

        debug_log.info(dumps(crs_csrs_payload, indent=2))
        CR_installer.delay(crs_csrs_payload, self.SH.getService_url(sink_srv_id), self.SH.getService_url(source_srv_id))
        return {"status": 201, "msg": "CREATED"}, 201
Пример #7
0
from DetailedHTTPException import DetailedHTTPException, error_handler
from Templates import ServiceRegistryHandler, Consent_form_Out, Sequences
from flask import request, Blueprint, current_app
from flask_restful import Resource, Api
from helpers import AccountManagerHandler, Helpers
from tasks import CR_installer

logger = logging.getLogger("sequence")
debug_log = logging.getLogger("debug")

api_CR_blueprint = Blueprint("api_CR_blueprint", __name__)
api = Api()
api.init_app(api_CR_blueprint)

SH = ServiceRegistryHandler()
getService = SH.getService

sq = Sequences("Operator_Components Mgmnt", {})
Operator_public_key = {}


class ConsentFormHandler(Resource):
    def __init__(self):
        super(ConsentFormHandler, self).__init__()
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user,
Пример #8
0
class Start(Resource):
    def __init__(self):
        super(Start, self).__init__()
        self.app = current_app
        self.service_registry_handler = ServiceRegistryHandler(current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"], current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
        self.request_timeout = current_app.config["TIMEOUT"]
        self.helper = Helpers(current_app.config)
        self.store_session = self.helper.store_session

    @error_handler
    def get(self, account_id, service_id):
        try:
            try:
                to_store = {}  # We want to store some information for later parts of flow.

                # This address needs to be fetched somewhere to support multiple services
                service_json = self.service_registry_handler.getService(service_id)
                service_domain = service_json["serviceInstance"][0]["domain"]
                service_access_uri = service_json["serviceInstance"][0]["serviceAccessEndPoint"]["serviceAccessURI"]
                service_login_uri = service_json["serviceInstance"][0]["loginUri"]
                # Endpoint address should be fetched somewhere as well so we can re-use the service address later easily.
                endpoint = "/slr/code"  # TODO: Comment above
                endpoint = "{}{}{}".format(service_domain, service_access_uri, endpoint)

                sq.send_to("Service_Components Mgmnt", "Fetch code from service_mgmnt")
                result = get(endpoint, timeout=self.request_timeout)
                code_status = result.status_code

                sq.task("Check code request is valid")
                debug_log.info(code_status)

                if code_status is 200:
                    sq.task("Load code object for use")
                    code = loads(result.text)
                    debug_log.info("Code contains: {}, account id {} and service_id {}".format(result.text, account_id, service_id))
                    to_store[code["code"]] = {"account_id": account_id, "service_id": service_id}
                    self.store_session(to_store)
                else:
                    raise DetailedHTTPException(status=code_status,
                                                detail={"msg": "Fetching code from Service_Components Mgmnt failed.",
                                                        "Errors From SrvMgmnt": loads(result.text)},
                                                title=result.reason)
            except Timeout:
                raise DetailedHTTPException(status=504,
                                            title="Request to Service_Components Mgmnt failed due to TimeoutError.",
                                            detail="Service_Components Mgmnt might be under heavy load, request for code got timeout.",
                                            trace=traceback.format_exc(limit=100).splitlines())
            except ConnectionError:
                raise DetailedHTTPException(status=503,
                                            title="Request to Service_Components Mgmnt failed due to ConnectionError.",
                                            detail="Service_Components Mgmnt might be down or unresponsive.",
                                            trace=traceback.format_exc(limit=100).splitlines())
            debug_log.info("We got code: {}".format(code))

            sq.task("Add user_id to code dictionary {'code': 'code', 'user_id': 'user_id'}")
            code["user_id"] = account_id

            try:
                endpoint = "/api/1.2/slr/login"
                endpoint = "{}{}{}".format(service_domain, service_access_uri, service_login_uri)
                sq.send_to("Service_Components Mgmnt", "Redirect user to Service_Components Mgmnt login")
                result = post(endpoint, json=code, timeout=self.request_timeout)
                debug_log.info("####Response to this end point: {}\n{}".format(result.status_code, result.text))
                if not result.ok:
                    raise DetailedHTTPException(status=result.status_code,
                                                detail={
                                                    "msg": "Something went wrong while Logging in with code to Service_Components Mgmnt",
                                                    "Error from Service_Components Mgmnt": loads(result.text)},
                                                title=result.reason)

            except Timeout:
                raise DetailedHTTPException(status=504,
                                            title="Request to Service_Components Mgmnt failed due to TimeoutError.",
                                            detail="Service_Components Mgmnt might be under heavy load, request for code got timeout.",
                                            trace=traceback.format_exc(limit=100).splitlines())
            except ConnectionError:
                raise DetailedHTTPException(status=504,
                                            title="Request to Service_Components Mgmnt failed due to ConnectionError.",
                                            detail="Service_Components Mgmnt might be down or unresponsive.",
                                            trace=traceback.format_exc(limit=100).splitlines())



######################## This step is actually pointless since its only to fetch list of slr so we are sure it got generated right.
            # try:
            #     sq.send_to("Service_Components Mgmnt","Fetch list of slr's from service to verify success, this is debug step.")
            #     endpoint = "/api/1.2/slr/slr"
            #     result = get("{}{}".format(service_mgmnt_address, endpoint), timeout=self.request_timeout)
            #     if not result.ok:
            #         raise DetailedHTTPException(status=result.status_code,
            #                                     detail={
            #                                         "msg": "Something went wrong while Fetching list of SLR from Service_Components Mgmnt",
            #                                         "Error from Service_Components Mgmnt": loads(result.text)},
            #                                     title=result.reason)
            # except Timeout:
            #     raise DetailedHTTPException(status=408,
            #                                 title="Request to Service_Components Mgmnt failed due to TimeoutError.",
            #                                 source="POST /login",
            #                                 detail="Service_Components Mgmnt might be under heavy load, request for code got timeout.")
            # except ConnectionError:
            #     raise DetailedHTTPException(status=504,
            #                                 title="Request to Service_Components Mgmnt failed due to ConnectionError.",
            #                                 source="POST /login",
            #                                 detail="Service_Components Mgmnt might be down or unresponsive.")
            #
            # return loads(result.text)
        except DetailedHTTPException as e:
            raise DetailedHTTPException(exception=e,
                                        title="SLR registration failed.",
                                        status=500,
                                        detail="Something failed during creation of SLR.",
                                        trace=traceback.format_exc(limit=100).splitlines())
        except Exception as e:
            raise DetailedHTTPException(status=500,
                                        title="Something went really wrong during SLR registration.",
                                        detail="Error: {}".format(repr(e)),
                                        exception=e,
                                        trace=traceback.format_exc(limit=100).splitlines())
Пример #9
0
class RegisterSur(Resource):
    def __init__(self):
        super(RegisterSur, self).__init__()
        self.app = current_app
        self.Helpers = Helpers(self.app.config)

        account_id = "ACC-ID-RANDOM"
        self.operator_key = self.Helpers.get_key()
        self.request_timeout = self.app.config["TIMEOUT"]

        self.payload = \
            {
                "version": "1.2",
                "link_id": "",
                "operator_id": account_id,
                "service_id": "",
                "surrogate_id": "",
                "operator_key": self.operator_key["pub"],
                "cr_keys": "",
                "iat": int(time.time()), # TODO: set to iat when Account version used supports it
            }
        debug_log.info(dumps(self.payload, indent=3))
        self.service_registry_handler = ServiceRegistryHandler(
            current_app.config["SERVICE_REGISTRY_SEARCH_DOMAIN"],
            current_app.config["SERVICE_REGISTRY_SEARCH_ENDPOINT"])
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user,
                                            self.am_password, self.timeout)
        except Exception as e:
            debug_log.warn(
                "Initialization of AccountManager failed. We will crash later but note it here.\n{}"
                .format(repr(e)))

        self.query_db = self.Helpers.query_db

    @error_handler
    def post(self):
        try:
            debug_log.info(dumps(request.json))
            sq.task("Load json payload as object")
            js = request.json

            sq.task("Load account_id and service_id from database")
            query = self.query_db("select * from session_store where code=%s;",
                                  (js["code"], ))
            debug_log.info(type(query))
            debug_log.info(query)
            dict_query = loads(query)
            debug_log.debug("{}  {}".format(type(query), query))
            account_id = dict_query["account_id"]
            self.payload["service_id"] = dict_query["service_id"]
            # Check Surrogate_ID exists.
            # Fill token_key
            try:
                sq.task("Verify surrogate_id and token_key exist")
                token_key = js["token_key"]
                self.payload["surrogate_id"] = js["surrogate_id"]
                #self.payload["token_key"] = {"key": token_key}

                sq.task("Store surrogate_id and keys for CR steps later on.")
                key_template = {
                    "token_key": token_key,
                    "pop_key": token_key
                }  # TODO: Get pop_key here?

                self.Helpers.store_service_key_json(
                    kid=token_key["kid"],
                    surrogate_id=js["surrogate_id"],
                    key_json=key_template)
            except Exception as e:
                debug_log.exception(e)
                raise DetailedHTTPException(
                    exception=e,
                    detail={
                        "msg":
                        "Received Invalid JSON that may not contain surrogate_id",
                        "json": js
                    })
            #sq.task("Fetch and fill token_issuer_keys")
            # TODO: Token keys separetely when the time is right.
            #self.payload["token_issuer_keys"][0] = self.Helpers.get_key()["pub"]

            # Create template
            self.payload["link_id"] = str(guid())
            # TODO: Currently you can generate endlessly new slr even if one exists already
            sq.task("Fill template for Account Manager")
            template = {
                "code": js["code"],
                "data": {
                    "slr": {
                        "type": "ServiceLinkRecord",
                        "attributes": self.payload,
                    },
                    "surrogate_id": {
                        "type": "SurrogateId",
                        "attributes": {
                            "surrogate_id": self.payload["surrogate_id"],
                            "service_id": self.payload["service_id"],
                            "account_id": account_id
                        }
                    }
                },
            }

            debug_log.info("###########Template for Account Manager#")
            debug_log.info(dumps(template, indent=3))
            debug_log.info("########################################")
            sq.send_to("Account Manager", "Sign SLR at Account Manager")
            try:
                reply = self.AM.sign_slr(template, account_id)
            except AttributeError as e:
                raise DetailedHTTPException(
                    status=502,
                    title=
                    "It would seem initiating Account Manager Handler has failed.",
                    detail="Account Manager might be down or unresponsive.",
                    trace=traceback.format_exc(limit=100).splitlines())
            debug_log.info(dumps(reply, indent=2))

            # Parse JSON form Account Manager to format Service_Mgmnt understands.
            try:
                req = {
                    "data": {
                        "code": js["code"],
                    },
                    "slr": reply["data"]["slr"]["attributes"]["slr"]
                }

                debug_log.info("SLR O: {}".format(dumps(req, indent=3)))
            except Exception as e:
                raise DetailedHTTPException(
                    exception=e,
                    detail=
                    "Parsing JSON form Account Manager to format Service_Mgmnt understands has failed.",
                    trace=traceback.format_exc(limit=100).splitlines())

            try:
                sq.send_to(
                    "Service_Components Mgmnt",
                    "Send created and signed SLR to Service_Components Mgnt")
                endpoint = "/api/1.2/slr/slr"
                service_url = self.service_registry_handler.getService_url(
                    self.payload["service_id"].encode())
                debug_log.info("Service_ulr = {}, type: {}".format(
                    service_url, type(service_url)))
                response = post("{}{}".format(service_url, endpoint),
                                json=req,
                                timeout=self.request_timeout)
                debug_log.info("Request sent.")
                if not response.ok:
                    raise DetailedHTTPException(
                        status=response.status_code,
                        detail={
                            "Error from Service_Components Mgmnt":
                            loads(response.text)
                        },
                        title=response.reason)
            except DetailedHTTPException as e:
                raise e
            except Exception as e:
                raise DetailedHTTPException(
                    exception=e,
                    detail="Sending SLR to service has failed",
                    trace=traceback.format_exc(limit=100).splitlines())

        except DetailedHTTPException as e:
            raise e
        except Exception as e:
            raise DetailedHTTPException(
                title="Creation of SLR has failed.",
                exception=e,
                trace=traceback.format_exc(limit=100).splitlines())
Пример #10
0
    def __init__(self):
        super(RegisterSur, self).__init__()
        self.app = current_app
        #print(current_app.config)
        keysize = current_app.config["KEYSIZE"]
        cert_key_path = current_app.config["CERT_KEY_PATH"]
        self.request_timeout = current_app.config["TIMEOUT"]

        SUPER_DEBUG = True

        account_id = "ACC-ID-RANDOM"
        user_account_id = account_id + "_" + str(guid())

        # Keys need to come from somewhere else instead of being generated each time.
        gen = {"generate": "EC", "cvr": "P-256", "kid": user_account_id}
        gen3 = {"generate": "RSA", "size": keysize, "kid": account_id}
        operator_key = jwk.JWK(**gen3)
        try:
            with open(cert_key_path, "r") as cert_file:
                operator_key2 = jwk.JWK(**loads(load(cert_file)))
                operator_key = operator_key2
        except Exception as e:
            print(e)
            with open(cert_key_path, "w+") as cert_file:
                dump(operator_key.export(), cert_file, indent=2)

        # Template to send the key to key server
        template = {
            account_id: {
                "cr_keys": loads(operator_key.export_public()),
                "token_keys": loads(operator_key.export_public())
            }
        }
        # post("http://localhost:6666/key", json=template)

        self.payload = \
            {
                "version": "1.2",
                "link_id": "",
                "operator_id": account_id,
                "service_id": "SRV-SH14W4S3",  # How do we know this?
                "surrogate_id": "",
                "token_key": "",
                "operator_key": loads(operator_key.export_public()),
                "cr_keys": "",
                "created": ""  # time.time(),
            }
        debug_log.info(dumps(self.payload, indent=3))

        protti = {"alg": "RS256"}
        headeri = {
            "kid": user_account_id,
            "jwk": loads(operator_key.export_public())
        }
        self.service_registry_handler = ServiceRegistryHandler()
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user,
                                            self.am_password, self.timeout)
        except Exception as e:
            debug_log.warn(
                "Initialization of AccountManager failed. We will crash later but note it here.\n{}"
                .format(repr(e)))

        self.Helpers = Helpers(current_app.config)
        self.query_db = self.Helpers.query_db
Пример #11
0
class RegisterSur(Resource):
    def __init__(self):
        super(RegisterSur, self).__init__()
        self.app = current_app
        #print(current_app.config)
        keysize = current_app.config["KEYSIZE"]
        cert_key_path = current_app.config["CERT_KEY_PATH"]
        self.request_timeout = current_app.config["TIMEOUT"]

        SUPER_DEBUG = True

        account_id = "ACC-ID-RANDOM"
        user_account_id = account_id + "_" + str(guid())

        # Keys need to come from somewhere else instead of being generated each time.
        gen = {"generate": "EC", "cvr": "P-256", "kid": user_account_id}
        gen3 = {"generate": "RSA", "size": keysize, "kid": account_id}
        operator_key = jwk.JWK(**gen3)
        try:
            with open(cert_key_path, "r") as cert_file:
                operator_key2 = jwk.JWK(**loads(load(cert_file)))
                operator_key = operator_key2
        except Exception as e:
            print(e)
            with open(cert_key_path, "w+") as cert_file:
                dump(operator_key.export(), cert_file, indent=2)

        # Template to send the key to key server
        template = {
            account_id: {
                "cr_keys": loads(operator_key.export_public()),
                "token_keys": loads(operator_key.export_public())
            }
        }
        # post("http://localhost:6666/key", json=template)

        self.payload = \
            {
                "version": "1.2",
                "link_id": "",
                "operator_id": account_id,
                "service_id": "SRV-SH14W4S3",  # How do we know this?
                "surrogate_id": "",
                "token_key": "",
                "operator_key": loads(operator_key.export_public()),
                "cr_keys": "",
                "created": ""  # time.time(),
            }
        debug_log.info(dumps(self.payload, indent=3))

        protti = {"alg": "RS256"}
        headeri = {
            "kid": user_account_id,
            "jwk": loads(operator_key.export_public())
        }
        self.service_registry_handler = ServiceRegistryHandler()
        self.am_url = current_app.config["ACCOUNT_MANAGEMENT_URL"]
        self.am_user = current_app.config["ACCOUNT_MANAGEMENT_USER"]
        self.am_password = current_app.config["ACCOUNT_MANAGEMENT_PASSWORD"]
        self.timeout = current_app.config["TIMEOUT"]
        try:
            self.AM = AccountManagerHandler(self.am_url, self.am_user,
                                            self.am_password, self.timeout)
        except Exception as e:
            debug_log.warn(
                "Initialization of AccountManager failed. We will crash later but note it here.\n{}"
                .format(repr(e)))

        self.Helpers = Helpers(current_app.config)
        self.query_db = self.Helpers.query_db

    @error_handler
    def post(self):
        try:
            debug_log.info(dumps(request.json))
            sq.task("Load json payload as object")
            js = request.json

            sq.task("Load account_id and service_id from database")
            for code_json in self.query_db(
                    "select * from session_store where code = ?;",
                [js["code"]]):
                debug_log.debug("{}  {}".format(type(code_json), code_json))
                account_id = loads(code_json["json"])["account_id"]
                self.payload["service_id"] = loads(
                    code_json["json"])["service_id"]
            # Check Surrogate_ID exists.
            # Fill token_key
            try:
                sq.task("Verify surrogate_id and token_key exist")
                self.payload["surrogate_id"] = js["surrogate_id"]
                self.payload["token_key"] = {"key": js["token_key"]}
            except Exception as e:
                raise DetailedHTTPException(
                    exception=e,
                    detail={
                        "msg":
                        "Received Invalid JSON that may not contain surrogate_id",
                        "json": js
                    })

            # Create template
            self.payload["link_id"] = str(guid())
            # TODO: Currently you can generate endlessly new slr even if one exists already
            sq.task("Fill template for Account Mgmnt")
            template = {
                "code": js["code"],
                "data": {
                    "slr": {
                        "type": "ServiceLinkRecord",
                        "attributes": self.payload,
                    },
                    "surrogate_id": {
                        "type": "SurrogateId",
                        "attributes": {
                            "surrogate_id": self.payload["surrogate_id"],
                            "service_id": self.payload["service_id"],
                            "account_id": account_id
                        }
                    }
                },
            }

            debug_log.info("###########Template for Account Manager#")
            debug_log.info(dumps(template, indent=3))
            debug_log.info("########################################")
            sq.send_to("Account Manager", "Sign SLR at Account Manager")
            try:
                reply = self.AM.sign_slr(template, account_id)
            except AttributeError as e:
                raise DetailedHTTPException(
                    status=502,
                    title=
                    "It would seem initiating Account Manager Handler has failed.",
                    detail="Account Manager might be down or unresponsive.",
                    trace=traceback.format_exc(limit=100).splitlines())
            debug_log.info(dumps(reply, indent=2))

            # Parse JSON form Account Manager to format Service_Mgmnt understands.
            try:
                req = {
                    "data": {
                        "code": js["code"],
                    },
                    "slr": reply["data"]["slr"]["attributes"]["slr"]
                }

                debug_log.info("SLR O: {}".format(dumps(req, indent=3)))
            except Exception as e:
                raise DetailedHTTPException(
                    exception=e,
                    detail=
                    "Parsing JSON form Account Manager to format Service_Mgmnt understands has failed.",
                    trace=traceback.format_exc(limit=100).splitlines())

            try:
                sq.send_to(
                    "Service_Components Mgmnt",
                    "Send created and signed SLR to Service_Components Mgnt")
                endpoint = "/api/1.2/slr/slr"
                service_url = self.service_registry_handler.getService_url(
                    self.payload["service_id"].encode())
                debug_log.info("Service_ulr = {}, type: {}".format(
                    service_url, type(service_url)))
                response = post("{}{}".format(service_url, endpoint),
                                json=req,
                                timeout=self.request_timeout)
                debug_log.info("Request sent.")
                if not response.ok:
                    raise DetailedHTTPException(
                        status=response.status_code,
                        detail={
                            "Error from Service_Components Mgmnt":
                            loads(response.text)
                        },
                        title=response.reason)
            except DetailedHTTPException as e:
                raise e
            except Exception as e:
                raise DetailedHTTPException(
                    exception=e,
                    detail="Sending SLR to service has failed",
                    trace=traceback.format_exc(limit=100).splitlines())

        except DetailedHTTPException as e:
            raise e
        except Exception as e:
            raise DetailedHTTPException(
                title="Creation of SLR has failed.",
                exception=e,
                trace=traceback.format_exc(limit=100).splitlines())