Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for a dynamic origin #282

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions flask_cors/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def get_regexp_pattern(regexp):


def get_cors_origins(options, request_origin):
origins = options.get('origins')
origins = retrieve_origins(options, request_origin)
wildcard = r'.*' in origins

# If the Origin header is not present terminate this set of steps.
Expand Down Expand Up @@ -174,7 +174,8 @@ def get_allow_headers(options, acl_request_headers):


def get_cors_headers(options, request_headers, request_method):
origins_to_set = get_cors_origins(options, request_headers.get('Origin'))
request_origin = request_headers.get('Origin')
origins_to_set = get_cors_origins(options, request_origin)
headers = MultiDict()

if not origins_to_set: # CORS is not enabled for this route
Expand Down Expand Up @@ -211,11 +212,13 @@ def get_cors_headers(options, request_headers, request_method):
# Only set header if the origin returned will vary dynamically,
# i.e. if we are not returning an asterisk, and there are multiple
# origins that can be matched.
origins = retrieve_origins(options, request_origin)

if headers[ACL_ORIGIN] == '*':
pass
elif (len(options.get('origins')) > 1 or
elif (len(origins) > 1 or
len(origins_to_set) > 1 or
any(map(probably_regex, options.get('origins')))):
any(map(probably_regex, origins))):
headers.add('Vary', 'Origin')

return MultiDict((k, v) for k, v in headers.items() if v)
Expand Down Expand Up @@ -350,6 +353,11 @@ def ensure_iterable(inst):
def sanitize_regex_param(param):
return [re_fix(x) for x in ensure_iterable(param)]

def retrieve_origins(options, request_origin):
origins = options.get('origins')
if callable(origins):
origins = sanitize_regex_param(origins(request_origin))
return origins

def serialize_options(opts):
"""
Expand All @@ -362,12 +370,19 @@ def serialize_options(opts):
LOG.warning("Unknown option passed to Flask-CORS: %s", key)

# Ensure origins is a list of allowed origins with at least one entry.
options['origins'] = sanitize_regex_param(options.get('origins'))
origins = options.get('origins')
if not callable(origins):
origins = sanitize_regex_param(origins) # sanitize if not a fn
options['origins'] = origins # keep it as a function in options
options['allow_headers'] = sanitize_regex_param(options.get('allow_headers'))

# This is expressly forbidden by the spec. Raise a value error so people
# don't get burned in production.
if r'.*' in options['origins'] and options['supports_credentials'] and options['send_wildcard']:
if (not callable(origins)
and r'.*' in origins
and options['supports_credentials']
and options['send_wildcard']
):
raise ValueError("Cannot use supports_credentials in conjunction with"
"an origin string of '*'. See: "
"http://www.w3.org/TR/cors/#resource-requests")
Expand Down
20 changes: 20 additions & 0 deletions tests/decorator/test_origins.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@
from flask_cors.core import *

letters = 'abcdefghijklmnopqrstuvwxyz' # string.letters is not PY3 compatible
dynamic_pattern = "dynamic"

def _dynamic_origin(origin):
if dynamic_pattern in origin:
return origin
return ""

class OriginsTestCase(FlaskCorsTestCase):
def setUp(self):
Expand Down Expand Up @@ -81,6 +87,11 @@ def test_regex_mixed_list():
def test_multiple_protocols():
return ''

@self.app.route('/test_dynamic_origin')
@cross_origin(origins=_dynamic_origin)
def test_dynamic_origin():
return ''

def test_defaults_no_origin(self):
''' If there is no Origin header in the request, the
Access-Control-Allow-Origin header should be '*' by default.
Expand Down Expand Up @@ -199,6 +210,15 @@ def test_multiple_protocols(self):
resp = self.get('test_multiple_protocols', origin='https://example.com')
self.assertEqual('https://example.com', resp.headers.get(ACL_ORIGIN))

def test_dynamic_header(self):
''' If the origin contains the variable dynamic_pattern, the
Access-Control-Allow-Origin should be echoed
'''
resp = self.get('/test_dynamic_origin', origin='http://foo.com')
self.assertEqual(resp.headers.get(ACL_ORIGIN), None)
resp = self.get('/test_dynamic_origin', origin='http://foo-dynamic.com')
self.assertEqual(resp.headers.get(ACL_ORIGIN), 'http://foo-dynamic.com')


if __name__ == "__main__":
unittest.main()