forked from simonw/asgi-csrf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_asgi_csrf.py
366 lines (309 loc) · 12.4 KB
/
test_asgi_csrf.py
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
from asgi_lifespan import LifespanManager
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from asgi_csrf import asgi_csrf
from itsdangerous.url_safe import URLSafeSerializer
import httpx
import json
import pytest
SECRET = "secret"
async def hello_world(request):
if "csrftoken" in request.scope and "_no_token" not in request.query_params:
request.scope["csrftoken"]()
if request.method == "POST":
data = await request.form()
data = dict(data)
if "csv" in data:
data["csv"] = (await data["csv"].read()).decode("utf-8")
return JSONResponse(data)
headers = {}
if "_vary" in request.query_params:
headers["Vary"] = request.query_params["_vary"]
return JSONResponse({"hello": "world"}, headers=headers)
async def hello_world_static(request):
return JSONResponse({"hello": "world", "static": True})
hello_world_app = Starlette(
routes=[
Route("/", hello_world, methods=["GET", "POST"]),
Route("/static", hello_world_static, methods=["GET"]),
Route("/api/", hello_world_static, methods=["POST"]),
Route("/api/foo", hello_world_static, methods=["POST"]),
]
)
@pytest.fixture
def app_csrf():
return asgi_csrf(hello_world_app, signing_secret=SECRET)
@pytest.fixture
def csrftoken():
return URLSafeSerializer(SECRET).dumps("token", "csrftoken")
@pytest.mark.asyncio
async def test_hello_world_app():
async with httpx.AsyncClient(app=hello_world_app) as client:
response = await client.get("http://localhost/")
assert b'{"hello":"world"}' == response.content
def test_signing_secret_if_none_provided(monkeypatch):
app = asgi_csrf(hello_world_app)
# Should be randomly generated
assert isinstance(app.__closure__[6].cell_contents.secret_key, bytes)
# Should pick up `ASGI_CSRF_SECRET` if available
monkeypatch.setenv("ASGI_CSRF_SECRET", "secret-from-environment")
app2 = asgi_csrf(hello_world_app)
assert app2.__closure__[6].cell_contents.secret_key == b"secret-from-environment"
@pytest.mark.asyncio
async def test_asgi_csrf_sets_cookie(app_csrf):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.get("http://localhost/")
assert b'{"hello":"world"}' == response.content
assert "csrftoken" in response.cookies
assert response.headers["set-cookie"].endswith("; Path=/")
assert "Cookie" == response.headers["vary"]
@pytest.mark.asyncio
async def test_asgi_csrf_modifies_existing_vary_header(app_csrf):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.get("http://localhost/?_vary=User-Agent")
assert b'{"hello":"world"}' == response.content
assert "csrftoken" in response.cookies
assert response.headers["set-cookie"].endswith("; Path=/")
assert "User-Agent, Cookie" == response.headers["vary"]
@pytest.mark.asyncio
async def test_asgi_csrf_sets_no_cookie_or_vary_if_page_has_no_form(app_csrf):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.get("http://localhost/static")
assert b'{"hello":"world","static":true}' == response.content
assert "csrftoken" not in response.cookies
assert "vary" not in response.headers
@pytest.mark.asyncio
async def test_vary_header_only_if_page_contains_csrftoken(app_csrf, csrftoken):
async with httpx.AsyncClient(app=app_csrf) as client:
assert (
"vary"
in (
await client.get("http://localhost/", cookies={"csrftoken": csrftoken})
).headers
)
assert (
"vary"
not in (
await client.get(
"http://localhost/?_no_token=1", cookies={"csrftoken": csrftoken}
)
).headers
)
@pytest.mark.asyncio
async def test_headers_passed_through_correctly(app_csrf):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.get("http://localhost/static")
assert "application/json" == response.headers["content-type"]
@pytest.mark.asyncio
async def test_asgi_csrf_does_not_set_cookie_if_one_sent(app_csrf, csrftoken):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.get(
"http://localhost/", cookies={"csrftoken": csrftoken}
)
assert b'{"hello":"world"}' == response.content
assert "csrftoken" not in response.cookies
@pytest.mark.asyncio
async def test_prevents_post_if_cookie_not_sent_in_post(app_csrf, csrftoken):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.post(
"http://localhost/", cookies={"csrftoken": csrftoken}
)
assert 403 == response.status_code
@pytest.mark.asyncio
async def test_prevents_post_if_cookie_not_sent_in_post(app_csrf, csrftoken):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.post(
"http://localhost/",
cookies={"csrftoken": csrftoken},
data={"csrftoken": csrftoken[-1]},
)
assert 403 == response.status_code
assert response.text == "form-urlencoded POST field did not match cookie"
@pytest.mark.asyncio
async def test_allows_post_if_cookie_duplicated_in_header(app_csrf, csrftoken):
async with httpx.AsyncClient(app=app_csrf) as client:
response = await client.post(
"http://localhost/",
headers={"x-csrftoken": csrftoken},
cookies={"csrftoken": csrftoken},
)
assert 200 == response.status_code
@pytest.mark.asyncio
async def test_allows_post_if_cookie_duplicated_in_post_data(csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
response = await client.post(
"http://localhost/",
data={"csrftoken": csrftoken, "hello": "world"},
cookies={"csrftoken": csrftoken},
)
assert 200 == response.status_code
assert {"csrftoken": csrftoken, "hello": "world"} == json.loads(response.content)
@pytest.mark.asyncio
async def test_multipart(csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
response = await client.post(
"http://localhost/",
data={"csrftoken": csrftoken},
files={"csv": ("data.csv", "blah,foo\n1,2", "text/csv")},
cookies={"csrftoken": csrftoken},
)
assert response.status_code == 200
assert response.json() == {"csrftoken": csrftoken, "csv": "blah,foo\n1,2"}
@pytest.mark.asyncio
async def test_multipart_failure_wrong_token(csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
response = await client.post(
"http://localhost/",
data={"csrftoken": csrftoken},
files={"csv": ("data.csv", "blah,foo\n1,2", "text/csv")},
cookies={"csrftoken": csrftoken[:-1]},
)
assert response.status_code == 403
assert response.text == "multipart/form-data POST field did not match cookie"
class TrickEmptyDictionary(dict):
# https://github.com/simonw/asgi-csrf/pull/14#issuecomment-674424080
def __bool__(self):
return True
@pytest.mark.asyncio
async def test_multipart_failure_missing_token(csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
response = await client.post(
"http://localhost/",
data={"foo": "bar"},
files=TrickEmptyDictionary(),
cookies={"csrftoken": csrftoken},
)
assert response.status_code == 403
assert response.text == "multipart/form-data POST field did not match cookie"
@pytest.mark.asyncio
async def test_multipart_failure_file_comes_before_token(csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
request = httpx.Request(
url="http://localhost/",
method="POST",
data=(
b"--boo\r\n"
b'Content-Disposition: form-data; name="csv"; filename="data.csv"'
b"\r\nContent-Type: text/csv\r\n\r\n"
b"blah,foo\n1,2"
b"\r\n"
b"--boo\r\n"
b'Content-Disposition: form-data; name="csrftoken"\r\n\r\n'
+ csrftoken.encode("utf-8")
+ b"\r\n"
b"--boo--\r\n"
),
headers={"content-type": "multipart/form-data; boundary=boo"},
cookies={"csrftoken": csrftoken},
)
response = await client.send(request)
assert response.status_code == 403
assert (
response.text
== "File encountered before csrftoken - make sure csrftoken is first in the HTML"
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"authorization,expected_status", [("Bearer xxx", 200), ("Basic xxx", 403)]
)
async def test_post_with_authorization(authorization, expected_status):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET)
) as client:
response = await client.post(
"http://localhost/",
headers={"Authorization": authorization},
cookies={"foo": "bar"},
)
assert expected_status == response.status_code
@pytest.mark.asyncio
@pytest.mark.parametrize(
"cookies,path,expected_status",
[
({}, "/", 200),
({"foo": "bar"}, "/", 403),
({}, "/login", 403),
({"foo": "bar"}, "/login", 403),
],
)
async def test_no_cookies_skips_check_unless_path_required(
cookies, path, expected_status
):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET, always_protect={"/login"})
) as client:
response = await client.post("http://localhost{}".format(path), cookies=cookies)
assert expected_status == response.status_code
@pytest.mark.asyncio
@pytest.mark.parametrize(
"cookies,path,expected_status",
[
({}, "/", 200),
({"foo": "bar"}, "/", 403),
({}, "/api/", 200),
({"foo": "bar"}, "/api/", 200),
({}, "/api/foo", 200),
({"foo": "bar"}, "/api/foo", 200),
],
)
async def test_skip_if_scope(cookies, path, expected_status):
async with httpx.AsyncClient(
app=asgi_csrf(
hello_world_app,
signing_secret=SECRET,
skip_if_scope=lambda scope: scope["path"].startswith("/api/"),
)
) as client:
response = await client.post("http://localhost{}".format(path), cookies=cookies)
assert expected_status == response.status_code
@pytest.mark.asyncio
@pytest.mark.parametrize("always_set_cookie", [True, False])
async def test_always_set_cookie(always_set_cookie):
async with httpx.AsyncClient(
app=asgi_csrf(
hello_world_app, signing_secret=SECRET, always_set_cookie=always_set_cookie
)
) as client:
response = await client.get("http://localhost/static")
assert 200 == response.status_code
if always_set_cookie:
assert "csrftoken" in response.cookies
else:
assert "csrftoken" not in response.cookies
@pytest.mark.asyncio
@pytest.mark.parametrize("send_csrftoken_cookie", [True, False])
async def test_always_set_cookie_unless_cookie_is_set(send_csrftoken_cookie, csrftoken):
async with httpx.AsyncClient(
app=asgi_csrf(hello_world_app, signing_secret=SECRET, always_set_cookie=True)
) as client:
cookies = {}
if send_csrftoken_cookie:
cookies["csrftoken"] = csrftoken
response = await client.get("http://localhost/static", cookies=cookies)
assert 200 == response.status_code
if send_csrftoken_cookie:
assert "csrftoken" not in response.cookies
else:
assert "csrftoken" in response.cookies
@pytest.mark.asyncio
async def test_asgi_lifespan():
app = asgi_csrf(hello_world_app, signing_secret=SECRET)
async with LifespanManager(app):
async with httpx.AsyncClient(app=app) as client:
response = await client.post(
"http://localhost/",
headers={"Authorization": "Bearer xxx"},
cookies={"foo": "bar"},
)
assert 200 == response.status_code