-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_auth_handler.py
More file actions
647 lines (528 loc) · 21.1 KB
/
test_auth_handler.py
File metadata and controls
647 lines (528 loc) · 21.1 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# Copyright 2026 Google LLC
#
# Licensed 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 copy
import time
from unittest.mock import Mock
from unittest.mock import patch
from authlib.oauth2.rfc6749 import OAuth2Token
from fastapi.openapi.models import APIKey
from fastapi.openapi.models import APIKeyIn
from fastapi.openapi.models import OAuth2
from fastapi.openapi.models import OAuthFlowAuthorizationCode
from fastapi.openapi.models import OAuthFlows
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_credential import AuthCredentialTypes
from google.adk.auth.auth_credential import OAuth2Auth
from google.adk.auth.auth_handler import AuthHandler
from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.auth.auth_tool import AuthConfig
import pytest
# Mock classes for testing
class MockState(dict):
"""Mock State class for testing."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def get(self, key, default=None):
return super().get(key, default)
class MockOAuth2Session:
"""Mock OAuth2Session for testing."""
def __init__(
self,
client_id=None,
client_secret=None,
scope=None,
redirect_uri=None,
state=None,
):
self.client_id = client_id
self.client_secret = client_secret
self.scope = scope
self.redirect_uri = redirect_uri
self.state = state
def create_authorization_url(self, url, **kwargs):
params = f"client_id={self.client_id}&scope={self.scope}"
if kwargs.get("audience"):
params += f"&audience={kwargs.get('audience')}"
if kwargs.get("code_challenge_method"):
params += (
"&code_challenge_method="
f"{kwargs.get('code_challenge_method')}"
)
if kwargs.get("code_challenge"):
params += f"&code_challenge={kwargs.get('code_challenge')}"
if kwargs.get("code_verifier"):
params += f"&code_verifier={kwargs.get('code_verifier')}"
return f"{url}?{params}", "mock_state"
def fetch_token(
self,
token_endpoint,
authorization_response=None,
code=None,
grant_type=None,
):
return {
"access_token": "mock_access_token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "mock_refresh_token",
}
# Fixtures for common test objects
@pytest.fixture
def oauth2_auth_scheme():
"""Create an OAuth2 auth scheme for testing."""
# Create the OAuthFlows object first
flows = OAuthFlows(
authorizationCode=OAuthFlowAuthorizationCode(
authorizationUrl="https://example.com/oauth2/authorize",
tokenUrl="https://example.com/oauth2/token",
scopes={"read": "Read access", "write": "Write access"},
)
)
# Then create the OAuth2 object with the flows
return OAuth2(flows=flows)
@pytest.fixture
def openid_auth_scheme():
"""Create an OpenID Connect auth scheme for testing."""
return OpenIdConnectWithConfig(
openIdConnectUrl="https://example.com/.well-known/openid-configuration",
authorization_endpoint="https://example.com/oauth2/authorize",
token_endpoint="https://example.com/oauth2/token",
scopes=["openid", "profile", "email"],
)
@pytest.fixture
def oauth2_credentials():
"""Create OAuth2 credentials for testing."""
return AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
redirect_uri="https://example.com/callback",
),
)
@pytest.fixture
def oauth2_credentials_with_token():
"""Create OAuth2 credentials with a token for testing."""
return AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
redirect_uri="https://example.com/callback",
access_token="mock_access_token",
refresh_token="mock_refresh_token",
),
)
@pytest.fixture
def oauth2_credentials_with_auth_uri():
"""Create OAuth2 credentials with an auth URI for testing."""
return AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
redirect_uri="https://example.com/callback",
auth_uri="https://example.com/oauth2/authorize?client_id=mock_client_id&scope=read,write",
state="mock_state",
),
)
@pytest.fixture
def oauth2_credentials_with_auth_code():
"""Create OAuth2 credentials with an auth code for testing."""
return AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
redirect_uri="https://example.com/callback",
auth_uri="https://example.com/oauth2/authorize?client_id=mock_client_id&scope=read,write",
state="mock_state",
auth_code="mock_auth_code",
auth_response_uri="https://example.com/callback?code=mock_auth_code&state=mock_state",
),
)
@pytest.fixture
def auth_config(oauth2_auth_scheme, oauth2_credentials):
"""Create an AuthConfig for testing."""
# Create a copy of the credentials for the exchanged_auth_credential
exchanged_credential = oauth2_credentials.model_copy(deep=True)
return AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=oauth2_credentials,
exchanged_auth_credential=exchanged_credential,
)
@pytest.fixture
def auth_config_with_exchanged(
oauth2_auth_scheme, oauth2_credentials, oauth2_credentials_with_auth_uri
):
"""Create an AuthConfig with exchanged credentials for testing."""
return AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=oauth2_credentials,
exchanged_auth_credential=oauth2_credentials_with_auth_uri,
)
@pytest.fixture
def auth_config_with_auth_code(
oauth2_auth_scheme, oauth2_credentials, oauth2_credentials_with_auth_code
):
"""Create an AuthConfig with auth code for testing."""
return AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=oauth2_credentials,
exchanged_auth_credential=oauth2_credentials_with_auth_code,
)
class TestAuthHandlerInit:
"""Tests for the AuthHandler initialization."""
def test_init(self, auth_config):
"""Test the initialization of AuthHandler."""
handler = AuthHandler(auth_config)
assert handler.auth_config == auth_config
class TestGenerateAuthUri:
"""Tests for the generate_auth_uri method."""
@patch("google.adk.auth.auth_handler.OAuth2Session", MockOAuth2Session)
def test_generate_auth_uri_oauth2(self, auth_config):
"""Test generating an auth URI for OAuth2."""
handler = AuthHandler(auth_config)
result = handler.generate_auth_uri()
assert result.oauth2.auth_uri.startswith(
"https://example.com/oauth2/authorize"
)
assert "client_id=mock_client_id" in result.oauth2.auth_uri
assert "audience" not in result.oauth2.auth_uri
assert result.oauth2.state == "mock_state"
@patch("google.adk.auth.auth_handler.OAuth2Session", MockOAuth2Session)
def test_generate_auth_uri_with_audience_and_prompt(
self, openid_auth_scheme, oauth2_credentials
):
"""Test generating an auth URI with audience and prompt."""
oauth2_credentials.oauth2.audience = "test_audience"
exchanged = oauth2_credentials.model_copy(deep=True)
config = AuthConfig(
auth_scheme=openid_auth_scheme,
raw_auth_credential=oauth2_credentials,
exchanged_auth_credential=exchanged,
)
handler = AuthHandler(config)
result = handler.generate_auth_uri()
assert "audience=test_audience" in result.oauth2.auth_uri
@patch("google.adk.auth.auth_handler.OAuth2Session", MockOAuth2Session)
def test_generate_auth_uri_with_pkce(self, auth_config):
"""Test generating an auth URI with PKCE enabled."""
auth_config.raw_auth_credential.oauth2.code_challenge_method = "S256"
handler = AuthHandler(auth_config)
result = handler.generate_auth_uri()
assert "code_challenge_method=S256" in result.oauth2.auth_uri
assert "code_challenge=" in result.oauth2.auth_uri
assert "code_verifier=" not in result.oauth2.auth_uri
assert result.oauth2.code_verifier
@patch("google.adk.auth.auth_handler.OAuth2Session", MockOAuth2Session)
def test_generate_auth_uri_openid(
self, openid_auth_scheme, oauth2_credentials
):
"""Test generating an auth URI for OpenID Connect."""
# Create a copy for the exchanged credential
exchanged = oauth2_credentials.model_copy(deep=True)
config = AuthConfig(
auth_scheme=openid_auth_scheme,
raw_auth_credential=oauth2_credentials,
exchanged_auth_credential=exchanged,
)
handler = AuthHandler(config)
result = handler.generate_auth_uri()
assert result.oauth2.auth_uri.startswith(
"https://example.com/oauth2/authorize"
)
assert "client_id=mock_client_id" in result.oauth2.auth_uri
assert result.oauth2.state == "mock_state"
class TestGenerateAuthRequest:
"""Tests for the generate_auth_request method."""
def test_non_oauth_scheme(self):
"""Test with a non-OAuth auth scheme."""
# Use a SecurityBase instance without using APIKey which has validation issues
api_key_scheme = APIKey(**{"name": "test_api_key", "in": APIKeyIn.header})
credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="test_api_key"
)
# Create a copy for the exchanged credential
exchanged = credential.model_copy(deep=True)
config = AuthConfig(
auth_scheme=api_key_scheme,
raw_auth_credential=credential,
exchanged_auth_credential=exchanged,
)
handler = AuthHandler(config)
result = handler.generate_auth_request()
assert result == config
def test_with_existing_auth_uri(self, auth_config_with_exchanged):
"""Test when auth_uri already exists in exchanged credential."""
handler = AuthHandler(auth_config_with_exchanged)
result = handler.generate_auth_request()
assert (
result.exchanged_auth_credential.oauth2.auth_uri
== auth_config_with_exchanged.exchanged_auth_credential.oauth2.auth_uri
)
def test_missing_raw_credential(self, oauth2_auth_scheme):
"""Test when raw_auth_credential is missing."""
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
)
handler = AuthHandler(config)
with pytest.raises(ValueError, match="requires auth_credential"):
handler.generate_auth_request()
def test_missing_oauth2_in_raw_credential(self, oauth2_auth_scheme):
"""Test when oauth2 is missing in raw_auth_credential."""
credential = AuthCredential(
auth_type=AuthCredentialTypes.API_KEY, api_key="test_api_key"
)
# Create a copy for the exchanged credential
exchanged = credential.model_copy(deep=True)
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=credential,
exchanged_auth_credential=exchanged,
)
handler = AuthHandler(config)
with pytest.raises(ValueError, match="requires oauth2 in auth_credential"):
handler.generate_auth_request()
def test_auth_uri_in_raw_credential(
self, oauth2_auth_scheme, oauth2_credentials_with_auth_uri
):
"""Test when auth_uri exists in raw_credential."""
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=oauth2_credentials_with_auth_uri,
exchanged_auth_credential=oauth2_credentials_with_auth_uri.model_copy(
deep=True
),
credential_key="my_tool_tokens",
)
handler = AuthHandler(config)
result = handler.generate_auth_request()
assert result.credential_key == "my_tool_tokens"
assert (
result.exchanged_auth_credential.oauth2.auth_uri
== oauth2_credentials_with_auth_uri.oauth2.auth_uri
)
def test_missing_client_credentials(self, oauth2_auth_scheme):
"""Test when client_id or client_secret is missing."""
bad_credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(redirect_uri="https://example.com/callback"),
)
# Create a copy for the exchanged credential
exchanged = bad_credential.model_copy(deep=True)
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=bad_credential,
exchanged_auth_credential=exchanged,
)
handler = AuthHandler(config)
with pytest.raises(
ValueError, match="requires both client_id and client_secret"
):
handler.generate_auth_request()
@patch("google.adk.auth.auth_handler.AuthHandler.generate_auth_uri")
def test_generate_new_auth_uri(self, mock_generate_auth_uri, auth_config):
"""Test generating a new auth URI."""
mock_credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
redirect_uri="https://example.com/callback",
auth_uri="https://example.com/generated",
state="generated_state",
),
)
mock_generate_auth_uri.return_value = mock_credential
handler = AuthHandler(auth_config)
result = handler.generate_auth_request()
assert mock_generate_auth_uri.called
assert result.exchanged_auth_credential == mock_credential
@patch("google.adk.auth.auth_handler.AuthHandler.generate_auth_uri")
def test_preserves_credential_key_on_generated_request(
self, mock_generate_auth_uri, oauth2_auth_scheme, oauth2_credentials
):
"""Test that AuthHandler preserves an explicit credential_key."""
mock_generate_auth_uri.return_value = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(
client_id="mock_client_id",
client_secret="mock_client_secret",
auth_uri="https://example.com/generated",
state="generated_state",
),
)
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
raw_auth_credential=oauth2_credentials,
credential_key="my_tool_tokens",
)
handler = AuthHandler(config)
result = handler.generate_auth_request()
assert result.credential_key == "my_tool_tokens"
class TestGetAuthResponse:
"""Tests for the get_auth_response method."""
def test_get_auth_response_exists(
self, auth_config, oauth2_credentials_with_auth_uri
):
"""Test retrieving an existing auth response from state."""
handler = AuthHandler(auth_config)
state = MockState()
# Store a credential in the state
credential_key = auth_config.credential_key
state["temp:" + credential_key] = oauth2_credentials_with_auth_uri
result = handler.get_auth_response(state)
assert result == oauth2_credentials_with_auth_uri
def test_get_auth_response_not_exists(self, auth_config):
"""Test retrieving a nonexistent auth response from state."""
handler = AuthHandler(auth_config)
state = MockState()
result = handler.get_auth_response(state)
assert result is None
class TestParseAndStoreAuthResponse:
"""Tests for the parse_and_store_auth_response method."""
@pytest.mark.asyncio
async def test_non_oauth_scheme(self, auth_config_with_exchanged):
"""Test with a non-OAuth auth scheme."""
# Modify the auth scheme type to be non-OAuth
auth_config = copy.deepcopy(auth_config_with_exchanged)
auth_config.auth_scheme = APIKey(
**{"name": "test_api_key", "in": APIKeyIn.header}
)
handler = AuthHandler(auth_config)
state = MockState()
await handler.parse_and_store_auth_response(state)
credential_key = auth_config.credential_key
assert (
state["temp:" + credential_key] == auth_config.exchanged_auth_credential
)
@patch("google.adk.auth.auth_handler.AuthHandler.exchange_auth_token")
@pytest.mark.asyncio
async def test_oauth_scheme(
self, mock_exchange_token, auth_config_with_exchanged
):
"""Test with an OAuth auth scheme."""
mock_exchange_token.return_value = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(access_token="exchanged_token"),
)
handler = AuthHandler(auth_config_with_exchanged)
state = MockState()
await handler.parse_and_store_auth_response(state)
credential_key = auth_config_with_exchanged.credential_key
assert state["temp:" + credential_key] == mock_exchange_token.return_value
assert mock_exchange_token.called
class TestExchangeAuthToken:
"""Tests for the exchange_auth_token method."""
@pytest.mark.asyncio
async def test_token_exchange_not_supported(
self, auth_config_with_auth_code, monkeypatch
):
"""Test when token exchange is not supported."""
monkeypatch.setattr(
"google.adk.auth.exchanger.oauth2_credential_exchanger.AUTHLIB_AVAILABLE",
False,
)
handler = AuthHandler(auth_config_with_auth_code)
result = await handler.exchange_auth_token()
assert result == auth_config_with_auth_code.exchanged_auth_credential
@pytest.mark.asyncio
async def test_openid_missing_token_endpoint(
self, openid_auth_scheme, oauth2_credentials_with_auth_code
):
"""Test OpenID Connect without a token endpoint."""
# Create a scheme without token_endpoint
scheme_without_token = copy.deepcopy(openid_auth_scheme)
delattr(scheme_without_token, "token_endpoint")
config = AuthConfig(
auth_scheme=scheme_without_token,
raw_auth_credential=oauth2_credentials_with_auth_code,
exchanged_auth_credential=oauth2_credentials_with_auth_code,
)
handler = AuthHandler(config)
result = await handler.exchange_auth_token()
assert result == oauth2_credentials_with_auth_code
@pytest.mark.asyncio
async def test_oauth2_missing_token_url(
self, oauth2_auth_scheme, oauth2_credentials_with_auth_code
):
"""Test OAuth2 without a token URL."""
# Create a scheme without tokenUrl
scheme_without_token = copy.deepcopy(oauth2_auth_scheme)
scheme_without_token.flows.authorizationCode.tokenUrl = None
config = AuthConfig(
auth_scheme=scheme_without_token,
raw_auth_credential=oauth2_credentials_with_auth_code,
exchanged_auth_credential=oauth2_credentials_with_auth_code,
)
handler = AuthHandler(config)
result = await handler.exchange_auth_token()
assert result == oauth2_credentials_with_auth_code
@pytest.mark.asyncio
async def test_non_oauth_scheme(self, auth_config_with_auth_code):
"""Test with a non-OAuth auth scheme."""
# Modify the auth scheme type to be non-OAuth
auth_config = copy.deepcopy(auth_config_with_auth_code)
auth_config.auth_scheme = APIKey(
**{"name": "test_api_key", "in": APIKeyIn.header}
)
handler = AuthHandler(auth_config)
result = await handler.exchange_auth_token()
assert result == auth_config.exchanged_auth_credential
@pytest.mark.asyncio
async def test_missing_credentials(self, oauth2_auth_scheme):
"""Test with missing credentials."""
empty_credential = AuthCredential(auth_type=AuthCredentialTypes.OAUTH2)
config = AuthConfig(
auth_scheme=oauth2_auth_scheme,
exchanged_auth_credential=empty_credential,
)
handler = AuthHandler(config)
result = await handler.exchange_auth_token()
assert result == empty_credential
@pytest.mark.asyncio
async def test_credentials_with_token(
self, auth_config, oauth2_credentials_with_token
):
"""Test when credentials already have a token."""
config = AuthConfig(
auth_scheme=auth_config.auth_scheme,
raw_auth_credential=auth_config.raw_auth_credential,
exchanged_auth_credential=oauth2_credentials_with_token,
)
handler = AuthHandler(config)
result = await handler.exchange_auth_token()
assert result == oauth2_credentials_with_token
@patch("google.adk.auth.oauth2_credential_util.OAuth2Session")
@pytest.mark.asyncio
async def test_successful_token_exchange(
self, mock_oauth2_session, auth_config_with_auth_code
):
"""Test a successful token exchange."""
# Setup mock OAuth2Session
mock_client = Mock()
mock_oauth2_session.return_value = mock_client
mock_tokens = OAuth2Token({
"access_token": "mock_access_token",
"refresh_token": "mock_refresh_token",
"expires_at": int(time.time()) + 3600,
"expires_in": 3600,
})
mock_client.fetch_token.return_value = mock_tokens
handler = AuthHandler(auth_config_with_auth_code)
result = await handler.exchange_auth_token()
assert result.oauth2.access_token == "mock_access_token"
assert result.oauth2.refresh_token == "mock_refresh_token"
assert result.auth_type == AuthCredentialTypes.OAUTH2