Ejemplo n.º 1
0
    def test_setup_security(self):
        disabled = registry._disabled_content_types
        self.assertEqual(0, len(disabled))

        current_app.conf.CELERY_TASK_SERIALIZER = 'json'

        setup_security()
        self.assertIn('application/x-python-serialize', disabled)
        disabled.clear()
Ejemplo n.º 2
0
    def test_setup_security(self):
        disabled = registry._disabled_content_types
        self.assertEqual(0, len(disabled))

        current_app.conf.CELERY_TASK_SERIALIZER = 'json'

        setup_security()
        self.assertIn('application/x-python-serialize', disabled)
        disabled.clear()
Ejemplo n.º 3
0
    def test_setup_registry_complete(self, dis, reg, key="KEY", cert="CERT"):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = "B" if calls[0] else "A"
                return m
            finally:
                calls[0] += 1

        with mock_open(side_effect=effect):
            store = Mock()
            setup_security(["json"], key, cert, store)
            dis.assert_called_with(["json"])
            reg.assert_called_with("A", "B", store)
Ejemplo n.º 4
0
    def test_setup_registry_complete(self, dis, reg, key="KEY", cert="CERT"):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = "B" if calls[0] else "A"
                return m
            finally:
                calls[0] += 1

        with mock_open(side_effect=effect):
            store = Mock()
            setup_security(["json"], key, cert, store)
            dis.assert_called_with(["json"])
            reg.assert_called_with("A", "B", store)
Ejemplo n.º 5
0
    def test_setup_registry_complete(self, dis, reg, key='KEY', cert='CERT'):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = 'B' if calls[0] else 'A'
                return m
            finally:
                calls[0] += 1

        with mock_open(side_effect=effect):
            store = Mock()
            setup_security(['json'], key, cert, store)
            dis.assert_called_with(['json'])
            reg.assert_called_with('A', 'B', store)
Ejemplo n.º 6
0
    def setup_security(self, allowed_serializers=None, key=None, cert=None,
                       store=None, digest='sha1', serializer='json'):
        """Setup the message-signing serializer.

        This will affect all application instances (a global operation).

        Disables untrusted serializers and if configured to use the ``auth``
        serializer will register the auth serializer with the provided settings
        into the Kombu serializer registry.

        :keyword allowed_serializers: List of serializer names, or
            content_types that should be exempt from being disabled.
        :keyword key: Name of private key file to use.
            Defaults to the :setting:`security_key` setting.
        :keyword cert: Name of certificate file to use.
            Defaults to the :setting:`security_certificate` setting.
        :keyword store: Directory containing certificates.
            Defaults to the :setting:`security_cert_store` setting.
        :keyword digest: Digest algorithm used when signing messages.
            Default is ``sha1``.
        :keyword serializer: Serializer used to encode messages after
            they have been signed.  See :setting:`task_serializer` for
            the serializers supported.
            Default is ``json``.

        """
        from celery.security import setup_security
        return setup_security(allowed_serializers, key, cert,
                              store, digest, serializer, app=self)
Ejemplo n.º 7
0
    def setup_security(self, allowed_serializers=None, key=None, cert=None,
                       store=None, digest=DEFAULT_SECURITY_DIGEST,
                       serializer='json'):
        """Setup the message-signing serializer.

        This will affect all application instances (a global operation).

        Disables untrusted serializers and if configured to use the ``auth``
        serializer will register the ``auth`` serializer with the provided
        settings into the Kombu serializer registry.

        Arguments:
            allowed_serializers (Set[str]): List of serializer names, or
                content_types that should be exempt from being disabled.
            key (str): Name of private key file to use.
                Defaults to the :setting:`security_key` setting.
            cert (str): Name of certificate file to use.
                Defaults to the :setting:`security_certificate` setting.
            store (str): Directory containing certificates.
                Defaults to the :setting:`security_cert_store` setting.
            digest (str): Digest algorithm used when signing messages.
                Default is ``sha256``.
            serializer (str): Serializer used to encode messages after
                they've been signed.  See :setting:`task_serializer` for
                the serializers supported.  Default is ``json``.
        """
        from celery.security import setup_security
        return setup_security(allowed_serializers, key, cert,
                              store, digest, serializer, app=self)
Ejemplo n.º 8
0
    def setup_security(self, allowed_serializers=None, key=None, cert=None,
                       store=None, digest='sha1', serializer='json'):
        """Setup the message-signing serializer.

        This will affect all application instances (a global operation).

        Disables untrusted serializers and if configured to use the ``auth``
        serializer will register the ``auth`` serializer with the provided
        settings into the Kombu serializer registry.

        :keyword allowed_serializers: List of serializer names, or
            content_types that should be exempt from being disabled.
        :keyword key: Name of private key file to use.
            Defaults to the :setting:`security_key` setting.
        :keyword cert: Name of certificate file to use.
            Defaults to the :setting:`security_certificate` setting.
        :keyword store: Directory containing certificates.
            Defaults to the :setting:`security_cert_store` setting.
        :keyword digest: Digest algorithm used when signing messages.
            Default is ``sha1``.
        :keyword serializer: Serializer used to encode messages after
            they have been signed.  See :setting:`task_serializer` for
            the serializers supported.
            Default is ``json``.

        """
        from celery.security import setup_security
        return setup_security(allowed_serializers, key, cert,
                              store, digest, serializer, app=self)
Ejemplo n.º 9
0
    def test_setup_registry_complete(self, dis, reg, key='KEY', cert='CERT'):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = 'B' if calls[0] else 'A'
                return m
            finally:
                calls[0] += 1

        with mock_open(side_effect=effect):
            store = Mock()
            setup_security(['json'], key, cert, store)
            dis.assert_called_with(['json'])
            reg.assert_called_with('A', 'B', store)
Ejemplo n.º 10
0
    def test_setup_registry_complete(self, dis, reg, key='KEY', cert='CERT'):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = 'B' if calls[0] else 'A'
                return m
            finally:
                calls[0] += 1

        with mock_open(side_effect=effect):
            with patch('celery.security.registry') as registry:
                store = Mock()
                setup_security(['json'], key, cert, store)
                dis.assert_called_with(['json'])
                reg.assert_called_with('A', 'B', store, 'sha1', 'json')
                registry._set_default_serializer.assert_called_with('auth')
Ejemplo n.º 11
0
 def setup_security(self,
                    allowed_serializers=None,
                    key=None,
                    cert=None,
                    store=None,
                    digest='sha1',
                    serializer='json'):
     from celery.security import setup_security
     return setup_security(allowed_serializers,
                           key,
                           cert,
                           store,
                           digest,
                           serializer,
                           app=self)
Ejemplo n.º 12
0
def create_app(config_filename='config.py', config_override={}):
    """Factory function for flask application.

    Args:
        config_filename:
            path to python config file
        config_override:
            a dict with settings to use to override config from file;
            useful for writing very specific tests.
    """
    app = Flask(__name__)

    #
    # Configuration handling
    #

    if config_filename:
        app.config.from_pyfile(config_filename)

    for key, value in config_override.items():
        app.config[key] = value

    # ReCaptcha
    recaptcha.init_app(app)

    # Limiter
    limiter.init_app(app)

    # Scheduler
    if app.config.get('SCHEDULER_ENABLED', True):
        if scheduler.running:
            scheduler.shutdown()
        scheduler.init_app(app)
        scheduler.start()

    # Celery
    celery.init_app(app)
    from celery.security import setup_security
    setup_security()

    #
    # Error logging
    #
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler

        os.makedirs('logs', exist_ok=True)

        file_handler = RotatingFileHandler('logs/app.log',
                                           maxBytes=10 * 1024 * 1024,
                                           backupCount=5)
        file_handler.setLevel(logging.WARNING)
        root_logger = logging.getLogger()
        root_logger.addHandler(file_handler)

    #
    # Database creation
    #
    db.app = app
    db.init_app(app)
    db.create_all(bind='__all__')

    mode = app.config.get('BDB_MODE', 'c')
    bdb.open(app.config['BDB_DNA_TO_PROTEIN_PATH'], mode=mode)
    bdb_refseq.open(app.config['BDB_GENE_TO_ISOFORM_PATH'], mode=mode)

    if app.config['USE_LEVENSTHEIN_MYSQL_UDF']:
        with app.app_context():
            for bind_key in ['bio', 'cms']:
                engine = get_engine(bind_key)
                engine.execute("DROP FUNCTION IF EXISTS levenshtein_ratio")
                engine.execute(
                    "CREATE FUNCTION levenshtein_ratio RETURNS REAL SONAME 'levenshtein.so'"
                )

    #
    # Configure Login Manager
    #
    from models import User
    from models import AnonymousUser

    login_manager.anonymous_user = AnonymousUser
    login_manager.user_loader(User.user_loader)

    login_manager.init_app(app)

    #
    # Configure mail service
    #
    mail.init_app(app)

    #
    # Register assets
    #
    assets = Environment(app)

    for name, bundle in bundles.items():
        assets.register(name, bundle)

    #
    # Import views
    #

    # allow access to this app from views through module
    import sys
    sys.path.insert(0, '..')

    with app.app_context():

        from website.views import views

        for view in views:
            view.register(app)

    #
    # Register functions for Jinja
    #

    import jinja2

    base_dir = os.path.dirname(os.path.realpath(__file__))

    template_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(os.path.join(base_dir, 'static/js_templates')),
    ])
    app.jinja_loader = template_loader

    from website.views.cms import substitute_variables
    from website.views.cms import thousand_separated_number
    from website.views.cms import ContentManagementSystem
    from jinja2_pluralize import pluralize
    import json

    # csrf adds hooks in before_request to validate token
    app.before_request(csrf.csrf_protect)

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    jinja_globals = app.jinja_env.globals
    jinja_filters = app.jinja_env.filters

    app.dependency_manager = DependencyManager(app)

    jinja_globals['dependency'] = app.dependency_manager.get_dependency
    jinja_globals['system_menu'] = ContentManagementSystem._system_menu
    jinja_globals['system_setting'] = ContentManagementSystem._system_setting
    jinja_globals['inline_help'] = ContentManagementSystem._inline_help
    jinja_globals['text_entry'] = ContentManagementSystem._text_entry
    jinja_globals['t_sep'] = thousand_separated_number
    jinja_globals['csrf_token'] = csrf.new_csrf_token
    jinja_globals['is_debug_mode'] = app.debug

    jinja_filters['json'] = json.dumps
    jinja_filters['substitute_allowed_variables'] = substitute_variables
    jinja_filters['pluralize'] = pluralize

    return app
Ejemplo n.º 13
0
 def test_setup_security__default_app(self, current_app):
     setup_security()
Ejemplo n.º 14
0
 def setup_security(self, allowed_serializers=None, key=None, cert=None,
                    store=None, digest='sha1', serializer='json'):
     from celery.security import setup_security
     return setup_security(allowed_serializers, key, cert,
                           store, digest, serializer, app=self)
Ejemplo n.º 15
0
 def test_setup_security__default_app(self, current_app):
     with pytest.raises(ImproperlyConfigured):
         setup_security()
Ejemplo n.º 16
0
 def test_setup_security__default_app(self, current_app):
     setup_security()
Ejemplo n.º 17
0
 def test_setup_security__default_app(self, current_app):
     with pytest.raises(ImproperlyConfigured):
         setup_security()