Commit d810c2f2 authored by Alex Kakiris's avatar Alex Kakiris
Browse files

refine log levels in Security_API

parent ac4cb87b
Loading
Loading
Loading
Loading
Loading
+7 −7
Original line number Diff line number Diff line
@@ -39,7 +39,7 @@ def cert_validation():

            cn = cert.subject.get_attributes_for_oid(
                x509.OID_COMMON_NAME)[0].value.strip()
            current_app.logger.info(f"CN: {cn}")
            current_app.logger.debug(f"CN: {cn}")
            if cn != "superadmin" and "AEF" not in cn:
                cert_signature = cert.signature.hex()

@@ -83,7 +83,7 @@ def securities_security_id_token_post(security_id, body): # noqa: E501

    :rtype: Union[AccessTokenRsp, Tuple[AccessTokenRsp, int], Tuple[AccessTokenRsp, int, Dict[str, str]]
    """
    current_app.logger.info("Creating security token")
    current_app.logger.debug("Creating security token")
    if request.is_json:
        res_owner_id = ResOwnerId.from_dict(request.get_json())  # noqa: E501

@@ -113,7 +113,7 @@ def trusted_invokers_api_invoker_id_delete(api_invoker_id): # noqa: E501

    :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]]
    """
    current_app.logger.info("Removing security context")
    current_app.logger.debug("Removing security context")
    return service_security_ops.delete_servicesecurity(api_invoker_id)


@@ -133,7 +133,7 @@ def trusted_invokers_api_invoker_id_delete_post(api_invoker_id, body): # noqa:
    if request.is_json:
        body = SecurityNotification.from_dict(request.get_json())  # noqa: E501

    current_app.logger.info("Revoking permissions")
    current_app.logger.debug("Revoking permissions")
    res = service_security_ops.revoke_api_authorization(api_invoker_id, body)

    return res
@@ -153,7 +153,7 @@ def trusted_invokers_api_invoker_id_get(api_invoker_id, authentication_info=None

    :rtype: Union[ServiceSecurity, Tuple[ServiceSecurity, int], Tuple[ServiceSecurity, int, Dict[str, str]]
    """
    current_app.logger.info("Obtaining security context")
    current_app.logger.debug("Obtaining security context")
    res = service_security_ops.get_servicesecurity(
        api_invoker_id, authentication_info, authorization_info)

@@ -172,7 +172,7 @@ def trusted_invokers_api_invoker_id_put(api_invoker_id, body): # noqa: E501

    :rtype: Union[ServiceSecurity, Tuple[ServiceSecurity, int], Tuple[ServiceSecurity, int, Dict[str, str]]
    """
    current_app.logger.info("Creating security context")
    current_app.logger.debug("Creating security context")

    if request.is_json:
        body = ServiceSecurity.from_dict(request.get_json())  # noqa: E501
@@ -203,7 +203,7 @@ def trusted_invokers_api_invoker_id_update_post(api_invoker_id, body): # noqa:

    :rtype: Union[ServiceSecurity, Tuple[ServiceSecurity, int], Tuple[ServiceSecurity, int, Dict[str, str]]
    """
    current_app.logger.info("Updating security context")
    current_app.logger.debug("Updating security context")

    if request.is_json:
        body = ServiceSecurity.from_dict(request.get_json())  # noqa: E501
+1 −1
Original line number Diff line number Diff line
@@ -16,7 +16,7 @@ class Subscriber():
        self.p.subscribe("internal-messages", "acls-messages")

    def listen(self):
        current_app.logger.info("Listening security context messages")
        current_app.logger.debug("Listening security context messages")
        for raw_message in self.p.listen():
            if raw_message["type"] == "message" and raw_message["channel"].decode('utf-8') == "internal-messages":
                internal_redis_event = json.loads(
+29 −29
Original line number Diff line number Diff line
@@ -49,7 +49,7 @@ class SecurityOperations(Resource):
            "Checking api invoker with id: " + api_invoker_id)
        invoker = invokers_col.find_one({"api_invoker_id": api_invoker_id})
        if invoker is None:
            current_app.logger.error("Invoker not found")
            current_app.logger.warning("Invoker not found")
            return not_found_error(detail="Invoker not found", cause="API Invoker not exists or invalid ID")

        return None
@@ -61,7 +61,7 @@ class SecurityOperations(Resource):
            current_app.logger.debug("Checking scope")
            header = scope[0:4]
            if header != "3gpp":
                current_app.logger.error("Bad format scope")
                current_app.logger.warning("Bad format scope")
                token_error = AccessTokenErr(error="invalid_scope", error_description="The first characters must be '3gpp'")
                return make_response(object=clean_empty(token_error.to_dict()), status=400)

@@ -76,7 +76,7 @@ class SecurityOperations(Resource):
            for group in groups:
                aef_id, api_names = group.split(":")
                if aef_id not in aef_security_context:
                    current_app.logger.error("Bad format Scope, not valid aef id ")
                    current_app.logger.warning("Bad format Scope, not valid aef id ")
                    token_error = AccessTokenErr(error="invalid_scope", error_description="One of aef_id not belongs of your security context")
                    return make_response(object=clean_empty(token_error.to_dict()), status=400)

@@ -85,7 +85,7 @@ class SecurityOperations(Resource):
                    service = capif_service_col.find_one(
                        {"$and": [{"api_name": api_name}, {self.filter_aef_id: aef_id}]})
                    if service is None:
                        current_app.logger.error("Bad format Scope, not valid api name")
                        current_app.logger.warning("Bad format Scope, not valid api name")
                        token_error = AccessTokenErr(
                            error="invalid_scope",
                            error_description="One of the api names does not exist or is not associated with the aef id provided")
@@ -163,7 +163,7 @@ class SecurityOperations(Resource):
                                                          "_id": 0, "api_invoker_id": 0})

                if services_security_object is None:
                    current_app.logger.error("Not found security context")
                    current_app.logger.warning("Not found security context")
                    return not_found_error(detail=security_context_not_found_detail, cause=api_invoker_no_context_cause)

                for security_info_obj in services_security_object['security_info']:
@@ -223,7 +223,7 @@ class SecurityOperations(Resource):
                            del security_info_obj['authorization_info']

                    else:
                        current_app.logger.error("Bad format security method")
                        current_app.logger.warning("Bad format security method")
                        return bad_request_error(detail="Bad format security method", cause="Bad format security method", invalid_params=[{"param": "securityMethod", "reason": "Bad format security method"}])


@@ -256,7 +256,7 @@ class SecurityOperations(Resource):
                return result

            if rfc3987.match(service_security.notification_destination, rule="URI") is None:
                current_app.logger.error("Bad url format")
                current_app.logger.warning("Bad url format")
                return bad_request_error(detail="Bad Param", cause="Detected Bad format of param", invalid_params=[{"param": "notificationDestination", "reason": "Not valid URL format"}])

            services_security_object = mycol.find_one(
@@ -264,7 +264,7 @@ class SecurityOperations(Resource):

            if services_security_object is not None:

                current_app.logger.error(
                current_app.logger.warning(
                    "Already security context defined with same api invoker id")
                return forbidden_error(detail="Security method already defined", cause="Identical AEF Profile IDs")

@@ -292,7 +292,7 @@ class SecurityOperations(Resource):
                    current_app.logger.debug("Aef profile: " + str(aef_profiles))

                    if aef_profiles is None:
                        current_app.logger.error(
                        current_app.logger.warning(
                            "Not found service with this interface description: " + json.dumps(clean_empty(service_instance.interface_details.to_dict())))
                        return not_found_error(detail=f"Service with interfaceDescription {json.dumps(clean_empty(service_instance.interface_details.to_dict()))} not found", cause="Not found Service")

@@ -335,7 +335,7 @@ class SecurityOperations(Resource):
                            # After processing all interfaces, use the combined set
                            valid_security_methods.update(interface_methods)
                        else:
                            current_app.logger.debug("No interfaces found in AEF profile.")
                            current_app.logger.warning("No interfaces found in AEF profile.")
                            return not_found_error(detail=f"Service with interfaceDescription {json.dumps(clean_empty(service_instance.interface_details.to_dict()))} not found", cause="Not found Service")

                    psk_interface = service_instance.interface_details.to_dict()
@@ -354,7 +354,7 @@ class SecurityOperations(Resource):
                    
                    current_app.logger.debug("Aef profile: " + str(services_security_object))
                    if services_security_object is None:
                        current_app.logger.error(
                        current_app.logger.warning(
                            "Not found service with this aef id: " + service_instance.aef_id)
                        return not_found_error(detail="Service with this aefId not found", cause="Not found Service")
                    
@@ -406,7 +406,7 @@ class SecurityOperations(Resource):
                        valid_security_methods) & set(pref_security_methods)

                if len(list(valid_security_method)) == 0:
                    current_app.logger.error(
                    current_app.logger.warning(
                        "Not found comptaible security method with pref security method")
                    return bad_request_error(detail="Not found compatible security method with pref security method", cause="Error pref security method", invalid_params=[{"param": "prefSecurityMethods", "reason": "pref security method not compatible with security method available"}])

@@ -429,7 +429,7 @@ class SecurityOperations(Resource):
                    tls_protocol = request.headers.get('X-TLS-Protocol', 'N/A')
                    session_id = request.headers.get('X-TLS-Session-ID', 'N/A')  
                    mkey = request.headers.get('X-TLS-MKey', 'N/A') 
                    current_app.logger.info(f"TLS Protocol: {tls_protocol}, Session id: {session_id}, Master Key: {mkey}") 
                    current_app.logger.debug(f"TLS Protocol: {tls_protocol}, Session id: {session_id}, Master Key: {mkey}") 

                    if psk_interface:
                        current_app.logger.debug("Deriving PSK")
@@ -438,13 +438,13 @@ class SecurityOperations(Resource):

                        service_instance.authorization_info = str(psk)
                    else:
                        current_app.logger.error("No interface information available to derive PSK")
                        current_app.logger.warning("No interface information available to derive PSK")
                        
                # Send service instance to ACL
                current_app.logger.debug("Sending message to create ACL")
                publish_ops.publish_message("acls-messages", "create-acl:"+str(
                    api_invoker_id)+":"+str(service_instance.api_id)+":"+str(service_instance.aef_id))
                current_app.logger.debug(
                current_app.logger.info(
                    "Inserted security context in database")

            # We use update with $setOnInsert and $push with $each to add the security info array if the document is created
@@ -485,7 +485,7 @@ class SecurityOperations(Resource):
                services_security_count = mycol.count_documents(my_query)

                if services_security_count == 0:
                    current_app.logger.error(security_context_not_found_detail)
                    current_app.logger.warning(security_context_not_found_detail)
                    return not_found_error(detail=security_context_not_found_detail, cause=api_invoker_no_context_cause)

                mycol.delete_many(my_query)
@@ -493,7 +493,7 @@ class SecurityOperations(Resource):
                publish_ops.publish_message(
                    "acls-messages", "remove-acl:"+api_invoker_id)

                current_app.logger.debug(
                current_app.logger.info(
                    "Removed security context from database")
                out = "The security info of Network App with Network App ID " + \
                    api_invoker_id + " were deleted.", 204
@@ -536,7 +536,7 @@ class SecurityOperations(Resource):

            service_security = mycol.find_one({"api_invoker_id": security_id})
            if service_security is None:
                current_app.logger.error("Not found security context with id: " + security_id)
                current_app.logger.warning("Not found security context with id: " + security_id)
                return not_found_error(detail= security_context_not_found_detail, cause=api_invoker_no_context_cause)

            result = self.__check_scope(
@@ -555,7 +555,7 @@ class SecurityOperations(Resource):
            access_token_resp = AccessTokenRsp(access_token=access_token, token_type="Bearer", expires_in=int(
                expire_time.total_seconds()), scope=access_token_req["scope"])

            current_app.logger.debug("Created access token")
            current_app.logger.info("Created access token")

            res = make_response(object=clean_empty(access_token_resp.to_dict()), status=200)
            return res
@@ -579,7 +579,7 @@ class SecurityOperations(Resource):
            old_object = mycol.find_one({"api_invoker_id": api_invoker_id})

            if old_object is None:
                current_app.logger.error(
                current_app.logger.warning(
                    "Service api not found with id: " + api_invoker_id)
                return not_found_error(detail="Service API not existing", cause="Not exist securiy information for this invoker")

@@ -605,7 +605,7 @@ class SecurityOperations(Resource):
                    current_app.logger.debug("Aef profile: " + str(aef_profile))

                    if aef_profiles is None:
                        current_app.logger.error(
                        current_app.logger.warning(
                            "Not found service with this interface description: " + json.dumps(clean_empty(service_instance.interface_details.to_dict())))
                        return not_found_error(detail=f"Service with interfaceDescription {json.dumps(clean_empty(service_instance.interface_details.to_dict()))} not found", cause="Not found Service")

@@ -632,7 +632,7 @@ class SecurityOperations(Resource):
                            # After processing all interfaces, use the combined set
                            valid_security_methods.update(interface_methods)
                        else:
                            current_app.logger.debug("No interfaces found in AEF profile.")
                            current_app.logger.warning("No interfaces found in AEF profile.")
                            return not_found_error(detail=f"Service with interfaceDescription {json.dumps(clean_empty(service_instance.interface_details.to_dict()))} not found", cause="Not found Service")

                    psk_interface = service_instance.interface_details.to_dict()
@@ -653,7 +653,7 @@ class SecurityOperations(Resource):
                    
                    current_app.logger.debug("Aef profile: " + str(services_security_object))
                    if services_security_object is None:
                        current_app.logger.error(
                        current_app.logger.warning(
                            "Not found service with this aef id: " + service_instance.aef_id)
                        return not_found_error(detail="Service with this aefId not found", cause="Not found Service")
                    
@@ -705,7 +705,7 @@ class SecurityOperations(Resource):
                        valid_security_methods) & set(pref_security_methods)
                    
                if len(list(valid_security_method)) == 0:
                    current_app.logger.error(
                    current_app.logger.warning(
                        "Not found comptaible security method with pref security method")
                    return bad_request_error(detail="Not found compatible security method with pref security method", cause="Error pref security method", invalid_params=[{"param": "prefSecurityMethods", "reason": "pref security method not compatible with security method available"}])
                
@@ -717,7 +717,7 @@ class SecurityOperations(Resource):
                    tls_protocol = request.headers.get('X-TLS-Protocol', 'N/A')
                    session_id = request.headers.get('X-TLS-Session-ID', 'N/A')  
                    mkey = request.headers.get('X-TLS-MKey', 'N/A') 
                    current_app.logger.info(f"TLS Protocol: {tls_protocol}, Session id: {session_id}, Master Key: {mkey}") 
                    current_app.logger.debug(f"TLS Protocol: {tls_protocol}, Session id: {session_id}, Master Key: {mkey}") 

                    if psk_interface:
                        current_app.logger.debug("Deriving PSK")
@@ -726,14 +726,14 @@ class SecurityOperations(Resource):

                        service_instance.authorization_info = str(psk)
                    else:
                        current_app.logger.error("No interface information available to derive PSK")
                        current_app.logger.warning("No interface information available to derive PSK")

            service_security = service_security.to_dict()
            service_security = clean_empty(service_security)

            result = mycol.find_one_and_update(old_object, {"$set": service_security}, projection={
                                               '_id': 0, "api_invoker_id": 0}, return_document=ReturnDocument.AFTER, upsert=False)
            current_app.logger.debug(
            current_app.logger.info(
                    "Inserted security context in database")

            # result = clean_empty(result)
@@ -743,7 +743,7 @@ class SecurityOperations(Resource):
                publish_ops.publish_message("acls-messages", "create-acl:"+str(
                    api_invoker_id)+":"+str(update_acl['api_id'])+":"+str(update_acl['aef_id']))

            current_app.logger.debug("Updated security context")
            current_app.logger.info("Updated security context")

            res= make_response(object=dict_to_camel_case(clean_empty(result)), status=200)
            res.headers['Location'] = f"https://{os.getenv("CAPIF_HOSTNAME")}/capif-security/v1/trustedInvokers/{str(api_invoker_id)}"
@@ -769,7 +769,7 @@ class SecurityOperations(Resource):
            services_security_context = mycol.find_one(my_query)

            if services_security_context is None:
                current_app.logger.error(security_context_not_found_detail)
                current_app.logger.warning(security_context_not_found_detail)
                return not_found_error(detail=security_context_not_found_detail, cause=api_invoker_no_context_cause)

            updated_security_context = services_security_context.copy()