Python werkzeug.contrib.fixers.ProxyFix() Examples

The following are 30 code examples of werkzeug.contrib.fixers.ProxyFix(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module werkzeug.contrib.fixers , or try the search function .
Example #1
Source File: config.py    From nomad with Apache License 2.0 6 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)

        if app.config.get('ENABLE_PROXYFIX'):
            # handle proxy server headers
            from werkzeug.contrib.fixers import ProxyFix
            app.wsgi_app = ProxyFix(app.wsgi_app)

        if app.config.get('VERBOSE_SQLALCHEMY'):
            import logging
            from logging import StreamHandler
            stream_handler = StreamHandler()
            stream_handler.setLevel(logging.INFO)
            sql_logger = logging.getLogger('sqlalchemy.engine')
            sql_logger.addHandler(stream_handler)
            sql_logger.setLevel(logging.INFO) 
Example #2
Source File: app_object.py    From docassemble with MIT License 6 votes vote down vote up
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig
    import docassemble.webapp.database
    import docassemble.webapp.db_object
    connect_string = docassemble.webapp.database.connection_string()
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = docassemble.webapp.db_object.init_flask()
    db.init_app(app)
    csrf = CSRFProtect()
    csrf.init_app(app)
    babel = Babel()
    babel.init_app(app)
    if daconfig.get('behind https load balancer', False):
        if proxyfix_version >= 15:
            app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
        else:
            app.wsgi_app = ProxyFix(app.wsgi_app)
    if 'cross site domains' in daconfig:
        CORS(app, origins=daconfig['cross site domains'], supports_credentials=True)
    return app, csrf, babel 
Example #3
Source File: app.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def mount_apps(app: Flask):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    wsgiapp = WSGILogger(
        app.wsgi_app, [logging.StreamHandler()], ApacheFormatter(),
        propagate=False)
    cherrypy.tree.graft(wsgiapp, "/")

    cherrypy.tree.mount(None, "/favicon", {
        "/": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": favicon_dir,
            "tools.etags.on": True,
            "tools.etags.autotags": True
        }
    })

    cherrypy.tree.mount(None, "/public/images", {
        "/": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": img_dir,
            "tools.etags.on": True,
            "tools.etags.autotags": True
        }
    }) 
Example #4
Source File: test_checks.py    From flask-hookserver with MIT License 6 votes vote down vote up
def test_ipv4(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config['VALIDATE_IP'] = True
    app.config['VALIDATE_SIGNATURE'] = False
    client = app.test_client()

    rv = client.post('/', headers={'X-Forwarded-For': '192.30.252.1'})
    assert rv.status_code == 404

    rv = client.post('/hooks', headers={'X-Forwarded-For': '192.30.252.1'})
    assert rv.status_code == 400

    rv = client.post('/hooks', headers={'X-Forwarded-For': '192.30.251.255'})
    assert b'Requests must originate from GitHub' in rv.data
    assert rv.status_code == 403

    rv = client.post('/hooks', headers={'X-Forwarded-For': '192.31.0.1'})
    assert b'Requests must originate from GitHub' in rv.data
    assert rv.status_code == 403 
Example #5
Source File: test_checks.py    From flask-hookserver with MIT License 6 votes vote down vote up
def test_ipv6(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config['VALIDATE_IP'] = True
    app.config['VALIDATE_SIGNATURE'] = False
    client = app.test_client()

    rv = client.post('/', headers={'X-Forwarded-For': '::ffff:c01e:fc01'})
    assert rv.status_code == 404

    rv = client.post('/hooks', headers={'X-Forwarded-For': '::ffff:c01e:fc01'})
    assert rv.status_code == 400

    rv = client.post('/hooks', headers={'X-Forwarded-For': '::ffff:c01e:fbff'})
    assert b'Requests must originate from GitHub' in rv.data
    assert rv.status_code == 403

    rv = client.post('/hooks', headers={'X-Forwarded-For': '::ffff:c01f:1'})
    assert b'Requests must originate from GitHub' in rv.data
    assert rv.status_code == 403 
Example #6
Source File: test_checks.py    From flask-hookserver with MIT License 6 votes vote down vote up
def test_secret_key(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config['SECRET_KEY'] = b'Some key'
    app.config['VALIDATE_IP'] = False
    app.config['VALIDATE_SIGNATURE'] = True
    client = app.test_client()

    sig = 'e1590250fd7dd7882185062d1ade5bef8cb4319c'
    headers = {
        'X-Hub-Signature': 'sha1=' + sig,
        'X-GitHub-Event': 'ping',
        'X-GitHub-Delivery': 'abc',
    }
    rv = client.post('/hooks', content_type='application/json', data='{}',
                     headers=headers)
    assert rv.status_code == 200 
Example #7
Source File: test_checks.py    From flask-hookserver with MIT License 6 votes vote down vote up
def test_all_checks(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config['GITHUB_WEBHOOKS_KEY'] = b'Some key'
    app.config['VALIDATE_IP'] = True
    app.config['VALIDATE_SIGNATURE'] = True
    client = app.test_client()

    sig = 'e1590250fd7dd7882185062d1ade5bef8cb4319c'
    headers = {
        'X-Forwarded-For': '::ffff:c01e:fc01',
        'X-Hub-Signature': 'sha1=' + sig,
        'X-GitHub-Event': 'ping',
        'X-GitHub-Delivery': 'abc',
    }
    rv = client.post('/hooks', content_type='application/json', data='{}',
                     headers=headers)
    assert rv.status_code == 200 
Example #8
Source File: config.py    From USSD-Python-Demo with MIT License 5 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)
        # handle proxy server errors
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #9
Source File: config.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # Handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #10
Source File: config.py    From flask-base with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # Handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #11
Source File: test_checks.py    From flask-hookserver with MIT License 5 votes vote down vote up
def test_ignore_ip(app):
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.config['VALIDATE_IP'] = False
    app.config['VALIDATE_SIGNATURE'] = False
    client = app.test_client()

    rv = client.post('/', headers={'X-Forwarded-For': '192.30.251.255'})
    assert rv.status_code == 404

    rv = client.post('/', headers={'X-Forwarded-For': '::ffff:c01e:fbff'})
    assert rv.status_code == 404 
Example #12
Source File: config.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

        # log to stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler) 
Example #13
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def mount_apps(app: Flask):
    app.register_blueprint(powersource)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    wsgiapp = WSGILogger(
        app.wsgi_app, [logging.StreamHandler()], ApacheFormatter(),
        propagate=False)
    cherrypy.tree.graft(wsgiapp, "/") 
Example #14
Source File: fixers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_proxy_fix(self):
        @Request.application
        def app(request):
            return Response('%s|%s' % (
                request.remote_addr,
                # do not use request.host as this fixes too :)
                request.environ['HTTP_HOST']
            ))
        app = fixers.ProxyFix(app, num_proxies=2)
        environ = dict(create_environ(),
            HTTP_X_FORWARDED_PROTO="https",
            HTTP_X_FORWARDED_HOST='example.com',
            HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8',
            REMOTE_ADDR='127.0.0.1',
            HTTP_HOST='fake'
        )

        response = Response.from_app(app, environ)

        self.assert_equal(response.get_data(), b'1.2.3.4|example.com')

        # And we must check that if it is a redirection it is
        # correctly done:

        redirect_app = redirect('/foo/bar.hml')
        response = Response.from_app(redirect_app, environ)

        wsgi_headers = response.get_wsgi_headers(environ)
        assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml' 
Example #15
Source File: fixers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_proxy_fix_weird_enum(self):
        @fixers.ProxyFix
        @Request.application
        def app(request):
            return Response(request.remote_addr)
        environ = dict(create_environ(),
            HTTP_X_FORWARDED_FOR=',',
            REMOTE_ADDR='127.0.0.1',
        )

        response = Response.from_app(app, environ)
        self.assert_strict_equal(response.get_data(), b'127.0.0.1') 
Example #16
Source File: fixers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_proxy_fix(self):
        @Request.application
        def app(request):
            return Response('%s|%s' % (
                request.remote_addr,
                # do not use request.host as this fixes too :)
                request.environ['HTTP_HOST']
            ))
        app = fixers.ProxyFix(app, num_proxies=2)
        environ = dict(create_environ(),
            HTTP_X_FORWARDED_PROTO="https",
            HTTP_X_FORWARDED_HOST='example.com',
            HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8',
            REMOTE_ADDR='127.0.0.1',
            HTTP_HOST='fake'
        )

        response = Response.from_app(app, environ)

        self.assert_equal(response.get_data(), b'1.2.3.4|example.com')

        # And we must check that if it is a redirection it is
        # correctly done:

        redirect_app = redirect('/foo/bar.hml')
        response = Response.from_app(redirect_app, environ)

        wsgi_headers = response.get_wsgi_headers(environ)
        assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml' 
Example #17
Source File: fixers.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_proxy_fix_weird_enum(self):
        @fixers.ProxyFix
        @Request.application
        def app(request):
            return Response(request.remote_addr)
        environ = dict(create_environ(),
            HTTP_X_FORWARDED_FOR=',',
            REMOTE_ADDR='127.0.0.1',
        )

        response = Response.from_app(app, environ)
        self.assert_strict_equal(response.get_data(), b'127.0.0.1') 
Example #18
Source File: config.py    From flasky-first-edition with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

        # log to stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler) 
Example #19
Source File: config.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

        # log to stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler) 
Example #20
Source File: config.py    From nomad with Apache License 2.0 5 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)

        # handle proxy server headers
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

        # log to stderr
        import logging
        from logging import StreamHandler
        stream_handler = StreamHandler()
        stream_handler.setLevel(logging.WARNING)
        app.logger.addHandler(stream_handler) 
Example #21
Source File: config.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #22
Source File: config.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)
        app.wsgi_app = ProxyFix(app.wsgi_app)
        assert os.environ.get('SECRET_KEY'), 'SECRET_KEY IS NOT SET!'

        flask_raygun.Provider(app, app.config['RAYGUN_APIKEY']).attach() 
Example #23
Source File: app.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_app(config='udata.settings.Defaults', override=None,
               init_logging=init_logging):
    '''Factory for a minimal application'''
    app = UDataApp(APP_NAME)
    app.config.from_object(config)

    settings = os.environ.get('UDATA_SETTINGS', join(os.getcwd(), 'udata.cfg'))
    if exists(settings):
        app.settings_file = settings  # Keep track of loaded settings for diagnostic
        app.config.from_pyfile(settings)

    if override:
        app.config.from_object(override)

    # Loads defaults from plugins
    for pkg in entrypoints.get_roots(app):
        if pkg == 'udata':
            continue  # Defaults are already loaded
        module = '{}.settings'.format(pkg)
        try:
            settings = importlib.import_module(module)
        except ImportError:
            continue
        for key, default in settings.__dict__.items():
            if key.startswith('__'):
                continue
            app.config.setdefault(key, default)

    app.json_encoder = UDataJsonEncoder

    app.debug = app.config['DEBUG'] and not app.config['TESTING']

    app.wsgi_app = ProxyFix(app.wsgi_app)

    init_logging(app)
    register_extensions(app)

    return app 
Example #24
Source File: config.py    From dingdian with MIT License 5 votes vote down vote up
def init_app(cls, app):
        Config.init_app(app)

        # 处理代理服务器首部
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #25
Source File: __init__.py    From PyOne with Mozilla Public License 2.0 5 votes vote down vote up
def create_app():
    app = Flask(__name__)
    app.config.from_object(config)
    config.init_app(app)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    cache.init_app(app)
    limiter.init_app(app)

    from .front import front as front_blueprint
    app.register_blueprint(front_blueprint)

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint,url_prefix='/{}'.format(GetConfig('admin_prefix')))

    return app 
Example #26
Source File: config.py    From jbox with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)
        # 打印日志
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler)
        # 处理代理服务器头部
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app) 
Example #27
Source File: config.py    From Simpleblog with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # 处理代理服务器首部
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)
        # 输出到stderr
        import logging
        from logging import StreamHandler
        file_handler = StreamHandler()
        file_handler.setLevel(logging.WARNING)
        app.logger.addHandler(file_handler) 
Example #28
Source File: web.py    From dino with Apache License 2.0 5 votes vote down vote up
def create_app():
    _app = Flask(
            import_name=__name__,
            template_folder='admin/templates/',
            static_folder='admin/static/')

    # used for encrypting cookies for handling sessions
    _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'
    _app.config['ROOT_URL'] = environ.env.config.get(ConfigKeys.ROOT_URL, domain=ConfigKeys.WEB, default='/')

    message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.QUEUE, default=None)
    if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
        raise RuntimeError('no message queue type specified')

    message_queue = 'redis://%s' % environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.CACHE_SERVICE, default='')
    message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')

    logger.info('message_queue: %s' % message_queue)

    _socketio = SocketIO(
            _app,
            logger=logger,
            engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
            async_mode='eventlet',
            message_queue=message_queue,
            channel=message_channel)

    # preferably "emit" should be set during env creation, but the socketio object is not created until after env is
    environ.env.out_of_scope_emit = _socketio.emit

    _app.wsgi_app = ReverseProxied(ProxyFix(_app.wsgi_app))

    return _app, _socketio 
Example #29
Source File: __init__.py    From flask-restplus-server-example with MIT License 4 votes vote down vote up
def create_app(flask_config_name=None, **kwargs):
    """
    Entry point to the Flask RESTful Server application.
    """
    # This is a workaround for Alpine Linux (musl libc) quirk:
    # https://github.com/docker-library/python/issues/211
    import threading
    threading.stack_size(2*1024*1024)

    app = Flask(__name__, **kwargs)

    env_flask_config_name = os.getenv('FLASK_CONFIG')
    if not env_flask_config_name and flask_config_name is None:
        flask_config_name = 'local'
    elif flask_config_name is None:
        flask_config_name = env_flask_config_name
    else:
        if env_flask_config_name:
            assert env_flask_config_name == flask_config_name, (
                "FLASK_CONFIG environment variable (\"%s\") and flask_config_name argument "
                "(\"%s\") are both set and are not the same." % (
                    env_flask_config_name,
                    flask_config_name
                )
            )

    try:
        app.config.from_object(CONFIG_NAME_MAPPER[flask_config_name])
    except ImportError:
        if flask_config_name == 'local':
            app.logger.error(  # pylint: disable=no-member
                "You have to have `local_config.py` or `local_config/__init__.py` in order to use "
                "the default 'local' Flask Config. Alternatively, you may set `FLASK_CONFIG` "
                "environment variable to one of the following options: development, production, "
                "testing."
            )
            sys.exit(1)
        raise

    if app.config['REVERSE_PROXY_SETUP']:
        app.wsgi_app = ProxyFix(app.wsgi_app)

    from . import extensions
    extensions.init_app(app)

    from . import modules
    modules.init_app(app)

    return app 
Example #30
Source File: __init__.py    From Flask-Boost with MIT License 4 votes vote down vote up
def create_app():
    """Create Flask app."""
    config = load_config()

    app = Flask(__name__)
    app.config.from_object(config)

    # Proxy fix
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protect
    CsrfProtect(app)

    if app.debug or app.testing:
        DebugToolbarExtension(app)

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'application/pages')
        })
    else:
        # Log errors to stderr in production mode
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.ERROR)

        # Enable Sentry
        if app.config.get('SENTRY_DSN'):
            from .utils.sentry import sentry

            sentry.init_app(app, dsn=app.config.get('SENTRY_DSN'))

        # Serve static files
        app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
            '/static': os.path.join(app.config.get('PROJECT_PATH'), 'output/static'),
            '/pkg': os.path.join(app.config.get('PROJECT_PATH'), 'output/pkg'),
            '/pages': os.path.join(app.config.get('PROJECT_PATH'), 'output/pages')
        })

    # Register components
    register_db(app)
    register_routes(app)
    register_jinja(app)
    register_error_handle(app)
    register_hooks(app)

    return app