File: test_middleware.py

package info (click to toggle)
django-cors-headers 4.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 352 kB
  • sloc: python: 925; sh: 14; makefile: 3
file content (467 lines) | stat: -rw-r--r-- 18,381 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
from __future__ import annotations

from http import HTTPStatus

from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.deprecation import MiddlewareMixin

from corsheaders.middleware import (
    ACCESS_CONTROL_ALLOW_CREDENTIALS,
    ACCESS_CONTROL_ALLOW_HEADERS,
    ACCESS_CONTROL_ALLOW_METHODS,
    ACCESS_CONTROL_ALLOW_ORIGIN,
    ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK,
    ACCESS_CONTROL_EXPOSE_HEADERS,
    ACCESS_CONTROL_MAX_AGE,
)
from tests.utils import prepend_middleware, temporary_check_request_handler


class ShortCircuitMiddleware(MiddlewareMixin):
    def process_request(self, request):
        return HttpResponse("short-circuit-middleware-response")


class CorsMiddlewareTests(TestCase):
    def test_get_no_origin(self):
        resp = self.client.get("/")
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    def test_get_origin_vary_by_default(self):
        resp = self.client.get("/")
        assert resp["vary"] == "origin"

    def test_get_invalid_origin(self):
        resp = self.client.get("/", headers={"origin": "https://example.com]"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_get_not_in_allowed_origins(self):
        resp = self.client.get("/", headers={"origin": "https://example.org"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(CORS_ALLOWED_ORIGINS=["http://example.org"])
    def test_get_not_in_allowed_origins_due_to_wrong_scheme(self):
        resp = self.client.get("/", headers={"origin": "https://example.org"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com", "https://example.org"]
    )
    def test_get_in_allowed_origins(self):
        resp = self.client.get("/", headers={"origin": "https://example.org"})
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.org"

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.org"])
    async def test_async_get_in_allowed_origins(self):
        resp = await self.async_client.get("/async/", origin="https://example.org")
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.org"

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com", "null"])
    def test_null_in_allowed_origins(self):
        resp = self.client.get("/", headers={"origin": "null"})
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "null"

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com", "file://"])
    def test_file_in_allowed_origins(self):
        """
        'file://' should be allowed as an origin since Chrome on Android
        mistakenly sends it
        """
        resp = self.client.get("/", headers={"origin": "file://"})
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "file://"

    @override_settings(
        CORS_ALLOW_ALL_ORIGINS=True,
        CORS_EXPOSE_HEADERS=["accept", "content-type"],
    )
    def test_get_expose_headers(self):
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert resp[ACCESS_CONTROL_EXPOSE_HEADERS] == "accept, content-type"

    @override_settings(CORS_ALLOW_ALL_ORIGINS=True)
    def test_get_dont_expose_headers(self):
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_EXPOSE_HEADERS not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_ALLOW_CREDENTIALS=True
    )
    def test_get_allow_credentials(self):
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert resp[ACCESS_CONTROL_ALLOW_CREDENTIALS] == "true"

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_ALLOW_CREDENTIALS=True
    )
    def test_get_allow_credentials_bad_origin(self):
        resp = self.client.get("/", headers={"origin": "https://example.org"})
        assert ACCESS_CONTROL_ALLOW_CREDENTIALS not in resp

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_get_allow_credentials_disabled(self):
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_ALLOW_CREDENTIALS not in resp

    @override_settings(CORS_ALLOW_PRIVATE_NETWORK=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_allow_private_network_added_if_enabled_and_requested(self):
        resp = self.client.get(
            "/",
            headers={
                "access-control-request-private-network": "true",
                "origin": "http://example.com",
            },
        )
        assert resp[ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK] == "true"

    @override_settings(CORS_ALLOW_PRIVATE_NETWORK=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_allow_private_network_not_added_if_enabled_and_not_requested(self):
        resp = self.client.get("/", headers={"origin": "http://example.com"})
        assert ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK not in resp

    @override_settings(
        CORS_ALLOW_PRIVATE_NETWORK=True,
        CORS_ALLOWED_ORIGINS=["http://example.com"],
    )
    def test_allow_private_network_not_added_if_enabled_and_no_cors_origin(self):
        resp = self.client.get(
            "/",
            headers={
                "access-control-request-private-network": "true",
                "origin": "http://example.org",
            },
        )
        assert ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK not in resp

    @override_settings(CORS_ALLOW_PRIVATE_NETWORK=False, CORS_ALLOW_ALL_ORIGINS=True)
    def test_allow_private_network_not_added_if_disabled_and_requested(self):
        resp = self.client.get(
            "/",
            headers={
                "access-control-request-private-network": "true",
                "origin": "http://example.com",
            },
        )
        assert ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK not in resp

    @override_settings(
        CORS_ALLOW_HEADERS=["content-type"],
        CORS_ALLOW_METHODS=["GET", "OPTIONS"],
        CORS_PREFLIGHT_MAX_AGE=1002,
        CORS_ALLOW_ALL_ORIGINS=True,
    )
    def test_options_allowed_origin(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp[ACCESS_CONTROL_ALLOW_HEADERS] == "content-type"
        assert resp[ACCESS_CONTROL_ALLOW_METHODS] == "GET, OPTIONS"
        assert resp[ACCESS_CONTROL_MAX_AGE] == "1002"

    @override_settings(
        CORS_ALLOW_HEADERS=["content-type"],
        CORS_ALLOW_METHODS=["GET", "OPTIONS"],
        CORS_PREFLIGHT_MAX_AGE=1002,
        CORS_ALLOW_ALL_ORIGINS=True,
    )
    async def test_async_options_allowed_origin(self):
        resp = await self.async_client.options(
            "/async/",
            origin="https://example.com",
            access_control_request_method="GET",
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp[ACCESS_CONTROL_ALLOW_HEADERS] == "content-type"
        assert resp[ACCESS_CONTROL_ALLOW_METHODS] == "GET, OPTIONS"
        assert resp[ACCESS_CONTROL_MAX_AGE] == "1002"

    @override_settings(
        CORS_ALLOW_HEADERS=["content-type"],
        CORS_ALLOW_METHODS=["GET", "OPTIONS"],
        CORS_PREFLIGHT_MAX_AGE=0,
        CORS_ALLOW_ALL_ORIGINS=True,
    )
    def test_options_no_max_age(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp[ACCESS_CONTROL_ALLOW_HEADERS] == "content-type"
        assert resp[ACCESS_CONTROL_ALLOW_METHODS] == "GET, OPTIONS"
        assert ACCESS_CONTROL_MAX_AGE not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://localhost:9000"],
    )
    def test_options_allowed_origins_with_port(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://localhost:9000",
                "access-control-request-method": "GET",
            },
        )
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://localhost:9000"

    @override_settings(
        CORS_ALLOWED_ORIGIN_REGEXES=[r"^https://\w+\.example\.com$"],
    )
    def test_options_adds_origin_when_domain_found_in_allowed_regexes(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://foo.example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://foo.example.com"

    @override_settings(
        CORS_ALLOWED_ORIGIN_REGEXES=[
            r"^https://\w+\.example\.org$",
            r"^https://\w+\.example\.com$",
        ],
    )
    def test_options_adds_origin_when_domain_found_in_allowed_regexes_second(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://foo.example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://foo.example.com"

    @override_settings(
        CORS_ALLOWED_ORIGIN_REGEXES=[r"^https://\w+\.example\.org$"],
    )
    def test_options_doesnt_add_origin_when_domain_not_found_in_allowed_regexes(
        self,
    ):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://foo.example.com",
                "access-control-request-method": "GET",
            },
        )
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    def test_options_empty_request_method(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "",
            },
        )
        assert resp.status_code == HTTPStatus.OK

    def test_options_no_headers(self):
        resp = self.client.options("/")
        assert resp.status_code == HTTPStatus.METHOD_NOT_ALLOWED

    @override_settings(CORS_ALLOW_CREDENTIALS=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_allow_all_origins_get(self):
        resp = self.client.get(
            "/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.com"
        assert resp["vary"] == "origin"

    @override_settings(CORS_ALLOW_CREDENTIALS=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_allow_all_origins_options(self):
        resp = self.client.options(
            "/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.com"
        assert resp["vary"] == "origin"

    @override_settings(CORS_ALLOW_CREDENTIALS=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_non_200_headers_still_set(self):
        """
        It's not clear whether the header should still be set for non-HTTP200
        when not a preflight request. However this is the existing behaviour for
        django-cors-middleware, so at least this test makes that explicit, especially
        since for the switch to Django 1.10, special-handling will need to be put in
        place to preserve this behaviour. See `ExceptionMiddleware` mention here:
        https://docs.djangoproject.com/en/3.0/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware  # noqa: E501
        """
        resp = self.client.get(
            "/unauthorized/", headers={"origin": "https://example.com"}
        )
        assert resp.status_code == HTTPStatus.UNAUTHORIZED
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.com"

    @override_settings(CORS_ALLOW_CREDENTIALS=True, CORS_ALLOW_ALL_ORIGINS=True)
    def test_auth_view_options(self):
        """
        Ensure HTTP200 and header still set, for preflight requests to views requiring
        authentication. See: https://github.com/adamchainz/django-cors-headers/issues/3
        """
        resp = self.client.options(
            "/test-401/",
            headers={
                "origin": "https://example.com",
                "access-control-request-method": "GET",
            },
        )
        assert resp.status_code == HTTPStatus.OK
        assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.com"
        assert resp["Content-Length"] == "0"

    def test_signal_handler_that_returns_false(self):
        def handler(*args, **kwargs):
            return False

        with temporary_check_request_handler(handler):
            resp = self.client.options(
                "/",
                headers={
                    "origin": "https://example.com",
                    "access-control-request-method": "GET",
                },
            )

            assert resp.status_code == HTTPStatus.OK
            assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    def test_signal_handler_that_returns_true(self):
        def handler(*args, **kwargs):
            return True

        with temporary_check_request_handler(handler):
            resp = self.client.options(
                "/",
                headers={
                    "origin": "https://example.com",
                    "access-control-request-method": "GET",
                },
            )
            assert resp.status_code == HTTPStatus.OK
            assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.com"

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_signal_handler_allow_some_urls_to_everyone(self):
        def allow_api_to_all(sender, request, **kwargs):
            return request.path.startswith("/api/")

        with temporary_check_request_handler(allow_api_to_all):
            resp = self.client.options(
                "/",
                headers={
                    "origin": "https://example.org",
                    "access-control-request-method": "GET",
                },
            )
            assert resp.status_code == HTTPStatus.OK
            assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

            resp = self.client.options(
                "/api/something/",
                headers={
                    "origin": "https://example.org",
                    "access-control-request-method": "GET",
                },
            )
            assert resp.status_code == HTTPStatus.OK
            assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == "https://example.org"

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_signal_called_once_during_normal_flow(self):
        calls = 0

        def allow_all(sender, request, **kwargs):
            nonlocal calls
            calls += 1
            return True

        with temporary_check_request_handler(allow_all):
            self.client.get("/", headers={"origin": "https://example.org"})

            assert calls == 1

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    @prepend_middleware(f"{__name__}.ShortCircuitMiddleware")
    def test_get_short_circuit(self):
        """
        Test a scenario when a middleware that returns a response is run before
        the ``CorsMiddleware``. In this case
        ``CorsMiddleware.process_response()`` should ignore the request if
        MIDDLEWARE setting is used (new mechanism in Django 1.10+).
        """
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_URLS_REGEX=r"^/foo/$"
    )
    @prepend_middleware(f"{__name__}.ShortCircuitMiddleware")
    def test_get_short_circuit_should_be_ignored(self):
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_URLS_REGEX=r"^/foo/$"
    )
    def test_get_regex_matches(self):
        resp = self.client.get("/foo/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_URLS_REGEX=r"^/not-foo/$"
    )
    def test_get_regex_doesnt_match(self):
        resp = self.client.get("/foo/", headers={"origin": "https://example.com"})
        assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp

    @override_settings(
        CORS_ALLOWED_ORIGINS=["https://example.com"], CORS_URLS_REGEX=r"^/foo/$"
    )
    def test_get_regex_matches_path_info(self):
        resp = self.client.get(
            "/foo/", headers={"origin": "https://example.com"}, SCRIPT_NAME="/prefix/"
        )
        assert ACCESS_CONTROL_ALLOW_ORIGIN in resp

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_cors_enabled_is_attached_and_bool(self):
        """
        Ensure that request._cors_enabled is available - although a private API
        someone might use it for debugging
        """
        resp = self.client.get("/", headers={"origin": "https://example.com"})
        request = resp.wsgi_request
        assert isinstance(request._cors_enabled, bool)  # type: ignore [attr-defined]
        assert request._cors_enabled  # type: ignore [attr-defined]

    @override_settings(CORS_ALLOWED_ORIGINS=["https://example.com"])
    def test_works_if_view_deletes_cors_enabled(self):
        """
        Just in case something crazy happens in the view or other middleware,
        check that get_response doesn't fall over if `_cors_enabled` is removed
        """
        resp = self.client.get(
            "/delete-enabled/", headers={"origin": "https://example.com"}
        )
        assert ACCESS_CONTROL_ALLOW_ORIGIN in resp