def test_init_event_service_with_valid_certificate(self,
                                                       get_oneview_client,
                                                       config_mock, conn_param,
                                                       block_conn, channel):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': 'cert_file.crt'
            },
        }

        os.makedirs(name='scmb', exist_ok=True)
        self.addCleanup(shutil.rmtree, 'scmb')

        oneview_client = mock.MagicMock()
        oneview_client.certificate_authority.get.return_value = "CA CERT"
        oneview_client.certificate_rabbitmq.generate.return_value = True
        get_oneview_client.return_value = oneview_client
        oneview_client.certificate_rabbitmq.get_key_pair.return_value = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'}

        pika_mock = mock.MagicMock()
        pika_mock.channel.Channel = {}
        block_conn.return_value = pika_mock
        conn_param.return_value = {}
        channel.return_value = {}

        scmb.init_event_service()

        self.assertTrue(scmb._has_valid_certificates())
        self.assertTrue(scmb._is_cert_working_with_scmb())
    def test_is_cert_working_with_scmb_failed_case(self, config_mock,
                                                   get_map_scmb_connections,
                                                   get_oneview_client,
                                                   _get_ov_ca_cert_base64data):
        config_mock.get_authentication_mode.return_value = 'session'
        config_mock.get_oneview_multiple_ips.return_value = ['1.1.1.1']
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': '/dir/cert_file.crt'
            },
        }

        oneview_client = mock.MagicMock()
        get_oneview_client.return_value = oneview_client
        oneview_client.certificate_rabbitmq.get_key_pair.return_value = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'
        }

        oneview_client.connection = 'con'
        _get_ov_ca_cert_base64data.return_value = "CA CERT"
        get_map_scmb_connections.return_value = []

        scmb.init_event_service()

        scmb_thread = SCMB('2.2.2.2', 'cred', 'token')

        self.assertFalse(scmb_thread._is_cert_working_with_scmb())
def _add_subscription_to_file(subscription):
    file_content = get_file_content()
    if file_content:
        if not file_content.get('members'):
            # On first subscription request, start SCMB service
            if config.auth_mode_is_session():
                token = request.headers.get('x-auth-token')
                scmb.init_event_service(token)
            else:
                scmb.init_event_service()
        file_content['members'].append(subscription)
        _update_all_subscription(file_content)
Exemplo n.º 4
0
def post_session():
    """Posts Session

        The response to the POST request to create a session includes:

            - An X-Auth-Token header that contains a session auth token that
            the client can use an subsequent requests.
            - A Location header that contains a link to the newly created
            session resource.
            - The JSON response body that contains a full representation of
            the newly created session object.

        Exception:
            HPOneViewException: Invalid username or password.
            return abort(401)

    """

    try:
        try:
            body = request.get_json()
            username = body["UserName"]
            password = body["Password"]
        except Exception:
            error_message = "Invalid JSON key. The JSON request body " \
                            "must have the keys UserName and Password"
            abort(status.HTTP_400_BAD_REQUEST, error_message)

        token, session_id = client_session.login(username, password)

        sess = Session(session_id)

        if subscription.add_subscription_from_file():
            scmb.init_event_service(token)

        return ResponseBuilder.success_201(
            sess, {
                "Location": sess.redfish["@odata.id"],
                "X-Auth-Token": token
            })

    except HPOneViewException as e:
        logging.exception('Unauthorized error: {}'.format(e))
        abort(status.HTTP_401_UNAUTHORIZED)
    def test_init_event_service_with_certs_already_generated(
            self, config_mock, get_ov_client, _has_certs_path, conn_param,
            block_conn, channel):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': '/dir/cert_file.crt'
            },
        }

        pika_mock = mock.MagicMock()
        pika_mock.channel.Channel = {}
        block_conn.return_value = pika_mock
        conn_param.return_value = {}
        channel.return_value = {}
        oneview_client = mock.MagicMock()
        get_ov_client.return_value = oneview_client
        _has_certs_path.return_value = True

        scmb.init_event_service()

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.run()

        self.assertTrue(scmb_thread._has_valid_certificates())
def main(config_file_path,
         logging_config_file_path,
         is_dev_env=False,
         is_debug_mode=False):
    # Load config file, schemas and creates a OV connection
    try:
        config.configure_logging(logging_config_file_path)
        config.load_config(config_file_path)
    except Exception as e:
        logging.exception('Failed to load app configuration')
        logging.exception(e)
        exit(1)

    # Check auth mode
    auth_mode = config.get_authentication_mode()

    if auth_mode not in ["conf", "session"]:
        logging.error("Invalid authentication_mode. Please check your conf"
                      " file. Valid values are 'conf' or 'session'")

    # Flask application
    app = Flask(__name__)

    app.url_map.strict_slashes = False

    # Register blueprints
    app.register_blueprint(redfish_base, url_prefix="/redfish/")
    app.register_blueprint(service_root, url_prefix='/redfish/v1/')
    app.register_blueprint(event_service)
    app.register_blueprint(session_service)
    app.register_blueprint(chassis_collection)
    app.register_blueprint(computer_system_collection)
    app.register_blueprint(computer_system)
    app.register_blueprint(composition_service)
    app.register_blueprint(chassis)
    app.register_blueprint(ethernet_interface)
    app.register_blueprint(ethernet_interface_collection)
    app.register_blueprint(manager_collection)
    app.register_blueprint(manager)
    app.register_blueprint(metadata)
    app.register_blueprint(odata)
    app.register_blueprint(storage)
    app.register_blueprint(thermal)
    app.register_blueprint(storage_collection)
    app.register_blueprint(network_adapter_collection)
    app.register_blueprint(network_interface_collection)
    app.register_blueprint(network_port_collection)
    app.register_blueprint(network_device_function_collection)
    app.register_blueprint(network_device_function)
    app.register_blueprint(network_interface)
    app.register_blueprint(network_adapter)
    app.register_blueprint(network_port)
    app.register_blueprint(processor)
    app.register_blueprint(processor_collection)
    app.register_blueprint(storage_for_resource_block)
    app.register_blueprint(resource_block_collection)
    app.register_blueprint(resource_block)
    app.register_blueprint(vlan_network_interface)
    app.register_blueprint(zone_collection)
    app.register_blueprint(zone)

    # Init cached data
    client_session.init_map_clients()
    client_session.init_gc_for_expired_sessions()
    multiple_oneview.init_map_resources()
    multiple_oneview.init_map_appliances()
    category_resource.init_map_category_resources()

    if auth_mode == "conf":
        app.register_blueprint(subscription_collection)
        app.register_blueprint(subscription)

        client_session.login_conf_mode()
    else:
        app.register_blueprint(session)

    @app.before_request
    def init_performance_data():
        if logging.getLogger().isEnabledFor(logging.DEBUG):
            g.start_time_req = time.time()
            g.elapsed_time_ov = 0

    @app.before_request
    def check_authentication():
        # If authenticating do not check for anything
        if request.url_rule and \
           request.url_rule.rule == SessionCollection.BASE_URI and \
           request.method == "POST":
            return None

        if connection.is_service_root():
            return None

        if config.auth_mode_is_session():
            x_auth_token = request.headers.get('x-auth-token')
            client_session.check_authentication(x_auth_token)

        g.oneview_client = \
            handler_multiple_oneview.MultipleOneViewResource()

    @app.before_request
    def has_odata_version_header():
        """Deny request that specify a different OData-Version than 4.0"""
        odata_version_header = request.headers.get("OData-Version")

        if odata_version_header is None:
            pass
        elif odata_version_header != "4.0":
            abort(
                status.HTTP_412_PRECONDITION_FAILED,
                "The request specify a different OData-Version "
                "header then 4.0. This server also responds "
                "to requests without the OData-Version header")

    @app.after_request
    def set_odata_version_header(response):
        """Set OData-Version header for all responses"""
        response.headers["OData-Version"] = "4.0"
        return response

    @app.after_request
    def log_performance_data(response):
        if logging.getLogger().isEnabledFor(logging.DEBUG):
            end_time = time.time()
            req_time = end_time - g.start_time_req
            logging.getLogger(PERFORMANCE_LOGGER_NAME).debug(
                "OneView process: " + str(g.elapsed_time_ov))
            logging.getLogger(PERFORMANCE_LOGGER_NAME).debug(
                "Redfish process: " + str(req_time - g.elapsed_time_ov))
            logging.getLogger(PERFORMANCE_LOGGER_NAME).debug(
                "Total process: " + str(req_time))
        return response

    @app.errorhandler(status.HTTP_400_BAD_REQUEST)
    def bad_request(error):
        """Creates a Bad Request Error response"""
        logging.error(error.description)

        return ResponseBuilder.error_400(error)

    @app.errorhandler(status.HTTP_401_UNAUTHORIZED)
    def unauthorized_error(error):
        """Creates a Unauthorized Error response"""
        logging.error(error.description)

        return ResponseBuilder.error_401(error)

    @app.errorhandler(status.HTTP_403_FORBIDDEN)
    def forbidden(error):
        """Creates a Forbidden Error response"""
        logging.error(error.description)

        return ResponseBuilder.error_403(error)

    @app.errorhandler(status.HTTP_404_NOT_FOUND)
    def not_found(error):
        """Creates a Not Found Error response"""
        logging.error(error.description)

        return ResponseBuilder.error_404(error)

    @app.errorhandler(status.HTTP_500_INTERNAL_SERVER_ERROR)
    def internal_server_error(error):
        """Creates an Internal Server Error response"""
        logging.error(error)

        return ResponseBuilder.error_500(error)

    @app.errorhandler(status.HTTP_501_NOT_IMPLEMENTED)
    def not_implemented(error):
        """Creates a Not Implemented Error response"""
        logging.error(error.description)

        return ResponseBuilder.error_501(error)

    @app.errorhandler(HPOneViewException)
    def hp_oneview_client_exception(exception):
        logging.exception(exception)
        response = ResponseBuilder.error_by_hp_oneview_exception(exception)

        # checking if session has expired on Oneview
        if config.auth_mode_is_session() and \
                response.status_code == status.HTTP_401_UNAUTHORIZED:
            token = request.headers.get('x-auth-token')
            client_session.clear_session_by_token(token)

        return response

    @app.errorhandler(OneViewRedfishException)
    def oneview_redfish_exception(exception):
        logging.exception(exception)

        return ResponseBuilder.oneview_redfish_exception(exception)

    scmb.init_event_service()

    app_config = config.get_config()

    try:
        host = app_config["redfish"]["redfish_host"]

        # Gets the correct IP type based on the string
        ipaddress.ip_address(host)
    except ValueError:
        logging.error("Informed IP is not valid. Check the "
                      "variable 'redfish_host' on your config file.")
        exit(1)

    try:
        port = int(app_config["redfish"]["redfish_port"])
    except Exception:
        logging.exception(
            "Port must be an integer number between 1 and 65536.")
        exit(1)
    # Checking port range
    if port < 1 or port > 65536:
        logging.error("Port must be an integer number between 1 and 65536.")
        exit(1)

    if app_config["ssl"]["SSLType"] in ("self-signed", "adhoc"):
        logging.warning("Server is starting with a self-signed certificate.")
    if app_config["ssl"]["SSLType"] == "disabled":
        logging.warning(
            "Server is starting in HTTP mode. This is an insecure mode. "
            "Running the server with HTTPS enabled is highly recommended.")

    ssl_type = app_config["ssl"]["SSLType"]
    # Check SSLType:
    if ssl_type not in ('disabled', 'adhoc', 'certs', 'self-signed'):
        logging.error("Invalid SSL type: {}. Must be one of: disabled, adhoc, "
                      "self-signed or certs".format(ssl_type))
        exit(1)

    if ssl_type == 'disabled':
        app.run(host=host, port=port, debug=is_debug_mode)
    elif ssl_type == 'adhoc':
        app.run(host=host, port=port, debug=is_debug_mode, ssl_context="adhoc")
    else:
        # We should use certs file provided by the user
        ssl_cert_file = app_config["ssl"]["SSLCertFile"]
        ssl_key_file = app_config["ssl"]["SSLKeyFile"]

        # Generating cert files if they don't exists
        if ssl_type == "self-signed":
            if not os.path.exists(ssl_cert_file) and not \
                    os.path.exists(ssl_key_file):
                logging.warning("Generating self-signed certs")
                # Generate certificates
                util.generate_certificate(os.path.dirname(ssl_cert_file),
                                          "self-signed", 2048)
            else:
                logging.warning("Using existing self-signed certs")
        elif ssl_cert_file == "" or ssl_key_file == "":
            logging.error(
                "SSL type: is 'cert' but one of the files are missing on"
                "the config file. SSLCertFile: {}, SSLKeyFile: {}.".format(
                    ssl_cert_file, ssl_key_file))

        if is_dev_env and is_debug_mode:
            ssl_context = (ssl_cert_file, ssl_key_file)
            app.run(host=host,
                    port=port,
                    debug=is_debug_mode,
                    ssl_context=ssl_context)
        else:
            start_cherrypy(app,
                           host=host,
                           port=port,
                           ssl_cert_file=ssl_cert_file,
                           ssl_key_file=ssl_key_file,
                           is_dev_env=is_dev_env)
    def test_init_event_service_on_session_mode(self, config_mock):
        config_mock.get_authentication_mode.return_value = 'session'
        scmb.init_event_service()

        self.assertFalse(scmb._has_valid_certificates())
        self.assertFalse(scmb._is_cert_working_with_scmb())