-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasgi_test.py
More file actions
280 lines (222 loc) · 9.63 KB
/
asgi_test.py
File metadata and controls
280 lines (222 loc) · 9.63 KB
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
import unittest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from fastapi.websockets import WebSocket
from unittest.mock import AsyncMock
from unittest.mock import patch
from uuid import uuid4
from mauth_client.authenticator import LocalAuthenticator
from mauth_client.config import Config
from mauth_client.consts import (
AUTH_HEADER_DELIMITER,
X_MWS_AUTH,
MWS_TOKEN,
MCC_AUTH,
MWSV2_TOKEN,
ENV_APP_UUID,
ENV_AUTHENTIC,
ENV_PROTOCOL_VERSION,
)
from mauth_client.middlewares import MAuthASGIMiddleware
class TestMAuthASGIMiddlewareInitialization(unittest.TestCase):
def setUp(self):
self.app = FastAPI()
Config.APP_UUID = str(uuid4())
Config.MAUTH_URL = "https://mauth.com"
Config.MAUTH_API_VERSION = "v1"
Config.PRIVATE_KEY = "key"
def test_app_configuration(self):
try:
self.app.add_middleware(MAuthASGIMiddleware)
self.app.build_middleware_stack()
except TypeError:
self.fail("Shouldn't raise exception")
def test_app_configuration_missing_uuid(self):
Config.APP_UUID = None
with self.assertRaises(TypeError) as exc:
self.app.add_middleware(MAuthASGIMiddleware)
self.app.build_middleware_stack()
self.assertEqual(
str(exc.exception),
"MAuthASGIMiddleware requires APP_UUID and PRIVATE_KEY"
)
def test_app_configuration_missing_key(self):
Config.PRIVATE_KEY = None
with self.assertRaises(TypeError) as exc:
self.app.add_middleware(MAuthASGIMiddleware)
self.app.build_middleware_stack()
self.assertEqual(
str(exc.exception),
"MAuthASGIMiddleware requires APP_UUID and PRIVATE_KEY"
)
def test_app_configuration_missing_url(self):
Config.MAUTH_URL = None
with self.assertRaises(TypeError) as exc:
self.app.add_middleware(MAuthASGIMiddleware)
self.app.build_middleware_stack()
self.assertEqual(
str(exc.exception),
"MAuthASGIMiddleware requires MAUTH_URL and MAUTH_API_VERSION"
)
def test_app_configuration_missing_version(self):
Config.MAUTH_API_VERSION = None
with self.assertRaises(TypeError) as exc:
self.app.add_middleware(MAuthASGIMiddleware)
self.app.build_middleware_stack()
self.assertEqual(
str(exc.exception),
"MAuthASGIMiddleware requires MAUTH_URL and MAUTH_API_VERSION"
)
class TestMAuthASGIMiddlewareFunctionality(unittest.TestCase):
def setUp(self):
self.app_uuid = str(uuid4())
Config.APP_UUID = self.app_uuid
Config.MAUTH_URL = "https://mauth.com"
Config.MAUTH_API_VERSION = "v1"
Config.PRIVATE_KEY = "key"
self.app = FastAPI()
self.app.add_middleware(MAuthASGIMiddleware, exempt={"/app_status"})
@self.app.get("/")
async def root():
return {"msg": "authenticated"}
@self.app.get("/app_status")
async def app_status():
return {"msg": "open"}
self.client = TestClient(self.app)
def test_401_reponse_when_not_authenticated(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 401)
self.assertEqual(response.json(), {
"errors": {
"mauth": [(
"Authentication Failed. No mAuth signature present; "
"X-MWS-Authentication header is blank, "
"MCC-Authentication header is blank."
)]
}
})
def test_ok_when_calling_open_route(self):
response = self.client.get("/app_status")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"msg": "open"})
@patch.object(LocalAuthenticator, "is_authentic")
def test_ok_when_authenticated(self, is_authentic_mock):
is_authentic_mock.return_value = (True, 200, "")
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"msg": "authenticated"})
@patch.object(LocalAuthenticator, "is_authentic")
def test_adds_values_to_context_v1(self, is_authentic_mock):
is_authentic_mock.return_value = (True, 200, "")
headers_v1 = {
X_MWS_AUTH: f"{MWS_TOKEN} {self.app_uuid}:blah"
}
@self.app.get("/v1_test")
def root(request: Request):
self.assertEqual(request.scope[ENV_APP_UUID], self.app_uuid)
self.assertEqual(request.scope[ENV_AUTHENTIC], True)
self.assertEqual(request.scope[ENV_PROTOCOL_VERSION], 1)
return {"msg": "got it"}
self.client.get("/v1_test", headers=headers_v1)
@patch.object(LocalAuthenticator, "is_authentic")
def test_adds_values_to_context_v2(self, is_authentic_mock):
is_authentic_mock.return_value = (True, 200, "")
headers_v2 = {
MCC_AUTH: f"{MWSV2_TOKEN} {self.app_uuid}:blah{AUTH_HEADER_DELIMITER}"
}
@self.app.get("/v2_test")
def root(request: Request):
self.assertEqual(request.scope[ENV_APP_UUID], self.app_uuid)
self.assertEqual(request.scope[ENV_AUTHENTIC], True)
self.assertEqual(request.scope[ENV_PROTOCOL_VERSION], 2)
return {"msg": "got it"}
self.client.get("/v2_test", headers=headers_v2)
@patch.object(LocalAuthenticator, "is_authentic")
def test_downstream_can_receive_body(self, is_authentic_mock):
is_authentic_mock.return_value = (True, 200, "")
expected_body = {"msg": "test"}
@self.app.post("/post_test")
async def post_test(request: Request):
body = await request.json()
self.assertEqual(body, expected_body)
return {"msg": "app can still read the body!"}
self.client.post("/post_test", json=expected_body)
def test_ignores_non_http_requests(self):
@self.app.websocket_route("/ws")
async def ws(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({"msg": "helloes"})
await websocket.close()
with self.client.websocket_connect("/ws") as websocket:
data = websocket.receive_json()
self.assertEqual(data, {"msg": "helloes"})
class TestMAuthASGIMiddlewareInSubApplication(unittest.TestCase):
def setUp(self):
self.app_uuid = str(uuid4())
Config.APP_UUID = self.app_uuid
Config.MAUTH_URL = "https://mauth.com"
Config.MAUTH_API_VERSION = "v1"
Config.PRIVATE_KEY = "key"
self.app = FastAPI()
sub_app = FastAPI()
sub_app.add_middleware(MAuthASGIMiddleware)
@sub_app.get("/path")
async def sub_app_path():
return {"msg": "sub app path"}
self.app.mount("/sub_app", sub_app)
self.client = TestClient(self.app)
@patch.object(LocalAuthenticator, "is_authentic", autospec=True)
def test_includes_base_application_path_in_signature_verification(self, is_authentic_mock):
request_url = None
def is_authentic_effect(self):
nonlocal request_url
request_url = self.signable.attributes_for_signing["request_url"]
return True, 200, ""
is_authentic_mock.side_effect = is_authentic_effect
self.client.get("/sub_app/path")
self.assertEqual(request_url, "/sub_app/path")
class TestMAuthASGIMiddlewareInLongLivedConnections(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.app = FastAPI()
Config.APP_UUID = str(uuid4())
Config.MAUTH_URL = "https://mauth.com"
Config.MAUTH_API_VERSION = "v1"
Config.PRIVATE_KEY = "key"
@patch.object(LocalAuthenticator, "is_authentic")
async def test_fake_receive_delegates_to_original_after_body_consumed(self, is_authentic_mock):
"""Test that after body events are consumed, _fake_receive delegates to original receive"""
is_authentic_mock.return_value = (True, 200, "")
# Track that original receive was called after body events exhausted
call_order = []
async def mock_app(scope, receive, send):
# First receive should get body event
event1 = await receive()
call_order.append(("body", event1["type"]))
# Second receive should delegate to original receive
event2 = await receive()
call_order.append(("disconnect", event2["type"]))
await send({"type": "http.response.start", "status": 200, "headers": []})
await send({"type": "http.response.body", "body": b""})
middleware = MAuthASGIMiddleware(mock_app)
# Mock receive that returns body then disconnect
receive_calls = 0
async def mock_receive():
nonlocal receive_calls
receive_calls += 1
if receive_calls == 1:
return {"type": "http.request", "body": b"test", "more_body": False}
return {"type": "http.disconnect"}
send_mock = AsyncMock()
scope = {
"type": "http",
"method": "POST",
"path": "/test",
"query_string": b"",
"headers": []
}
await middleware(scope, mock_receive, send_mock)
# Verify events were received in correct order
self.assertEqual(len(call_order), 2)
self.assertEqual(call_order[0], ("body", "http.request"))
self.assertEqual(call_order[1], ("disconnect", "http.disconnect"))
self.assertEqual(receive_calls, 2) # Called once for auth, once from app