-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtest_basic.py
More file actions
330 lines (261 loc) · 11.2 KB
/
test_basic.py
File metadata and controls
330 lines (261 loc) · 11.2 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
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
"""Tests for basic authentication for the Ralph API."""
import base64
import json
import os
import bcrypt
import pytest
from fastapi.exceptions import HTTPException
from fastapi.security import HTTPBasicCredentials
from ralph.api.auth.basic import (
ServerUsersCredentials,
UserCredentials,
get_basic_auth_user,
)
from ralph.api.auth.user import AuthenticatedUser, UserScopes
from ralph.conf import AuthBackend, Settings, settings
from tests.helpers import configure_env_for_mock_oidc_auth
STORED_CREDENTIALS = json.dumps(
[
{
"username": "ralph",
"hash": bcrypt.hashpw(b"admin", bcrypt.gensalt()).decode("UTF-8"),
"scopes": ["statements/read/mine", "statements/write"],
"agent": {"mbox": "mailto:ralph@example.com"},
"target": "custom_target",
}
]
)
STORED_CREDENTIALS_MORE = json.dumps(
[
{
"username": "ralph",
"hash": bcrypt.hashpw(b"admin", bcrypt.gensalt()).decode("UTF-8"),
"scopes": ["statements/read/mine", "statements/write"],
"agent": {"mbox": "mailto:ralph@example.com"},
"target": "custom_target",
},
{
"username": "foo",
"hash": bcrypt.hashpw(b"bar", bcrypt.gensalt()).decode("UTF-8"),
"scopes": ["statements/read/mine", "statements/write"],
"agent": {"mbox": "mailto:foo@example.com"},
"target": "custom_target",
},
]
)
def test_api_auth_basic_model_serveruserscredentials():
"""Test api.auth ServerUsersCredentials model."""
users = ServerUsersCredentials(
root=[
UserCredentials(
username="johndoe",
hash="notrealhash",
scopes=["statements/read/mine", "statements/write"],
agent={"mbox": "mailto:johndoe@example.com"},
),
UserCredentials(
username="foo",
hash="notsorealhash",
scopes=["all"],
agent={"mbox": "mailto:foo@example.com"},
target="foo",
),
]
)
other_users = ServerUsersCredentials.model_validate(
[
UserCredentials(
username="janedoe",
hash="notreallyrealhash",
scopes=["statements/read/mine", "statements/write"],
agent={"mbox": "mailto:janedoe@example.com"},
),
]
)
# Test addition operator
users += other_users
# Test len
assert len(users) == 3
# Test getitem
assert users[0].username == "johndoe"
assert users[1].username == "foo"
assert users[2].username == "janedoe"
# Test iterator
usernames = [user.username for user in users]
assert len(usernames) == 3
assert usernames == ["johndoe", "foo", "janedoe"]
# Test username uniqueness validator
with pytest.raises(
ValueError,
match="You cannot create multiple credentials with the same username",
):
users += ServerUsersCredentials.model_validate(
[
UserCredentials(
username="foo",
hash="notsorealhash",
scopes=["statements/read/mine", "statements/write"],
agent={"mbox": "mailto:foo2@example.com"},
),
]
)
def test_api_auth_basic_caching_credentials(fs):
"""Test the caching of HTTP basic auth credentials."""
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
auth_file_modified_time = os.path.getmtime(auth_file_path)
get_basic_auth_user.cache_clear()
credentials = HTTPBasicCredentials(username="ralph", password="admin")
# Call function as in a first request with these credentials
get_basic_auth_user(credentials=credentials)
assert get_basic_auth_user.cache.popitem() == (
(auth_file_path, auth_file_modified_time, "ralph", "admin"),
AuthenticatedUser(
agent={"mbox": "mailto:ralph@example.com"},
scopes=UserScopes(["statements/read/mine", "statements/write"]),
target="custom_target",
),
)
def test_api_auth_basic_new_credentials(fs):
"""Test the authentication with new credentials and without clearing cache"""
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()
credentials = HTTPBasicCredentials(username="ralph", password="admin")
# Try to authenticate with known user, create cache entry
get_basic_auth_user(credentials)
# Add a new user to credentials file
# In order to test this, we do NOT clear cache
auth_file_mtime = os.path.getmtime(auth_file_path)
# FIX: Force update of modification time.
# It does not seem to be updated by setting the content of the pyfakefs file
os.remove(auth_file_path)
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS_MORE)
assert os.path.getmtime(auth_file_path) > auth_file_mtime
credentials_new = HTTPBasicCredentials(username="foo", password="bar")
# Try to authenticate with new user, should succeed
get_basic_auth_user(credentials_new)
def test_api_auth_basic_deleted_credentials(fs):
"""Test the authentication with deleted credentials and without clearing cache."""
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS_MORE)
get_basic_auth_user.cache_clear()
credentials = HTTPBasicCredentials(username="foo", password="bar")
# Try to authenticate with known user, create cache entry
get_basic_auth_user(credentials)
# In order to test this, we do NOT clear cache
auth_file_mtime = os.path.getmtime(auth_file_path)
# FIX: Force update of modification time.
# It does not seem to be updated by setting the content of the pyfakefs file
os.remove(auth_file_path)
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
assert os.path.getmtime(auth_file_path) > auth_file_mtime
# Try to authenticate with a deleted user, should fail
with pytest.raises(HTTPException):
get_basic_auth_user(credentials)
def test_api_auth_basic_with_wrong_password(fs):
"""Test the authentication with a wrong password."""
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()
credentials = HTTPBasicCredentials(username="ralph", password="wrong_password")
# Call function as in a first request with these credentials
with pytest.raises(HTTPException):
get_basic_auth_user(credentials)
def test_api_auth_basic_no_credential_file_found(fs, monkeypatch):
"""Test that, without a credential file, authentication fails."""
monkeypatch.setenv("RALPH_AUTH_FILE", "other_file")
monkeypatch.setattr("ralph.api.auth.basic.settings", Settings())
get_basic_auth_user.cache_clear()
credentials = HTTPBasicCredentials(username="ralph", password="admin")
with pytest.raises(HTTPException):
get_basic_auth_user(credentials)
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_no_credentials(client):
"""Whoami route returns a 401 error when no credentials are sent."""
response = await client.get("/whoami")
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_credentials_encoding_error(client):
"""Whoami route returns a 401 error when the credentials encoding is broken."""
response = await client.get(
"/whoami", headers={"Authorization": "Basic not-base64"}
)
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_username_not_found(fs, client):
"""Whoami route returns a 401 error when the username cannot be found."""
credential_bytes = base64.b64encode("john:admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
get_basic_auth_user.cache_clear()
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Basic"
assert response.json() == {"detail": "Invalid authentication credentials"}
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_wrong_password(fs, client):
"""Whoami route returns a 401 error when the password is wrong."""
credential_bytes = base64.b64encode("john:not-admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)
assert response.status_code == 401
assert response.json() == {"detail": "Invalid authentication credentials"}
@pytest.mark.anyio
@pytest.mark.parametrize(
"runserver_auth_backends",
[[AuthBackend.BASIC, AuthBackend.OIDC], [AuthBackend.BASIC]],
)
async def test_api_auth_basic_get_whoami_correct_credentials(
fs, monkeypatch, runserver_auth_backends, client
):
"""Whoami returns a 200 response when the credentials are correct.
Return the username and associated scopes.
"""
configure_env_for_mock_oidc_auth(monkeypatch, runserver_auth_backends)
credential_bytes = base64.b64encode("ralph:admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)
assert response.status_code == 200
assert len(response.json().keys()) == 2
assert response.json()["agent"] == {
"mbox": "mailto:ralph@example.com",
"objectType": "Agent",
}
assert sorted(response.json()["scopes"]) == [
"statements/read/mine",
"statements/write",
]
@pytest.mark.anyio
async def test_api_auth_basic_get_whoami_invalid_backend(fs, monkeypatch, client):
"""Check for an exception when providing valid credentials when Basic
authentication is not supported.
"""
configure_env_for_mock_oidc_auth(monkeypatch, [AuthBackend.OIDC])
credential_bytes = base64.b64encode("ralph:admin".encode("utf-8"))
credentials = str(credential_bytes, "utf-8")
auth_file_path = settings.APP_DIR / "auth.json"
fs.create_file(auth_file_path, contents=STORED_CREDENTIALS)
get_basic_auth_user.cache_clear()
response = await client.get(
"/whoami", headers={"Authorization": f"Basic {credentials}"}
)
assert response.status_code == 401
assert response.json() == {"detail": "Invalid authentication credentials"}