-
Notifications
You must be signed in to change notification settings - Fork 511
Expand file tree
/
Copy pathtest_rest_auth.py
More file actions
271 lines (220 loc) · 10.9 KB
/
Copy pathtest_rest_auth.py
File metadata and controls
271 lines (220 loc) · 10.9 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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import base64
from unittest.mock import MagicMock, patch
import pytest
import requests
from requests_mock import Mocker
from pyiceberg.catalog.rest.auth import (
AuthManagerAdapter,
BasicAuthManager,
EntraAuthManager,
GoogleAuthManager,
LegacyOAuth2AuthManager,
NoopAuthManager,
)
TEST_URI = "https://iceberg-test-catalog/"
GOOGLE_CREDS_URI = "https://oauth2.googleapis.com/token"
@pytest.fixture
def rest_mock(requests_mock: Mocker) -> Mocker:
requests_mock.get(
TEST_URI,
json={},
status_code=200,
)
return requests_mock
@pytest.fixture
def google_mock(requests_mock: Mocker) -> Mocker:
requests_mock.post(GOOGLE_CREDS_URI, json={"access_token": "aaaabbb"}, status_code=200)
requests_mock.get(
TEST_URI,
json={},
status_code=200,
)
return requests_mock
def test_noop_auth_header(rest_mock: Mocker) -> None:
auth_manager = NoopAuthManager()
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert "Authorization" not in actual_headers
def test_basic_auth_header(rest_mock: Mocker) -> None:
username = "testuser"
password = "testpassword"
expected_token = base64.b64encode(f"{username}:{password}".encode()).decode()
expected_header = f"Basic {expected_token}"
auth_manager = BasicAuthManager(username=username, password=password)
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == expected_header
@patch("google.auth.transport.requests.Request")
@patch("google.auth.default")
def test_google_auth_manager_default_credentials(
mock_google_auth_default: MagicMock, mock_google_request: MagicMock, rest_mock: Mocker
) -> None:
"""Test GoogleAuthManager with default application credentials."""
mock_credentials = MagicMock()
mock_credentials.token = "test_token"
mock_google_auth_default.return_value = (mock_credentials, "test_project")
auth_manager = GoogleAuthManager()
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_google_auth_default.assert_called_once_with(scopes=None)
mock_credentials.refresh.assert_called_once_with(mock_google_request.return_value)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer test_token"
@patch("google.auth.transport.requests.Request")
@patch("google.auth.load_credentials_from_file")
def test_google_auth_manager_with_credentials_file(
mock_load_creds: MagicMock, mock_google_request: MagicMock, rest_mock: Mocker
) -> None:
"""Test GoogleAuthManager with a credentials file path."""
mock_credentials = MagicMock()
mock_credentials.token = "file_token"
mock_load_creds.return_value = (mock_credentials, "test_project_file")
auth_manager = GoogleAuthManager(credentials_path="/fake/path.json")
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_load_creds.assert_called_once_with("/fake/path.json", scopes=None)
mock_credentials.refresh.assert_called_once_with(mock_google_request.return_value)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer file_token"
@patch("google.auth.transport.requests.Request")
@patch("google.auth.load_credentials_from_file")
def test_google_auth_manager_with_credentials_file_and_scopes(
mock_load_creds: MagicMock, mock_google_request: MagicMock, rest_mock: Mocker
) -> None:
"""Test GoogleAuthManager with a credentials file path and scopes."""
mock_credentials = MagicMock()
mock_credentials.token = "scoped_token"
mock_load_creds.return_value = (mock_credentials, "test_project_scoped")
scopes = ["https://www.googleapis.com/auth/bigquery"]
auth_manager = GoogleAuthManager(credentials_path="/fake/path.json", scopes=scopes)
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_load_creds.assert_called_once_with("/fake/path.json", scopes=scopes)
mock_credentials.refresh.assert_called_once_with(mock_google_request.return_value)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer scoped_token"
def test_google_auth_manager_import_error() -> None:
"""Test GoogleAuthManager raises ImportError if google-auth is not installed."""
with patch.dict("sys.modules", {"google.auth": None, "google.auth.transport.requests": None}):
with pytest.raises(ImportError, match="Google Auth libraries not found. Please install 'google-auth'."):
GoogleAuthManager()
@patch("azure.identity.DefaultAzureCredential")
def test_entra_auth_manager_default_credential(mock_default_cred: MagicMock, rest_mock: Mocker) -> None:
"""Test EntraAuthManager with DefaultAzureCredential."""
mock_credential_instance = MagicMock()
mock_token = MagicMock()
mock_token.token = "entra_default_token"
mock_token.expires_on = 9999999999 # Far future timestamp
mock_credential_instance.get_token.return_value = mock_token
mock_default_cred.return_value = mock_credential_instance
auth_manager = EntraAuthManager()
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_default_cred.assert_called_once_with()
mock_credential_instance.get_token.assert_called_once_with("https://storage.azure.com/.default")
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer entra_default_token"
@patch("azure.identity.DefaultAzureCredential")
def test_entra_auth_manager_with_managed_identity_client_id(mock_default_cred: MagicMock, rest_mock: Mocker) -> None:
"""Test EntraAuthManager with managed_identity_client_id passed to DefaultAzureCredential."""
mock_credential_instance = MagicMock()
mock_token = MagicMock()
mock_token.token = "entra_mi_token"
mock_token.expires_on = 9999999999
mock_credential_instance.get_token.return_value = mock_token
mock_default_cred.return_value = mock_credential_instance
auth_manager = EntraAuthManager(managed_identity_client_id="user-assigned-client-id")
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_default_cred.assert_called_once_with(managed_identity_client_id="user-assigned-client-id")
mock_credential_instance.get_token.assert_called_once_with("https://storage.azure.com/.default")
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer entra_mi_token"
@patch("azure.identity.DefaultAzureCredential")
def test_entra_auth_manager_custom_scopes(mock_default_cred: MagicMock, rest_mock: Mocker) -> None:
"""Test EntraAuthManager with custom scopes."""
mock_credential_instance = MagicMock()
mock_token = MagicMock()
mock_token.token = "entra_custom_scope_token"
mock_token.expires_on = 9999999999
mock_credential_instance.get_token.return_value = mock_token
mock_default_cred.return_value = mock_credential_instance
custom_scopes = ["https://datalake.azure.net/.default", "https://storage.azure.com/.default"]
auth_manager = EntraAuthManager(scopes=custom_scopes)
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
session.get(TEST_URI)
mock_default_cred.assert_called_once_with()
mock_credential_instance.get_token.assert_called_once_with(*custom_scopes)
history = rest_mock.request_history
assert len(history) == 1
actual_headers = history[0].headers
assert actual_headers["Authorization"] == "Bearer entra_custom_scope_token"
def test_entra_auth_manager_import_error() -> None:
"""Test EntraAuthManager raises ImportError if azure-identity is not installed."""
with patch.dict("sys.modules", {"azure.identity": None}):
with pytest.raises(ImportError, match="Azure Identity library not found"):
EntraAuthManager()
@patch("azure.identity.DefaultAzureCredential")
def test_entra_auth_manager_token_failure(mock_default_cred: MagicMock, rest_mock: Mocker) -> None:
"""Test EntraAuthManager raises exception when token acquisition fails."""
mock_credential_instance = MagicMock()
mock_credential_instance.get_token.side_effect = Exception("Failed to acquire token")
mock_default_cred.return_value = mock_credential_instance
auth_manager = EntraAuthManager()
session = requests.Session()
session.auth = AuthManagerAdapter(auth_manager)
with pytest.raises(Exception, match="Failed to acquire token"):
session.get(TEST_URI)
def test_legacy_oauth2_auth_header_returns_none_when_no_token() -> None:
"""LegacyOAuth2AuthManager.auth_header() must return None (not 'Bearer None') when no
credential or initial_token is provided. Returning 'Bearer None' caused S3V4RestSigner
to forward an invalid Authorization header to the catalog signer endpoint, resulting in
a 403 that was silently swallowed and the S3 request going unsigned."""
session = requests.Session()
auth_manager = LegacyOAuth2AuthManager(session=session, credential=None, initial_token=None)
assert auth_manager.auth_header() is None
def test_legacy_oauth2_auth_header_returns_bearer_token_when_set() -> None:
"""LegacyOAuth2AuthManager.auth_header() returns a proper Bearer token when one is present."""
session = requests.Session()
auth_manager = LegacyOAuth2AuthManager(session=session, credential=None, initial_token="my-token")
assert auth_manager.auth_header() == "Bearer my-token"