File: test_cors_middleware.py

package info (click to toggle)
python-falcon 4.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,172 kB
  • sloc: python: 33,608; javascript: 92; sh: 50; makefile: 50
file content (295 lines) | stat: -rw-r--r-- 12,372 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
from pathlib import Path

import pytest

import falcon
from falcon import testing


@pytest.fixture
def client(asgi, util):
    app = util.create_app(asgi)
    return testing.TestClient(app)


@pytest.fixture(scope='function')
def cors_client(asgi, util):
    # NOTE(kgriffs): Disable wrapping to test that built-in middleware does
    #   not require it (since this will be the case for non-test apps).
    with util.disable_asgi_non_coroutine_wrapping():
        app = util.create_app(asgi, cors_enable=True)
    return testing.TestClient(app)


class CORSHeaderResource:
    def on_get(self, req, resp):
        resp.text = "I'm a CORS test response"

    def on_delete(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', 'example.com')
        resp.text = "I'm a CORS test response"


class CORSOptionsResource:
    def on_options(self, req, resp):
        # No allow header set
        resp.set_header('Content-Length', '0')


class TestCorsMiddleware:
    def test_disabled_cors_should_not_add_any_extra_headers(self, client):
        client.app.add_route('/', CORSHeaderResource())
        result = client.simulate_get(headers={'Origin': 'localhost'})
        h = dict(result.headers.lower_items()).keys()
        assert 'Access-Control-Allow-Origin'.lower() not in h
        assert 'Access-Control-Allow-Credentials'.lower() not in h
        assert 'Access-Control-Expose-Headers'.lower() not in h

    def test_enabled_cors_no_origin(self, client):
        client.app.add_route('/', CORSHeaderResource())
        result = client.simulate_get()
        h = dict(result.headers.lower_items()).keys()
        assert 'Access-Control-Allow-Origin'.lower() not in h
        assert 'Access-Control-Allow-Credentials'.lower() not in h
        assert 'Access-Control-Expose-Headers'.lower() not in h

    def test_enabled_cors_should_add_extra_headers_on_response(self, cors_client):
        cors_client.app.add_route('/', CORSHeaderResource())
        result = cors_client.simulate_get(headers={'Origin': 'localhost'})
        assert (
            'Access-Control-Allow-Origin'.lower()
            in dict(result.headers.lower_items()).keys()
        )

    def test_enabled_cors_should_accept_all_origins_requests(self, cors_client):
        cors_client.app.add_route('/', CORSHeaderResource())

        result = cors_client.simulate_get(headers={'Origin': 'localhost'})
        assert result.headers['Access-Control-Allow-Origin'] == '*'

        result = cors_client.simulate_delete(headers={'Origin': 'localhost'})
        assert result.headers['Access-Control-Allow-Origin'] == 'example.com'

    def test_enabled_cors_handles_preflighting(self, cors_client):
        cors_client.app.add_route('/', CORSHeaderResource())
        result = cors_client.simulate_options(
            headers=(
                ('Origin', 'localhost'),
                ('Access-Control-Request-Method', 'GET'),
                ('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type'),
            )
        )
        assert result.headers['Access-Control-Allow-Methods'] == 'DELETE, GET'
        assert (
            result.headers['Access-Control-Allow-Headers']
            == 'X-PINGOTHER, Content-Type'
        )
        assert (
            result.headers['Access-Control-Max-Age'] == '86400'
        )  # 24 hours in seconds

    def test_enabled_cors_handles_preflight_custom_option(self, cors_client):
        cors_client.app.add_route('/', CORSOptionsResource())
        result = cors_client.simulate_options(
            headers=(
                ('Origin', 'localhost'),
                ('Access-Control-Request-Method', 'GET'),
                ('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type'),
            )
        )
        assert 'Access-Control-Allow-Methods' not in result.headers
        assert 'Access-Control-Allow-Headers' not in result.headers
        assert 'Access-Control-Max-Age' not in result.headers
        assert 'Access-Control-Expose-Headers' not in result.headers
        assert 'Access-Control-Allow-Origin' not in result.headers

    def test_enabled_cors_handles_preflighting_no_headers_in_req(self, cors_client):
        cors_client.app.add_route('/', CORSHeaderResource())
        result = cors_client.simulate_options(
            headers=(
                ('Origin', 'localhost'),
                ('Access-Control-Request-Method', 'POST'),
            )
        )
        assert result.headers['Access-Control-Allow-Methods'] == 'DELETE, GET'
        assert result.headers['Access-Control-Allow-Headers'] == '*'
        assert (
            result.headers['Access-Control-Max-Age'] == '86400'
        )  # 24 hours in seconds

    def test_enabled_cors_static_route(self, cors_client):
        cors_client.app.add_static_route('/static', Path(__file__).parent)
        result = cors_client.simulate_options(
            f'/static/{Path(__file__).name}',
            headers=(
                ('Origin', 'localhost'),
                ('Access-Control-Request-Method', 'GET'),
            ),
        )

        assert result.headers['Access-Control-Allow-Methods'] == 'GET'
        assert result.headers['Access-Control-Allow-Headers'] == '*'
        assert result.headers['Access-Control-Max-Age'] == '86400'
        assert result.headers['Access-Control-Allow-Origin'] == '*'

    @pytest.mark.parametrize('support_options', [True, False])
    def test_enabled_cors_sink_route(self, cors_client, support_options):
        def my_sink(req, resp):
            if req.method == 'OPTIONS' and support_options:
                resp.set_header('ALLOW', 'GET')
            else:
                resp.text = 'my sink'

        cors_client.app.add_sink(my_sink, '/sink')
        result = cors_client.simulate_options(
            '/sink/123',
            headers=(
                ('Origin', 'localhost'),
                ('Access-Control-Request-Method', 'GET'),
            ),
        )

        if support_options:
            assert result.headers['Access-Control-Allow-Methods'] == 'GET'
            assert result.headers['Access-Control-Allow-Headers'] == '*'
            assert result.headers['Access-Control-Max-Age'] == '86400'
            assert result.headers['Access-Control-Allow-Origin'] == '*'
        else:
            assert 'Access-Control-Allow-Methods' not in result.headers
            assert 'Access-Control-Allow-Headers' not in result.headers
            assert 'Access-Control-Max-Age' not in result.headers
            assert 'Access-Control-Expose-Headers' not in result.headers
            assert 'Access-Control-Allow-Origin' not in result.headers


@pytest.fixture(scope='function')
def make_cors_client(asgi, util):
    def make(middleware):
        app = util.create_app(asgi, middleware=middleware)
        return testing.TestClient(app)

    return make


class TestCustomCorsMiddleware:
    def test_raises(self):
        with pytest.raises(ValueError, match='passed to allow_origins'):
            falcon.CORSMiddleware(allow_origins=['*'])
        with pytest.raises(ValueError, match='passed to allow_credentials'):
            falcon.CORSMiddleware(allow_credentials=['*'])

    @pytest.mark.parametrize(
        'allow, fail_origins, success_origins',
        (
            ('*', [None], ['foo', 'bar']),
            ('test', ['other', 'Test', 'TEST'], ['test']),
            (
                ['foo', 'bar'],
                ['foo, bar', 'foobar', 'foo,bar', 'Foo', 'BAR'],
                ['foo', 'bar'],
            ),
        ),
    )
    def test_allow_origin(self, make_cors_client, allow, fail_origins, success_origins):
        client = make_cors_client(falcon.CORSMiddleware(allow_origins=allow))
        client.app.add_route('/', CORSHeaderResource())

        for origin in fail_origins:
            h = {'Origin': origin} if origin is not None else {}
            res = client.simulate_get(headers=h)
            h = dict(res.headers.lower_items()).keys()
            assert 'Access-Control-Allow-Origin'.lower() not in h
            assert 'Access-Control-Allow-Credentials'.lower() not in h
            assert 'Access-Control-Expose-Headers'.lower() not in h

        for origin in success_origins:
            res = client.simulate_get(headers={'Origin': origin})
            assert (
                res.headers['Access-Control-Allow-Origin'] == '*'
                if allow == '*'
                else origin
            )
            h = dict(res.headers.lower_items()).keys()
            assert 'Access-Control-Allow-Credentials'.lower() not in h
            assert 'Access-Control-Expose-Headers'.lower() not in h

    def test_allow_credential_wildcard(self, make_cors_client):
        client = make_cors_client(falcon.CORSMiddleware(allow_credentials='*'))
        client.app.add_route('/', CORSHeaderResource())

        res = client.simulate_get(headers={'Origin': 'localhost'})
        assert res.headers['Access-Control-Allow-Origin'] == 'localhost'
        assert res.headers['Access-Control-Allow-Credentials'] == 'true'

    @pytest.mark.parametrize(
        'allow, successOrigin',
        (
            (['foo', 'bar'], ['foo', 'bar']),
            ('foo', ['foo']),
        ),
    )
    def test_allow_credential_list_or_str(self, make_cors_client, allow, successOrigin):
        client = make_cors_client(falcon.CORSMiddleware(allow_credentials=allow))
        client.app.add_route('/', CORSHeaderResource())

        for origin in ('foo, bar', 'foobar', 'foo,bar', 'Foo', 'BAR'):
            res = client.simulate_get(headers={'Origin': origin})
            assert res.headers['Access-Control-Allow-Origin'] == '*'
            h = dict(res.headers.lower_items()).keys()
            assert 'Access-Control-Allow-Credentials'.lower() not in h
            assert 'Access-Control-Expose-Headers'.lower() not in h

        for origin in successOrigin:
            res = client.simulate_get(headers={'Origin': origin})
            assert res.headers['Access-Control-Allow-Origin'] == origin
            assert res.headers['Access-Control-Allow-Credentials'] == 'true'
            h = dict(res.headers.lower_items()).keys()
            assert 'Access-Control-Expose-Headers'.lower() not in h

    def test_allow_credential_existing_origin(self, make_cors_client):
        client = make_cors_client(falcon.CORSMiddleware(allow_credentials='*'))
        client.app.add_route('/', CORSHeaderResource())

        res = client.simulate_delete(headers={'Origin': 'something'})
        assert res.headers['Access-Control-Allow-Origin'] == 'example.com'
        h = dict(res.headers.lower_items()).keys()
        assert 'Access-Control-Allow-Credentials'.lower() not in h

    def test_allow_origin_allow_credential(self, make_cors_client):
        client = make_cors_client(
            falcon.CORSMiddleware(allow_origins='test', allow_credentials='*')
        )
        client.app.add_route('/', CORSHeaderResource())

        for origin in ['foo', 'TEST']:
            res = client.simulate_get(headers={'Origin': origin})
            h = dict(res.headers.lower_items()).keys()
            assert 'Access-Control-Allow-Origin'.lower() not in h
            assert 'Access-Control-Allow-Credentials'.lower() not in h
            assert 'Access-Control-Expose-Headers'.lower() not in h

        res = client.simulate_get(headers={'Origin': 'test'})
        assert res.headers['Access-Control-Allow-Origin'] == 'test'
        assert res.headers['Access-Control-Allow-Credentials'] == 'true'
        h = dict(res.headers.lower_items()).keys()
        assert 'Access-Control-Expose-Headers'.lower() not in h

    @pytest.mark.parametrize(
        'attr, exp',
        (
            ('foo', 'foo'),
            ('foo, bar', 'foo, bar'),
            (['foo', 'bar'], 'foo, bar'),
        ),
    )
    def test_expose_headers(self, make_cors_client, attr, exp):
        client = make_cors_client(
            falcon.CORSMiddleware(expose_headers=attr, allow_credentials=None)
        )
        client.app.add_route('/', CORSHeaderResource())

        res = client.simulate_get(headers={'Origin': 'something'})
        assert res.headers['Access-Control-Allow-Origin'] == '*'
        assert res.headers['Access-Control-Expose-Headers'] == exp
        h = dict(res.headers.lower_items()).keys()
        assert 'Access-Control-Allow-Credentials'.lower() not in h