Exemple #1
0
def test_log_with_bad_level_uses_info(set_console_ip, info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
        qpylib.log('hello', 'BAD')
        verify_log_file_content(log_path, [{'level': 'INFO', 'text': 'hello'}])
Exemple #2
0
def test_set_log_level_with_bad_level_uses_info(set_console_ip,
                                                debug_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
        qpylib.set_log_level('BAD')
        qpylib.log('hello debug', 'DEBUG')
        qpylib.log('hello default info')
        qpylib.log('hello info', 'INFO')
        qpylib.log('hello warning', 'WARNING')
        qpylib.log('hello error', 'ERROR')
        qpylib.log('hello critical', 'CRITICAL')
        verify_log_file_content(log_path, [{
            'level': 'INFO',
            'text': 'hello default info'
        }, {
            'level': 'INFO',
            'text': 'hello info'
        }, {
            'level': 'WARNING',
            'text': 'hello warning'
        }, {
            'level': 'ERROR',
            'text': 'hello error'
        }, {
            'level': 'CRITICAL',
            'text': 'hello critical'
        }],
                                not_expected_lines=[{
                                    'level': 'DEBUG',
                                    'text': 'hello debug'
                                }])
Exemple #3
0
def test_log_with_bad_level_raises_error(info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
        with pytest.raises(ValueError, match="Unknown level: 'BAD'"):
            qpylib.log('hello', 'BAD')
Exemple #4
0
def test_all_log_levels_with_set_debug_threshold(info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
        qpylib.set_log_level('DEBUG')
        qpylib.log('hello debug', 'DEBUG')
        qpylib.log('hello default info')
        qpylib.log('hello info', 'INFO')
        qpylib.log('hello warning', 'WARNING')
        qpylib.log('hello error', 'ERROR')
        qpylib.log('hello critical', 'CRITICAL')
        qpylib.log('hello exception', 'EXCEPTION')
    verify_log_file_content(log_path, [{
        'level': 'DEBUG',
        'text': 'hello debug'
    }, {
        'level': 'INFO',
        'text': 'hello default info'
    }, {
        'level': 'INFO',
        'text': 'hello info'
    }, {
        'level': 'WARNING',
        'text': 'hello warning'
    }, {
        'level': 'ERROR',
        'text': 'hello error'
    }, {
        'level': 'CRITICAL',
        'text': 'hello critical'
    }, {
        'level': 'ERROR',
        'text': 'hello exception'
    }])
Exemple #5
0
def test_set_log_level_sets_correct_level(info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
    qpylib.set_log_level('DEBUG')
    assert log_qpylib.QLOGGER.getEffectiveLevel() == logging.DEBUG
Exemple #6
0
def test_create_log_without_qradaf_app_uuid_skips_syslog_handler(
        set_console_ip, info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
    assert len(log_qpylib.QLOGGER.handlers) == 1
    assert isinstance(log_qpylib.QLOGGER.handlers[0], RotatingFileHandler)
Exemple #7
0
def test_create_without_console_ip_env_var_raises_error(
        info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        with pytest.raises(
                KeyError,
                match='Environment variable QRADAR_CONSOLE_IP is not set'):
            qpylib.create_log()
Exemple #8
0
def create_app():
    # Create a Flask instance.
    qflask = Flask(__name__)

    csrf = CSRFProtect()
    csrf.init_app(qflask)

    # Retrieve QRadar app id.
    qradar_app_id = qpylib.get_app_id()

    # Create unique session cookie name for this app.
    qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id)

    secret_key = ""
    try:
        # Read in secret key
        secret_key_store = Encryption({'name': 'secret_key', 'user': '******'})
        secret_key = secret_key_store.decrypt()
    except EncryptionError:
        # If secret key file doesn't exist/fail to decrypt it,
        # generate a new random password for it and encrypt it
        secret_key = secrets.token_urlsafe(64)
        secret_key_store = Encryption({'name': 'secret_key', 'user': '******'})
        secret_key_store.encrypt(secret_key)

    qflask.config["SECRET_KEY"] = secret_key

    # Hide server details in endpoint responses.
    # pylint: disable=unused-variable
    @qflask.after_request
    def obscure_server_header(resp):
        resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id)
        return resp

    # Register q_url_for function for use with Jinja2 templates.
    qflask.add_template_global(qpylib.q_url_for, 'q_url_for')

    # Initialize logging.
    qpylib.create_log()

    # To enable app health checking, the QRadar App Framework
    # requires every Flask app to define a /debug endpoint.
    # The endpoint function should contain a trivial implementation
    # that returns a simple confirmation response message.
    @qflask.route('/debug')
    def debug():
        return 'Pong!'

    # Import additional endpoints.
    # For more information see:
    #   https://flask.palletsprojects.com/en/1.1.x/tutorial/views
    from . import views
    qflask.register_blueprint(views.viewsbp)

    return qflask
Exemple #9
0
def test_create_log_with_ipv6(set_console_ipv6, info_threshold, tmpdir):
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = os.path.join(tmpdir.strpath,
                                                      'app.log')
        qpylib.create_log()
    assert len(qpylib.log_qpylib.QLOGGER.handlers) == 2
    for handler in qpylib.log_qpylib.QLOGGER.handlers:
        if isinstance(handler, SysLogHandler):
            assert handler.address[0] == '9.123.234.101'
        if isinstance(handler, RotatingFileHandler):
            check_rotating_file_handler_attrs(handler)
Exemple #10
0
def test_create_log_all_handlers(mock_manifest, set_console_ip, set_app_uuid,
                                 info_threshold, tmpdir):
    log_path = os.path.join(tmpdir.strpath, 'app.log')
    with patch('qpylib.log_qpylib._log_file_location') as mock_log_location:
        mock_log_location.return_value = log_path
        qpylib.create_log()
    assert log_qpylib.QLOGGER.getEffectiveLevel() == logging.INFO
    assert len(log_qpylib.QLOGGER.handlers) == 2
    for handler in log_qpylib.QLOGGER.handlers:
        if isinstance(handler, SysLogHandler):
            check_syslog_handler_attrs(handler)
        if isinstance(handler, RotatingFileHandler):
            check_rotating_file_handler_attrs(handler, log_path)
Exemple #11
0
def create_app():
    # Create a Flask instance.
    qflask = Flask(__name__)

    # Retrieve QRadar app id.
    qradar_app_id = qpylib.get_app_id()

    # Create unique session cookie name for this app.
    qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id)

    # Hide server details in endpoint responses.
    # pylint: disable=unused-variable
    @qflask.after_request
    def obscure_server_header(resp):
        resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id)
        return resp

    # Register q_url_for function for use with Jinja2 templates.
    qflask.add_template_global(qpylib.q_url_for, 'q_url_for')

    # Initialize logging.
    qpylib.create_log()

    # To enable app health checking, the QRadar App Framework
    # requires every Flask app to define a /debug endpoint.
    # The endpoint function should contain a trivial implementation
    # that returns a simple confirmation response message.
    @qflask.route('/debug')
    def debug():
        return 'Pong!'

    # Flask-Babel is an extension to Flask that adds i18n and l10n support
    # to any Flask application with the help of babel, pytz and speaklater.
    babel = Babel(qflask)

    # Try to select the language from the user accept header the browser transmits.
    # We support en/es/fr in this example.
    # The best match wins.
    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(LANGUAGES.keys())

    # Import additional endpoints.
    # For more information see:
    #   https://flask.palletsprojects.com/en/1.1.x/tutorial/views
    from . import views
    qflask.register_blueprint(views.viewsbp)

    return qflask
Exemple #12
0
def create_app():
    # Create a Flask instance.
    qflask = Flask(__name__)

    # Retrieve QRadar app id.
    qradar_app_id = qpylib.get_app_id()

    # Create unique session cookie name for this app.
    qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id)

    # Hide server details in endpoint responses.
    # pylint: disable=unused-variable
    @qflask.after_request
    def obscure_server_header(resp):
        resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id)
        return resp

    # Register q_url_for function for use with Jinja2 templates.
    qflask.add_template_global(qpylib.q_url_for, 'q_url_for')

    # Initialize logging.
    qpylib.create_log()

    # To enable app health checking, the QRadar App Framework
    # requires every Flask app to define a /debug endpoint.
    # The endpoint function should contain a trivial implementation
    # that returns a simple confirmation response message.
    @qflask.route('/debug')
    def debug():
        return 'Pong!'

    # Import additional endpoints.
    # For more information see:
    #   https://flask.palletsprojects.com/en/1.1.x/tutorial/views
    from . import views
    qflask.register_blueprint(views.viewsbp)

    return qflask
Exemple #13
0
__author__ = 'IBM'

import os.path
import sys
import json
import re
from flask import Flask
from flask import send_from_directory, render_template, request
from qpylib import qpylib

app = Flask(__name__)
# Create log here to prevent race condition when importing views
qpylib.create_log()

qpylib.register_jsonld_endpoints()

from app import views


@app.route('/debug')
def debug():
    return send_from_directory('/store/log/', 'app.log')


@app.route('/debug_view')
def debug_view():
    debug_content = open('/store/log/app.log').read()
    return render_template('debug.html', debug_content=debug_content)


@app.route('/resources/<path:filename>')
__author__ = 'IBM'

from flask import Flask
from flask import send_from_directory, render_template, request
from qpylib import qpylib

app = Flask(__name__)
# Create log here to prevent race condition when importing views
qpylib.create_log()

from app import views

@app.route('/debug')
def debug():
    return send_from_directory( '/store/log/', 'app.log' )

@app.route('/debug_view')
def debug_view():
    debug_content = open('/store/log/app.log').read()
    return render_template('debug.html', debug_content=debug_content)

@app.route('/resources/<path:file>')
def send_file(file):
    qpylib.log(" >>> route resources >>>")
    qpylib.log(" file=" + file)
    qpylib.log(" app.static_folder=" + app.static_folder)
    qpylib.log(" full file path =" + app.static_folder + '/resources/'+file )
    return send_from_directory(app.static_folder, 'resources/'+file)

@app.route('/log_level', methods=['POST'])
def log_level():
Exemple #15
0
def create_app():
    # Create a Flask instance.
    qflask = Flask(__name__)

    csrf = CSRFProtect()
    csrf.init_app(qflask)

    # Retrieve QRadar app id.
    qradar_app_id = qpylib.get_app_id()

    # Create unique session cookie name for this app.
    qflask.config['SESSION_COOKIE_NAME'] = 'session_{0}'.format(qradar_app_id)

    secret_key = ""
    try:
        # Read in secret key
        secret_key_store = Encryption({'name': 'secret_key', 'user': '******'})
        secret_key = secret_key_store.decrypt()
    except EncryptionError:
        # If secret key file doesn't exist/fail to decrypt it,
        # generate a new random password for it and encrypt it
        secret_key = secrets.token_urlsafe(64)
        secret_key_store = Encryption({'name': 'secret_key', 'user': '******'})
        secret_key_store.encrypt(secret_key)

    qflask.config["SECRET_KEY"] = secret_key

    # Initialize database settings and flask configuration options via json file
    with open(qpylib.get_root_path(
            "container/conf/config.json")) as config_json_file:
        config_json = json.load(config_json_file)

    qflask.config.update(config_json)

    # Hide server details in endpoint responses.
    # pylint: disable=unused-variable
    @qflask.after_request
    def obscure_server_header(resp):
        resp.headers['Server'] = 'QRadar App {0}'.format(qradar_app_id)
        return resp

    # Register q_url_for function for use with Jinja2 templates.
    qflask.add_template_global(qpylib.q_url_for, 'q_url_for')

    # Initialize logging.
    qpylib.create_log()

    # To enable app health checking, the QRadar App Framework
    # requires every Flask app to define a /debug endpoint.
    # The endpoint function should contain a trivial implementation
    # that returns a simple confirmation response message.
    @qflask.route('/debug')
    def debug():
        return 'Pong!'

    # Import additional endpoints.
    # For more information see:
    #   https://flask.palletsprojects.com/en/1.1.x/tutorial/views
    from . import views
    qflask.register_blueprint(views.viewsbp)

    # NOTE: This sample app does not deal with migration of db schema between app versions as its v1.0.0.
    # If you have multiple versions of your application and the schema changes between them you would
    # need to add your own migration process at this point so that the schema is updated and loaded.
    # Also worth versioning your schema changes as well so you can perform the migration.

    db_host = qflask.config["DB_HOST"]
    db_port = qflask.config["DB_PORT"]
    db_user = qflask.config["DB_USER"]
    db_name = qflask.config["DB_NAME"]

    # create db if it doesnt exist and load schema
    if not db_exists(db_host, db_port, db_user, db_name):
        schema_file_path = qpylib.get_root_path("container/conf/db/schema.sql")
        create_db(db_host, db_port, db_user, db_name)
        execute_schema_sql(db_host, db_port, db_user, db_name,
                           schema_file_path)

    return qflask