Пример #1
0
 def __init__(self):
     super(Status_Change, 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,
                                         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.helper_object = Helpers(current_app.config)
Пример #2
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"]
Пример #3
0
class Status_Change(Resource):
    def __init__(self):
        super(Status_Change, 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,
                                            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.helper_object = Helpers(current_app.config)

    @error_handler
    def post(self, acc_id, srv_id, cr_id, new_status):
        '''post

        :return: Returns latest csr for source
        '''
        try:
            debug_log.info(
                "We received status change request for cr_id ({}) for srv_id ({}) on account ({})"
                .format(cr_id, srv_id, acc_id))
            # TODO: Do we need srv_id for anything?
            # TODO: How do we authorize this request? Who is allowed to make it?
            # Get previous_csr_id
            previous_csr_id = self.AM.get_last_csr(cr_id)["csr_id"]
            csr_payload = self.helper_object.gen_csr(acc_id, cr_id, new_status,
                                                     previous_csr_id)
            debug_log.info("Created CSR payload:\n {}".format(csr_payload))
            result = self.AM.create_new_csr(cr_id, csr_payload)

            # result = self.AM.get_last_csr(cr_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(result))
        return {"status": "OK"}  # result
Пример #4
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
Пример #5
0
class AuthToken(Resource):
    def __init__(self):
        super(AuthToken, 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,
                                            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)))
        helper_object = Helpers(current_app.config)
        self.gen_auth_token = helper_object.gen_auth_token

    @error_handler
    def get(self, cr_id):
        '''get

        :return: Returns Auth_token to service
        '''
        ##
        # Generate Auth Token and save it.
        # helper.py has the function template, look into it.
        ##

        #gen_auth_token()
        try:
            result = self.AM.get_AuthTokenInfo(cr_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.debug(dumps(result, indent=2))
        token = self.gen_auth_token(result)
        debug_log.info(dumps(result, indent=2))
        return {"auth_token": token}
Пример #6
0
class Introspection_Missing(Resource):
    def __init__(self):
        super(Introspection_Missing, 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,
                                            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)))
        helper_object = Helpers(current_app.config)

    @error_handler
    def get(self, cr_id, csr_id):
        '''get

        :return: Returns latest csr for source
        '''
        try:
            debug_log.info(
                "We received introspection request for cr_id ({})".format(
                    cr_id))
            result = self.AM.get_missing_csr(cr_id, csr_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(result))
        return result
Пример #7
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
Пример #8
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"]
        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)

    @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 = getService(service_ids["sink"])
        _consent_form["sink"]["service_id"] = sink["name"]
        source = getService(service_ids["source"])
        _consent_form["source"]["service_id"] = source["name"]

        sq.task("Generate RS_ID")
        sq.task("Store RS_ID")

        rs_id = self.Helpers.gen_rs_id(source["name"])
        _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 Mgmt", "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

        # Generate common_cr for both sink and source.
        sq.task("Generate common CR")
        common_cr_source = self.Helpers.gen_cr_common(
            surrogate_id_source, _consent_form["source"]["rs_id"],
            slr_id_source)
        common_cr_sink = self.Helpers.gen_cr_common(
            surrogate_id_sink, _consent_form["source"]["rs_id"], slr_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)

        sq.task("Generate CR for source")
        source_cr = self.Helpers.gen_cr_source(common_cr_source, _consent_form,
                                               Operator_public_key)
        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 Mgmt", "Send CR/CSR to sign and store")
        result = self.AM.signAndstore(sink_cr, sink_csr, source_cr, source_csr,
                                      account_id)
        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("Sink", "Post CR-Sink, CSR-Sink")
        sq.send_to("Source", "Post CR-Source, CSR-Source")

        debug_log.info(dumps(crs_csrs_payload, indent=2))
        CR_installer.delay(crs_csrs_payload, SH.getService_url(sink_srv_id),
                           SH.getService_url(source_srv_id))
        return {"status": 201, "msg": "CREATED"}, 201
Пример #9
0
class VerifySLR(Resource):
    def __init__(self):
        super(VerifySLR, self).__init__()
        self.app = current_app
        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):

        debug_log.info(dumps(request.json, indent=2))

        sq.task("Load SLR to object")
        slr = request.json["slr"]
        debug_log.info("{} {}".format("SLR STORE:\n", slr))

        sq.task("Load slr payload as object")
        payload = slr["payload"]
        debug_log.info("{} {}".format("Before Fix:", payload))

        sq.task("Fix possible incorrect padding in payload")
        payload += '=' * (-len(payload) % 4
                          )  # Fix incorrect padding of base64 string.
        debug_log.info("{} {}".format("After Fix :", payload))

        sq.task("Decode payload and store it into object")
        content = decode(payload.encode())

        sq.task("Load decoded payload as python dict")
        payload = loads(
            loads(content.decode("utf-8"))
        )  # TODO: Figure out why we get str out of loads the first time?
        debug_log.info(payload)
        debug_log.info(type(payload))

        sq.task("Fetch link_id from decoded payload")
        slr_id = payload["link_id"]

        try:
            ##
            # Verify SLR with key from Service_Components Management
            ##
            sq.task("Load account_id from database")
            for code_json in self.query_db(
                    "select * from session_store where code = ?;",
                [request.json["data"]["code"]]):
                debug_log.debug("{}  {}".format(type(code_json), code_json))
                account_id = loads(code_json["json"])["account_id"]

            debug_log.info("################Verify########################")
            debug_log.info(dumps(request.json))
            debug_log.info("########################################")

            sq.task("Load slr and code from json payload")
            slr = request.json["slr"]
            code = request.json["data"]["code"]

            sq.send_to("Account Manager", "Verify SLR at Account Manager.")
            try:
                reply = self.AM.verify_slr(payload, code, slr, 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())
            if reply.ok:
                sq.reply_to("Service_Components Mgmnt", "201, SLR VERIFIED")
                debug_log.info(reply.text)
                return reply.text, reply.status_code
            else:
                raise DetailedHTTPException(
                    status=reply.status_code,
                    detail={
                        "msg":
                        "Something went wrong while verifying SLR at Account Manager",
                        "content": reply.json()
                    },
                    title=reply.reason)
        except DetailedHTTPException as e:
            raise e

        except Exception as e:
            raise DetailedHTTPException(
                exception=e,
                detail=
                "Verifying SLR failed for unknown reason, access is denied.")
Пример #10
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())
Пример #11
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
Пример #12
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())