Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/google/adk/auth/exchanger/oauth2_credential_exchanger.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,19 @@ async def _exchange_client_credentials(
)
return ExchangeResult(auth_credential, False)

scopes: list[str] = []
if isinstance(auth_scheme, OAuth2) and auth_scheme.flows.clientCredentials:
scopes = list(auth_scheme.flows.clientCredentials.scopes or {})
elif isinstance(auth_scheme, OpenIdConnectWithConfig):
scopes = auth_scheme.scopes or []

try:
# authlib's client is synchronous; run it off the event loop.
tokens = await asyncio.to_thread(
client.fetch_token,
token_endpoint,
grant_type=OAuthGrantType.CLIENT_CREDENTIALS,
scope=" ".join(scopes) or None,
)
update_credential_with_tokens(auth_credential, tokens)
logger.debug("Successfully exchanged client credentials for access token")
Expand Down
46 changes: 46 additions & 0 deletions tests/unittests/auth/exchanger/test_oauth2_credential_exchanger.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@
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_schemes import AuthScheme
from google.adk.auth.auth_schemes import OAuthGrantType
from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.auth.exchanger import oauth2_credential_exchanger
from google.adk.auth.exchanger.base_credential_exchanger import CredentialExchangeError
from google.adk.auth.exchanger.oauth2_credential_exchanger import OAuth2CredentialExchanger
import pytest
from pytest_mock import MockerFixture
from requests import Response


class _TokenBodyCapturingOAuth2Session(OAuth2Session):
Expand Down Expand Up @@ -383,6 +386,7 @@ async def test_exchange_client_credentials_success(self, mock_oauth2_session):
mock_client.fetch_token.assert_called_once_with(
"https://example.com/token",
grant_type="client_credentials",
scope="read write",
)

@patch("google.adk.auth.oauth2_credential_util.OAuth2Session")
Expand Down Expand Up @@ -542,3 +546,45 @@ async def test_determine_grant_type_openid_connect(self):
from google.adk.auth.auth_schemes import OAuthGrantType

assert grant_type == OAuthGrantType.AUTHORIZATION_CODE


@pytest.mark.parametrize("scheme_kind", ["oauth2", "oidc"])
@pytest.mark.parametrize(
"scopes", [[], ["read:items"], ["read:items", "write:items"]]
)
async def test_client_credentials_request_scopes(
scheme_kind: str, scopes: list[str], mocker: MockerFixture
) -> None:
"""Configured scopes reach the actual Authlib client-credentials POST."""
scheme: AuthScheme
if scheme_kind == "oauth2":
scheme = OAuth2(
flows=OAuthFlows(
clientCredentials=OAuthFlowClientCredentials(
tokenUrl="https://example.com/token",
scopes={scope: scope for scope in scopes},
)
)
)
else:
scheme = OpenIdConnectWithConfig(
authorization_endpoint="https://example.com/auth",
token_endpoint="https://example.com/token",
grant_types_supported=["client_credentials"],
scopes=scopes,
)
credential = AuthCredential(
auth_type=AuthCredentialTypes.OAUTH2,
oauth2=OAuth2Auth(client_id="client", client_secret="secret"),
)
response = Response()
response.status_code = 200
response._content = b'{"access_token":"fresh","token_type":"Bearer"}'
send = mocker.patch("requests.sessions.Session.send", return_value=response)

result = await OAuth2CredentialExchanger().exchange(credential, scheme)

assert result.was_exchanged
body = parse_qs(send.call_args.args[0].body, keep_blank_values=True)
assert body["grant_type"] == ["client_credentials"]
assert body.get("scope") == ([" ".join(scopes)] if scopes else None)