-
-
Notifications
You must be signed in to change notification settings - Fork 864
/
test_authentication.py
344 lines (265 loc) Β· 9.92 KB
/
test_authentication.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
import base64
import binascii
import pytest
from starlette.applications import Starlette
from starlette.authentication import (
AuthCredentials,
AuthenticationBackend,
AuthenticationError,
SimpleUser,
requires,
)
from starlette.endpoints import HTTPEndpoint
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
class BasicAuth(AuthenticationBackend):
async def authenticate(self, request):
if "Authorization" not in request.headers:
return None
auth = request.headers["Authorization"]
try:
scheme, credentials = auth.split()
decoded = base64.b64decode(credentials).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error):
raise AuthenticationError("Invalid basic auth credentials")
username, _, password = decoded.partition(":")
return AuthCredentials(["authenticated"]), SimpleUser(username)
app = Starlette()
app.add_middleware(AuthenticationMiddleware, backend=BasicAuth())
@app.route("/")
def homepage(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.route("/dashboard")
@requires("authenticated")
async def dashboard(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.route("/admin")
@requires("authenticated", redirect="homepage")
async def admin(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.route("/dashboard/sync")
@requires("authenticated")
def dashboard_sync(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.route("/dashboard/class")
class Dashboard(HTTPEndpoint):
@requires("authenticated")
def get(self, request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.route("/admin/sync")
@requires("authenticated", redirect="homepage")
def admin_sync(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
@app.websocket_route("/ws")
@requires("authenticated")
async def websocket_endpoint(websocket):
await websocket.accept()
await websocket.send_json(
{
"authenticated": websocket.user.is_authenticated,
"user": websocket.user.display_name,
}
)
def async_inject_decorator(**kwargs):
def wrapper(endpoint):
async def app(request):
return await endpoint(request=request, **kwargs)
return app
return wrapper
@app.route("/dashboard/decorated")
@async_inject_decorator(additional="payload")
@requires("authenticated")
async def decorated_async(request, additional):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
"additional": additional,
}
)
def sync_inject_decorator(**kwargs):
def wrapper(endpoint):
def app(request):
return endpoint(request=request, **kwargs)
return app
return wrapper
@app.route("/dashboard/decorated/sync")
@sync_inject_decorator(additional="payload")
@requires("authenticated")
def decorated_sync(request, additional):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
"additional": additional,
}
)
def ws_inject_decorator(**kwargs):
def wrapper(endpoint):
def app(websocket):
return endpoint(websocket=websocket, **kwargs)
return app
return wrapper
@app.websocket_route("/ws/decorated")
@ws_inject_decorator(additional="payload")
@requires("authenticated")
async def websocket_endpoint_decorated(websocket, additional):
await websocket.accept()
await websocket.send_json(
{
"authenticated": websocket.user.is_authenticated,
"user": websocket.user.display_name,
"additional": additional,
}
)
def test_invalid_decorator_usage():
with pytest.raises(Exception):
@requires("authenticated")
def foo():
pass # pragma: nocover
def test_user_interface():
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"authenticated": False, "user": ""}
response = client.get("/", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
def test_authentication_required():
with TestClient(app) as client:
response = client.get("/dashboard")
assert response.status_code == 403
response = client.get("/dashboard", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/sync")
assert response.status_code == 403
response = client.get("/dashboard/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/class")
assert response.status_code == 403
response = client.get("/dashboard/class", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/dashboard/decorated", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
response = client.get("/dashboard/decorated")
assert response.status_code == 403
response = client.get(
"/dashboard/decorated/sync", auth=("tomchristie", "example")
)
assert response.status_code == 200
assert response.json() == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
response = client.get("/dashboard/decorated/sync")
assert response.status_code == 403
response = client.get("/dashboard", headers={"Authorization": "basic foobar"})
assert response.status_code == 400
assert response.text == "Invalid basic auth credentials"
def test_websocket_authentication_required():
with TestClient(app) as client:
with pytest.raises(WebSocketDisconnect):
client.websocket_connect("/ws")
with pytest.raises(WebSocketDisconnect):
client.websocket_connect("/ws", headers={"Authorization": "basic foobar"})
with client.websocket_connect(
"/ws", auth=("tomchristie", "example")
) as websocket:
data = websocket.receive_json()
assert data == {"authenticated": True, "user": "tomchristie"}
with pytest.raises(WebSocketDisconnect):
client.websocket_connect("/ws/decorated")
with pytest.raises(WebSocketDisconnect):
client.websocket_connect(
"/ws/decorated", headers={"Authorization": "basic foobar"}
)
with client.websocket_connect(
"/ws/decorated", auth=("tomchristie", "example")
) as websocket:
data = websocket.receive_json()
assert data == {
"authenticated": True,
"user": "tomchristie",
"additional": "payload",
}
def test_authentication_redirect():
with TestClient(app) as client:
response = client.get("/admin")
assert response.status_code == 200
assert response.url == "http://testserver/"
response = client.get("/admin", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get("/admin/sync")
assert response.status_code == 200
assert response.url == "http://testserver/"
response = client.get("/admin/sync", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
def on_auth_error(request: Request, exc: Exception):
return JSONResponse({"error": str(exc)}, status_code=401)
other_app = Starlette()
other_app.add_middleware(
AuthenticationMiddleware, backend=BasicAuth(), on_error=on_auth_error
)
@other_app.route("/control-panel")
@requires("authenticated")
def control_panel(request):
return JSONResponse(
{
"authenticated": request.user.is_authenticated,
"user": request.user.display_name,
}
)
def test_custom_on_error():
with TestClient(other_app) as client:
response = client.get("/control-panel", auth=("tomchristie", "example"))
assert response.status_code == 200
assert response.json() == {"authenticated": True, "user": "tomchristie"}
response = client.get(
"/control-panel", headers={"Authorization": "basic foobar"}
)
assert response.status_code == 401
assert response.json() == {"error": "Invalid basic auth credentials"}