def test_cors(): app = WsgiApp(MusicServiceImpl(), allowed_origins=frozenset(['example.com'])) client = Client(app, Response) def split(header, lower=False): vs = map(str.strip, header.split(',')) if lower: vs = map(str.lower, vs) return frozenset(vs) resp = client.options('/?method=get_music_by_artist_name', headers={ 'Origin': 'https://example.com', 'Access-Control-Request-Method': 'POST', }) assert resp.status_code == 200 assert resp.headers['Access-Control-Allow-Origin'] == 'https://example.com' assert split(resp.headers['Access-Control-Allow-Methods']) == { 'POST', 'OPTIONS', } assert 'origin' in split(resp.headers['Vary'], lower=True) resp2 = client.post('/?method=get_music_by_artist_name', headers={ 'Origin': 'https://example.com', 'Access-Control-Request-Method': 'POST', 'Content-Type': 'application/json', }, data=json.dumps({'artist_name': 'damien'})) assert resp2.status_code == 200, resp2.get_data(as_text=True) assert resp2.headers['Access-Control-Allow-Origin'] == \ 'https://example.com' assert {'POST', 'OPTIONS'} == split(resp2.headers['Access-Control-Allow-Methods']) assert 'origin' in split(resp2.headers['Vary'], lower=True) resp3 = client.options('/?method=get_music_by_artist_name', headers={ 'Origin': 'https://disallowed.com', 'Access-Control-Request-Method': 'POST', }) assert resp3.status_code == 200 allow_origin = resp3.headers.get('Access-Control-Allow-Origin', '') assert 'disallowed.com' not in allow_origin
def test_cors_http_resouce(origin, disallowed_origin_host, url, allow_methods, request_method): app = WsgiApp(CorsVerbServiceImpl(), allowed_origins=frozenset([ 'example.com', '*.prefix.example.com', 'infix.*.example.com', ])) assert app.allows_origin(origin) assert not app.allows_origin(u'http://' + disallowed_origin_host) assert not app.allows_origin(u'https://' + disallowed_origin_host) client = Client(app, Response) resp = client.options(url, headers={ 'Origin': origin, 'Access-Control-Request-Method': request_method, }) assert resp.status_code == 200 assert resp.headers['Access-Control-Allow-Origin'] == origin assert split(resp.headers['Access-Control-Allow-Methods']) == allow_methods assert u'origin' in split(resp.headers['Vary'], lower=True) resp2 = getattr(client, request_method.lower())( url, headers={ 'Origin': origin, 'Access-Control-Request-Method': request_method, 'Content-Type': u'application/json', }, ) assert resp2.status_code == 200, resp2.get_data(as_text=True) assert resp2.headers['Access-Control-Allow-Origin'] == origin assert allow_methods == split( resp2.headers['Access-Control-Allow-Methods']) assert 'origin' in split(resp2.headers['Vary'], lower=True) resp3 = client.options(url, headers={ 'Origin': u'https://' + disallowed_origin_host, 'Access-Control-Request-Method': request_method, }) assert resp3.status_code == 200 allow_origin = resp3.headers.get('Access-Control-Allow-Origin', u'') assert disallowed_origin_host not in allow_origin