Example #1
0
 def test_get_response_headers_preflight_with_cache(self):
     cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
     assert_equal(cors.get_response_headers(preflight=True),
                  [('Access-Control-Allow-Origin', '*'),
                   ('Access-Control-Allow-Methods', 'GET, PUT'),
                   ('Access-Control-Allow-Headers', 'accept'),
                   ('Access-Control-Max-Age', '86400')])
Example #2
0
 def test_get_response_headers_preflight_with_cache(self):
     cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
     assert_equal(cors.get_response_headers(preflight=True),
                  [('Access-Control-Allow-Origin', '*'),
                   ('Access-Control-Allow-Methods', 'GET, PUT'),
                   ('Access-Control-Allow-Headers', 'accept'),
                   ('Access-Control-Max-Age', '86400')])
Example #3
0
 def setUp(self):
     self.app = MagicMock()
     self.allowed_methods = ['GET', 'POST', 'DELETE']
     self.allowed_headers = ['Authorization', 'Accept']
     self.cors = CORSMiddleware(
         self.app,
         self.allowed_methods,
         self.allowed_headers)
Example #4
0
def _make_core_app(root, global_conf, full_stack=True, **app_conf):
    """
    Set allura up with the settings found in the PasteDeploy configuration
    file used.

    :param root: The controller module containing the TG root
    :param global_conf: The global settings for allura (those
        defined under the ``[DEFAULT]`` section).
    :type global_conf: dict
    :param full_stack: Should the whole TG2 stack be set up?
    :type full_stack: str or bool
    :return: The allura application with all the relevant middleware
        loaded.

    This is the PasteDeploy factory for the allura application.

    ``app_conf`` contains all the application-specific settings (those defined
    under ``[app:main]``.


    """
    # Run all the initialization code here
    mimetypes.init([pkg_resources.resource_filename('allura', 'etc/mime.types')] + mimetypes.knownfiles)

    # Configure MongoDB
    ming.configure(**app_conf)

    # Configure ActivityStream
    if asbool(app_conf.get('activitystream.recording.enabled', False)):
        activitystream.configure(**h.convert_bools(app_conf, prefix='activitystream.'))

    # Configure EW variable provider
    ew.render.TemplateEngine.register_variable_provider(get_tg_vars)

    # Set FormEncode language to english, as we don't support any other locales
    formencode.api.set_stdtranslation(domain='FormEncode', languages=['en'])

    # Create base app
    base_config = ForgeConfig(root)
    load_environment = base_config.make_load_environment()

    # Code adapted from tg.configuration, replacing the following lines:
    #     make_base_app = base_config.setup_tg_wsgi_app(load_environment)
    #     app = make_base_app(global_conf, full_stack=True, **app_conf)

    # Configure the TG environment
    load_environment(global_conf, app_conf)

    app = tg.TGApp()

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'inner':
            app = Middleware(app, config)

    # Required for sessions
    app = SessionMiddleware(app, config, data_serializer=BeakerPickleSerializerWithLatin1())
    # Handle "Remember me" functionality
    app = RememberLoginMiddleware(app, config)
    # Redirect 401 to the login page
    app = LoginRedirectMiddleware(app)
    # Add instrumentation
    app = AlluraTimerMiddleware(app, app_conf)
    # Clear cookies when the CSRF field isn't posted
    if not app_conf.get('disable_csrf_protection'):
        app = CSRFMiddleware(app, '_session_id')
    if asbool(config.get('cors.enabled', False)):
        # Handle CORS requests
        allowed_methods = aslist(config.get('cors.methods'))
        allowed_headers = aslist(config.get('cors.headers'))
        cache_duration = asint(config.get('cors.cache_duration', 0))
        app = CORSMiddleware(app, allowed_methods, allowed_headers, cache_duration)
    # Setup the allura SOPs
    app = allura_globals_middleware(app)
    # Ensure http and https used per config
    if config.get('override_root') != 'task':
        app = SSLMiddleware(app, app_conf.get('no_redirect.pattern'),
                            app_conf.get('force_ssl.pattern'),
                            app_conf.get('force_ssl.logged_in'))
    # Setup resource manager, widget context SOP
    app = ew.WidgetMiddleware(
        app,
        compress=True,
        use_cache=not asbool(global_conf['debug']),
        script_name=app_conf.get('ew.script_name', '/_ew_resources/'),
        url_base=app_conf.get('ew.url_base', '/_ew_resources/'),
        extra_headers=ast.literal_eval(app_conf.get('ew.extra_headers', '[]')),
        cache_max_age=asint(app_conf.get('ew.cache_header_seconds', 60*60*24*365)),

        # settings to pass through to jinja Environment for EW core widgets
        # these are for the easywidgets' own [easy_widgets.engines] entry point
        # (the Allura [easy_widgets.engines] entry point is named "jinja" (not jinja2) but it doesn't need
        #  any settings since it is a class that uses the same jinja env as the rest of allura)
        **{
            'jinja2.auto_reload': asbool(config['auto_reload_templates']),
            'jinja2.bytecode_cache': AlluraJinjaRenderer._setup_bytecode_cache(),
            'jinja2.cache_size': asint(config.get('jinja_cache_size', -1)),
        }
    )
    # Handle static files (by tool)
    app = StaticFilesMiddleware(app, app_conf.get('static.script_name'))
    # Handle setup and flushing of Ming ORM sessions
    app = MingMiddleware(app)
    # Set up the registry for stacked object proxies (SOPs).
    #    streaming=true ensures they won't be cleaned up till
    #    the WSGI application's iterator is exhausted
    app = RegistryManager(app, streaming=True)

    # "task" wsgi would get a 2nd request to /error/document if we used this middleware
    if config.get('override_root') not in ('task', 'basetest_project_root'):
        if asbool(config['debug']):
            # Converts exceptions to HTTP errors, shows traceback in debug mode
            # don't use TG footer with extra CSS & images that take time to load
            tg.error.footer_html = '<!-- %s %s -->'
            app = tg.error.ErrorHandler(app, global_conf, **config['tg.errorware'])
        else:
            app = ErrorMiddleware(app, config, **config['tg.errorware'])

        app = SetRequestHostFromConfig(app, config)

        # Redirect some status codes to /error/document
        if asbool(config['debug']):
            app = StatusCodeRedirect(app, base_config.handle_status_codes)
        else:
            app = StatusCodeRedirect(
                app, base_config.handle_status_codes + [500])

    for mw_ep in h.iter_entry_points('allura.middleware'):
        Middleware = mw_ep.load()
        if getattr(Middleware, 'when', 'inner') == 'outer':
            app = Middleware(app, config)

    return app
Example #5
0
 def test_init(self):
     cors = CORSMiddleware(self.app, ['get', 'post'], ['Some-Header'])
     assert_equal(cors.app, self.app)
     assert_equal(cors.allowed_methods, ['GET', 'POST'])
     assert_equal(cors.allowed_headers, set(['some-header']))
Example #6
0
 def setUp(self):
     self.app = MagicMock()
     self.allowed_methods = ['GET', 'POST', 'DELETE']
     self.allowed_headers = ['Authorization', 'Accept']
     self.cors = CORSMiddleware(self.app, self.allowed_methods,
                                self.allowed_headers)
Example #7
0
class TestCORSMiddleware(object):
    def setUp(self):
        self.app = MagicMock()
        self.allowed_methods = ['GET', 'POST', 'DELETE']
        self.allowed_headers = ['Authorization', 'Accept']
        self.cors = CORSMiddleware(self.app, self.allowed_methods,
                                   self.allowed_headers)

    def test_init(self):
        cors = CORSMiddleware(self.app, ['get', 'post'], ['Some-Header'])
        assert_equal(cors.app, self.app)
        assert_equal(cors.allowed_methods, ['GET', 'POST'])
        assert_equal(cors.allowed_headers, set(['some-header']))

    def test_call_not_api_request(self):
        callback = MagicMock()
        env = {'PATH_INFO': '/p/test/'}
        self.cors(env, callback)
        self.app.assert_called_once_with(env, callback)

    def test_call_invalid_cors(self):
        callback = MagicMock()
        env = {'PATH_INFO': '/rest/p/test/'}
        self.cors(env, callback)
        self.app.assert_called_once_with(env, callback)

    def test_handle_call_simple_request(self):
        callback = MagicMock()
        env = {
            'PATH_INFO': '/rest/p/test/',
            'HTTP_ORIGIN': 'my.site.com',
            'REQUEST_METHOD': 'GET'
        }
        self.cors(env, callback)
        assert_equal(self.app.call_count, 1)
        assert_equal(self.app.call_args_list[0][0][0], env)
        assert_not_equal(self.app.call_args_list[0][0][1], callback)

    @patch('allura.lib.custom_middleware.exc', autospec=True)
    def test_handle_call_preflight_request(self, exc):
        callback = MagicMock()
        env = {
            'PATH_INFO': '/rest/p/test/',
            'HTTP_ORIGIN': 'my.site.com',
            'REQUEST_METHOD': 'OPTIONS',
            'HTTP_ACCESS_CONTROL_REQUEST_METHOD': 'POST'
        }
        self.cors(env, callback)
        assert_equal(self.app.call_count, 0)
        exc.HTTPOk.assert_called_once_with(headers=[(
            'Access-Control-Allow-Origin',
            '*'), ('Access-Control-Allow-Methods', 'GET, POST, DELETE'
                   ), ('Access-Control-Allow-Headers',
                       'accept, authorization')])
        exc.HTTPOk.return_value.assert_called_once_with(env, callback)

    def test_get_response_headers_simple(self):
        # Allow-Origin: * is crucial for security, since that prevents browsers from exposing results fetched withCredentials: true (aka cookies)
        assert_equal(self.cors.get_response_headers(),
                     [('Access-Control-Allow-Origin', '*')])
        assert_equal(self.cors.get_response_headers(preflight=False),
                     [('Access-Control-Allow-Origin', '*')])

    def test_get_response_headers_preflight(self):
        assert_equal(
            self.cors.get_response_headers(preflight=True),
            [('Access-Control-Allow-Origin', '*'),
             ('Access-Control-Allow-Methods', 'GET, POST, DELETE'),
             ('Access-Control-Allow-Headers', 'accept, authorization')])

    def test_get_response_headers_preflight_with_cache(self):
        cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
        assert_equal(cors.get_response_headers(preflight=True),
                     [('Access-Control-Allow-Origin', '*'),
                      ('Access-Control-Allow-Methods', 'GET, PUT'),
                      ('Access-Control-Allow-Headers', 'accept'),
                      ('Access-Control-Max-Age', '86400')])

    def test_get_access_control_request_headers(self):
        key = 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'
        f = self.cors.get_access_control_request_headers
        assert_equal(f({}), set())
        assert_equal(f({key: ''}), set())
        assert_equal(f({key: 'Authorization, Accept'}),
                     set(['authorization', 'accept']))
Example #8
0
class TestCORSMiddleware(object):

    def setUp(self):
        self.app = MagicMock()
        self.allowed_methods = ['GET', 'POST', 'DELETE']
        self.allowed_headers = ['Authorization', 'Accept']
        self.cors = CORSMiddleware(
            self.app,
            self.allowed_methods,
            self.allowed_headers)

    def test_init(self):
        cors = CORSMiddleware(self.app, ['get', 'post'], ['Some-Header'])
        assert_equal(cors.app, self.app)
        assert_equal(cors.allowed_methods, ['GET', 'POST'])
        assert_equal(cors.allowed_headers, set(['some-header']))

    def test_call_not_api_request(self):
        callback = MagicMock()
        env = {'PATH_INFO': '/p/test/'}
        self.cors(env, callback)
        self.app.assert_called_once_with(env, callback)

    def test_call_invalid_cors(self):
        callback = MagicMock()
        env = {'PATH_INFO': '/rest/p/test/'}
        self.cors(env, callback)
        self.app.assert_called_once_with(env, callback)

    def test_handle_call_simple_request(self):
        callback = MagicMock()
        env = {'PATH_INFO': '/rest/p/test/',
               'HTTP_ORIGIN': 'my.site.com',
               'REQUEST_METHOD': 'GET'}
        self.cors(env, callback)
        assert_equal(self.app.call_count, 1)
        assert_equal(self.app.call_args_list[0][0][0], env)
        assert_not_equal(self.app.call_args_list[0][0][1], callback)

    @patch('allura.lib.custom_middleware.exc', autospec=True)
    def test_handle_call_preflight_request(self, exc):
        callback = MagicMock()
        env = {'PATH_INFO': '/rest/p/test/',
               'HTTP_ORIGIN': 'my.site.com',
               'REQUEST_METHOD': 'OPTIONS',
               'HTTP_ACCESS_CONTROL_REQUEST_METHOD': 'POST'}
        self.cors(env, callback)
        assert_equal(self.app.call_count, 0)
        exc.HTTPOk.assert_called_once_with(headers=[
            ('Access-Control-Allow-Origin', '*'),
            ('Access-Control-Allow-Methods', 'GET, POST, DELETE'),
            ('Access-Control-Allow-Headers', 'accept, authorization')
        ])
        exc.HTTPOk.return_value.assert_called_once_with(env, callback)

    def test_get_response_headers_simple(self):
        # Allow-Origin: * is crucial for security, since that prevents browsers from exposing results fetched withCredentials: true (aka cookies)
        assert_equal(self.cors.get_response_headers(),
                     [('Access-Control-Allow-Origin', '*')])
        assert_equal(self.cors.get_response_headers(preflight=False),
                     [('Access-Control-Allow-Origin', '*')])

    def test_get_response_headers_preflight(self):
        assert_equal(
            self.cors.get_response_headers(preflight=True),
            [('Access-Control-Allow-Origin', '*'),
             ('Access-Control-Allow-Methods', 'GET, POST, DELETE'),
             ('Access-Control-Allow-Headers', 'accept, authorization')])

    def test_get_response_headers_preflight_with_cache(self):
        cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
        assert_equal(cors.get_response_headers(preflight=True),
                     [('Access-Control-Allow-Origin', '*'),
                      ('Access-Control-Allow-Methods', 'GET, PUT'),
                      ('Access-Control-Allow-Headers', 'accept'),
                      ('Access-Control-Max-Age', '86400')])

    def test_get_access_control_request_headers(self):
        key = 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'
        f = self.cors.get_access_control_request_headers
        assert_equal(f({}), set())
        assert_equal(f({key: ''}), set())
        assert_equal(f({key: 'Authorization, Accept'}),
                     set(['authorization', 'accept']))