-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_asgi_gssapi.py
308 lines (260 loc) · 11.2 KB
/
test_asgi_gssapi.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
import base64
import pytest
import mock
from asgi_gssapi import SPNEGOAuthMiddleware
from async_asgi_testclient import TestClient
async def index(scope, receive, send):
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [
[b"content-type", b"text/plain"],
],
}
)
await send(
{
"type": "http.response.body",
"body": ("Hello {}".format(scope["gssapi"].get("principal") or "ANONYMOUS")).encode(),
}
)
def quick_error(code: int, content: bytes, content_type: bytes, www_auth_header: bool = False):
return (
{
"type": "http.response.start",
"status": code,
"headers": [
[b"content-type", content_type],
[b"content-length", str(len(content)).encode()],
*([[b"www-authenticate", b"negotiate"]] if www_auth_header else []),
],
},
{
"type": "http.response.body",
"body": content,
},
)
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@mock.patch("asgi_gssapi.SPNEGOAuthMiddleware._gssapi_authenticate")
@pytest.mark.asyncio
async def test_authentication_missing_but_not_required(do_auth):
"""
Ensure that when a user's auth_required_callback returns False,
and the request is missing an auth token,
authentication is not performed.
"""
false = lambda x: False
async with TestClient(SPNEGOAuthMiddleware(index, service="http", auth_required_callback=false)) as app:
r = await app.get("/")
assert r.status_code == 200
assert r.content == b"Hello ANONYMOUS"
assert r.headers.get("WWW-Authenticate") == None
assert do_auth.mock_calls == []
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@mock.patch("gssapi.SecurityContext.initiator_name", "[email protected]")
@mock.patch("gssapi.SecurityContext.complete", False)
@mock.patch("gssapi.SecurityContext.step")
@mock.patch("base64.b64decode")
@pytest.mark.asyncio
async def test_authentication_invalid_but_not_required(decode, step):
"""
Ensure that when a user's auth_required_callback returns False,
and the request includes an invalid auth token,
the invalid auth is ignored and the request
is allowed through to the app.
"""
decode.return_value = "CTOKEN"
false = lambda x: False
async with TestClient(
SPNEGOAuthMiddleware(
index,
service="http",
# hostname='example.org',
auth_required_callback=false,
)
) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 200
assert r.content == b"Hello ANONYMOUS"
assert r.headers.get("WWW-Authenticate", None) == None
assert step.mock_calls != [] # We tried
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@mock.patch("gssapi.SecurityContext.initiator_name", "[email protected]")
@mock.patch("gssapi.SecurityContext.complete", True)
@mock.patch("gssapi.SecurityContext.step")
@mock.patch("base64.b64decode")
@pytest.mark.asyncio
async def test_authentication_valid_but_not_required(decode, step):
"""
Ensure that when a users auth_required_callback returns False,
but the request does include a valid auth token,
the authenticated user is passed through to the app.
"""
decode.return_value = "CTOKEN"
step.return_value = b"STOKEN"
async def false(scope):
return False
async with TestClient(
SPNEGOAuthMiddleware(
index,
service="http",
# hostname='example.org',
auth_required_callback=false,
)
) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 200
assert r.content == b"Hello [email protected]"
assert r.headers["WWW-Authenticate"] == "Negotiate {}".format(base64.b64encode(b"STOKEN").decode())
assert step.mock_calls != [] # We tried
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_unauthorized():
"""
Ensure that when the client does not send an authorization token, they
receive a 401 Unauthorized response which includes a www-authenticate
header field which indicates the server supports Negotiate
authentication.
"""
async with TestClient(SPNEGOAuthMiddleware(index, service="http")) as app:
r = await app.get("/")
assert r.status_code == 401
assert r.content == b"Unauthorized"
assert r.headers["www-authenticate"] == "Negotiate"
assert r.headers["content-type"] == "text/plain"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_unauthorized_when_missing_negotiate():
"""
Ensure that when the client sends an Authorization header that does
not start with "Negotiate ", they receive a 401 Unauthorized response
with a "WWW-Authenticate: Negotiate" header.
"""
async with TestClient(SPNEGOAuthMiddleware(index, service="http")) as app:
r = await app.get("/", headers={"Authorization": "foo"})
assert r.status_code == 401
print(r.content, type(r.content))
assert r.content.startswith(b"Unauthorized")
assert r.headers["www-authenticate"] == "Negotiate"
assert r.headers["content-type"] == "text/plain"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_unauthorized_custom():
"""
Ensure that when the client does not send an authorization token, they
receive a 401 Unauthorized response which includes a www-authenticate
header field which indicates the server supports Negotiate
authentication. If configured, they should also receive customized
content.
"""
async with TestClient(SPNEGOAuthMiddleware(index, service="http", unauthorized="CUSTOM")) as app:
r = await app.get("/")
assert r.status_code == 401
assert r.content == b"CUSTOM"
assert r.headers["www-authenticate"] == "Negotiate"
assert r.headers["content-type"] == "text/plain"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_unauthorized_custom_content_type():
"""
Ensure that when the client does not send an authorization token, they
receive a 401 Unauthorized response which includes a www-authenticate
header field which indicates the server supports Negotiate
authentication. If configured, they should also receive customized
content and content type.
"""
async with TestClient(
SPNEGOAuthMiddleware(index, service="http", unauthorized=quick_error(401, b"401!", b"text/html", True))
) as app:
r = await app.get("/")
assert r.status_code == 401
assert r.content == b"401!"
assert r.headers["www-authenticate"].lower() == "negotiate"
assert r.headers["content-type"] == "text/html"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@mock.patch("gssapi.SecurityContext.initiator_name", "[email protected]")
@mock.patch("gssapi.SecurityContext.complete", True)
@mock.patch("gssapi.SecurityContext.step")
@mock.patch("base64.b64decode")
@pytest.mark.asyncio
async def test_authorized(decode, step): # self):#, clean, name, response, step, init):
"""
Ensure that when the client sends a correct authorization token,
they receive a 200 OK response and the user principal is extracted and
passed on to the routed method.
"""
decode.return_value = "CTOKEN"
step.return_value = b"STOKEN"
async with TestClient(SPNEGOAuthMiddleware(index, service="http")) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 200
assert r.content == b"Hello [email protected]"
assert r.headers["WWW-Authenticate"] == "Negotiate {}".format(base64.b64encode(b"STOKEN").decode())
assert step.mock_calls != []
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@mock.patch("gssapi.SecurityContext.initiator_name", "[email protected]")
@mock.patch("gssapi.SecurityContext.complete", True)
@mock.patch("gssapi.SecurityContext.step")
@mock.patch("base64.b64decode")
@pytest.mark.asyncio
async def test_authorized_any_hostname(decode, step): # self):#, clean, name, response, step, init):
"""
Ensure that the server can find matching hostname entry from the keytab.
We set hostname="" in this test to achive this.
"""
decode.return_value = "CTOKEN"
step.return_value = b"STOKEN"
async with TestClient(SPNEGOAuthMiddleware(index, service="http", hostname="")) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 200
assert r.content == b"Hello [email protected]"
assert r.headers["WWW-Authenticate"] == "Negotiate {}".format(base64.b64encode(b"STOKEN").decode())
assert step.mock_calls != []
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_forbidden():
"""
Ensure that when the client sends an incorrect authorization token,
they receive a 403 Forbidden response.
"""
async with TestClient(SPNEGOAuthMiddleware(index, service="http")) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 403
assert r.content, b"Forbidden"
assert r.headers["content-type"] == "text/plain"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_forbidden_custom():
"""
Ensure that when the client sends an incorrect authorization token,
they receive a 403 Forbidden response. If configured, they should
receive customized content.
"""
async with TestClient(SPNEGOAuthMiddleware(index, service="http", forbidden="CUSTOM")) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 403
assert r.content == b"CUSTOM"
assert r.headers["content-type"] == "text/plain"
assert r.headers["content-length"] == str(len(r.content))
@mock.patch("gssapi.Credentials", lambda name, usage: None)
@pytest.mark.asyncio
async def test_forbidden_custom_content_type():
"""
Ensure that when the client sends an incorrect authorization token,
they receive a 403 Forbidden response. If configured, they should
receive customized content and content-type.
"""
async with TestClient(
SPNEGOAuthMiddleware(index, service="http", forbidden=quick_error(403, b"CUSTOM", b"text/html"))
) as app:
r = await app.get("/", headers={"Authorization": "Negotiate CTOKEN"})
assert r.status_code == 403
assert r.content == b"CUSTOM"
assert r.headers["content-type"] == "text/html"
assert r.headers["content-length"] == str(len(r.content))