Debian Codegraph @

tests/test_csrf.py

raw symbols SCIP
1 import re
2
3 from django.conf import settings
4 from django.http import JsonResponse
5 from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
6
7 from ninja import NinjaAPI
8 from ninja.security import APIKeyCookie, APIKeyHeader, django_auth
9 from ninja.testing import TestClient as BaseTestClient
10
11
12 class AnyCookieAuth(APIKeyCookie):
13 """A mock authentication class that accepts any cookie value.
14 To test CSRF functionality without specific authentication logic.
15 """
16
17 def authenticate(self, request, key):
18 return True
19
20
21 class TestClient(BaseTestClient):
22 """
23 A mock authentication class that accepts any cookie value.
24 To test CSRF functionality without specific authentication logic.
25 """
26
27 def _build_request(self, *args, **kwargs):
28 request = super()._build_request(*args, **kwargs)
29 request._dont_enforce_csrf_checks = False
30 return request
31
32
33 csrf_OFF = NinjaAPI(urls_namespace="csrf_OFF")
34 csrf_ON = NinjaAPI(urls_namespace="csrf_ON", auth=AnyCookieAuth()) # , csrf=True
35 csrf_ON_with_django_auth = NinjaAPI(urls_namespace="csrf_ON_django", auth=django_auth)
36
37
38 @csrf_OFF.post("/post")
39 def post_off(request):
40 return {"success": True}
41
42
43 @csrf_ON.post("/post")
44 def post_on(request):
45 return {"success": True}
46
47
48 @csrf_ON.post("/post/csrf_exempt")
49 @csrf_exempt
50 def post_on_with_exempt(request):
51 return {"success": True}
52
53
54 # Operations for test_csrf_cookies_can_be_obtained - defined at module level
55 # to avoid frozen router issues
56 @csrf_ON.get("/obtain_csrf_token_get")
57 @ensure_csrf_cookie
58 def obtain_csrf_token_get(request):
59 return JsonResponse(data={"success": True})
60
61
62 @csrf_ON.post("/obtain_csrf_token_post")
63 @ensure_csrf_cookie
64 @csrf_exempt
65 def obtain_csrf_token_post(request):
66 return JsonResponse(data={"success": True})
67
68
69 @csrf_ON_with_django_auth.get("/obtain_csrf_token_get", auth=None)
70 @ensure_csrf_cookie
71 def obtain_csrf_token_get_no_auth_route(request):
72 return JsonResponse(data={"success": True})
73
74
75 @csrf_ON_with_django_auth.post("/obtain_csrf_token_post", auth=None)
76 @ensure_csrf_cookie
77 @csrf_exempt
78 def obtain_csrf_token_post_no_auth_route(request):
79 return JsonResponse(data={"success": True})
80
81
82 TOKEN = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD"
83 COOKIES = {settings.CSRF_COOKIE_NAME: TOKEN}
84
85
86 def test_csrf_off():
87 client = TestClient(csrf_OFF)
88 assert client.post("/post", COOKIES=COOKIES).status_code == 200
89
90
91 def test_csrf_on():
92 client = TestClient(csrf_ON)
93
94 assert client.post("/post", COOKIES=COOKIES).status_code == 403
95
96 # check with token in formdata
97 response = client.post("/post", {"csrfmiddlewaretoken": TOKEN}, COOKIES=COOKIES)
98 assert response.status_code == 200
99
100 # check with headers
101 response = client.post("/post", COOKIES=COOKIES, headers={"X-CSRFTOKEN": TOKEN})
102 assert response.status_code == 200
103
104 # exempt check
105 assert client.post("/post/csrf_exempt", COOKIES=COOKIES).status_code == 200
106
107
108 def test_csrf_cookie_auth():
109 "Cookie based authtentication should have csrf check by default"
110
111 class CookieAuth(APIKeyCookie):
112 def authenticate(self, request, key):
113 return key == "test"
114
115 cookie_auth = CookieAuth()
116 api = NinjaAPI(auth=cookie_auth)
117
118 @api.post("/test")
119 def test_view(request):
120 return {"success": True}
121
122 client = TestClient(api)
123
124 # No auth - access denied
125 assert client.post("/test").status_code == 403
126
127 # Cookie auth + valid csrf
128 cookies = {"key": "test"}
129 cookies.update(COOKIES)
130 response = client.post("/test", COOKIES=cookies, headers={"X-CSRFTOKEN": TOKEN})
131 assert response.status_code == 200, response.content
132
133 # Cookie auth + INVALID csrf
134 response = client.post(
135 "/test", COOKIES=cookies, headers={"X-CSRFTOKEN": TOKEN + "invalid"}
136 )
137 assert response.status_code == 403, response.content
138
139 # Turning off csrf on cookie, valid key, no csrf passed
140 cookie_auth.csrf = False
141 response = client.post("/test", COOKIES={"key": "test"})
142 assert response.status_code == 200, response.content
143
144
145 def test_csrf_cookies_can_be_obtained():
146 # Operations are defined at module level to avoid frozen router issues
147 client = TestClient(csrf_ON)
148 # can get csrf cookie through get
149 response = client.get("/obtain_csrf_token_get")
150 assert response.status_code == 200
151 assert len(response.cookies["csrftoken"].value) > 0
152 # can get csrf cookie through exempted post
153 response = client.post("/obtain_csrf_token_post")
154 assert response.status_code == 200
155 assert len(response.cookies["csrftoken"].value) > 0
156 # Now testing a route with disabled auth from a client with django_auth set globally also works
157 client = TestClient(csrf_ON_with_django_auth)
158 # can get csrf cookie through get on route with disabled auth
159 response = client.get("/obtain_csrf_token_get")
160 assert response.status_code == 200
161 assert len(response.cookies["csrftoken"].value) > 0
162 # can get csrf cookie through exempted post on route with disabled auth
163 response = client.post("/obtain_csrf_token_post")
164 assert response.status_code == 200
165 assert len(response.cookies["csrftoken"].value) > 0
166
167
168 def test_docs():
169 "Testing that docs are initializing csrf headers correctly"
170
171 api = NinjaAPI(auth=AnyCookieAuth())
172
173 client = TestClient(api)
174 resp = client.get("/docs")
175 assert resp.status_code == 200
176 csrf_token = re.findall(r'data-csrf-token="(.*?)"', resp.content.decode("utf8"))[0]
177 assert len(csrf_token) > 0
178
179
180 def test_no_auth_csrf_exempt():
181 """Test that APIs without authentication are CSRF exempt by default"""
182 from django.middleware.csrf import CsrfViewMiddleware
183 from django.test import RequestFactory
184
185 api = NinjaAPI(urls_namespace="test_no_auth_csrf")
186
187 @api.post("/create")
188 def create_item(request):
189 return {"status": "created"}
190
191 # Get the actual view function that Django will use
192 patterns = api.urls[0]
193 view_func = None
194 for pattern in patterns:
195 if hasattr(pattern, "callback") and "create" in str(pattern.pattern):
196 view_func = pattern.callback
197 break
198
199 assert view_func is not None, "Could not find view function"
200
201 # Test 1: Check if view has csrf_exempt attribute
202 has_csrf_exempt = hasattr(view_func, "csrf_exempt")
203 csrf_exempt_value = getattr(view_func, "csrf_exempt", None)
204 print(f"View has csrf_exempt: {has_csrf_exempt}, value: {csrf_exempt_value}")
205
206 # Test 2: Simulate Django's CSRF middleware check
207 factory = RequestFactory()
208 request = factory.post("/create", data="{}", content_type="application/json")
209
210 csrf_middleware = CsrfViewMiddleware(lambda r: None)
211 csrf_middleware.process_request(request)
212 csrf_response = csrf_middleware.process_view(request, view_func, (), {})
213
214 # If csrf_response is None, the request passed CSRF checks
215 # If it's not None, it's a 403 Forbidden response
216 assert (
217 csrf_response is None
218 ), f"CSRF middleware blocked the request! Regular APIs should be CSRF exempt. Response: {csrf_response}"
219
220
221 def test_docs_cookie_auth():
222 class CookieAuth(APIKeyCookie):
223 def authenticate(self, request, key):
224 return key == "test"
225
226 class HeaderAuth(APIKeyHeader):
227 def authenticate(self, request, key):
228 return key == "test"
229
230 api = NinjaAPI(auth=CookieAuth())
231 client = TestClient(api)
232 resp = client.get("/docs")
233 csrf_token = re.findall(r'data-csrf-token="(.*?)"', resp.content.decode("utf8"))[0]
234 assert len(csrf_token) > 0
235
236 api = NinjaAPI(auth=HeaderAuth())
237 client = TestClient(api)
238 resp = client.get("/docs")
239 csrf_token = re.findall(r'data-csrf-token="(.*?)"', resp.content.decode("utf8"))[0]
240 assert len(csrf_token) == 0