Skip to content

Commit b55a50d

Browse files
GWealecopybara-github
authored andcommitted
chore: fix mypy strict type errors in adk auth
Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 945169969
1 parent b46dd13 commit b55a50d

11 files changed

Lines changed: 42 additions & 33 deletions

src/google/adk/auth/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
from __future__ import annotations
1616

17-
import importlib
1817
from typing import TYPE_CHECKING
1918

2019
from .auth_credential import AuthCredential
@@ -30,7 +29,9 @@
3029
from .auth_handler import AuthHandler
3130

3231

33-
def __getattr__(name: str):
34-
if name == 'AuthHandler':
35-
return importlib.import_module(f'{__name__}.auth_handler').AuthHandler
36-
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
32+
def __getattr__(name: str) -> type[AuthHandler]:
33+
if name == "AuthHandler":
34+
from .auth_handler import AuthHandler
35+
36+
return AuthHandler
37+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

src/google/adk/auth/auth_handler.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ async def parse_and_store_auth_response(self, state: State) -> None:
8181
state[credential_key] = await self.exchange_auth_token()
8282

8383
def _validate(self) -> None:
84-
if not self.auth_scheme:
84+
if not self.auth_config.auth_scheme:
8585
raise ValueError("auth_scheme is empty.")
8686

8787
def get_auth_response(self, state: State) -> AuthCredential:
@@ -236,9 +236,10 @@ def generate_auth_uri(
236236
)
237237

238238
exchanged_auth_credential = auth_credential.model_copy(deep=True)
239-
exchanged_auth_credential.oauth2.auth_uri = uri
240-
exchanged_auth_credential.oauth2.state = state
241-
if code_verifier:
242-
exchanged_auth_credential.oauth2.code_verifier = code_verifier
239+
if exchanged_auth_credential.oauth2 is not None:
240+
exchanged_auth_credential.oauth2.auth_uri = uri
241+
exchanged_auth_credential.oauth2.state = state
242+
if code_verifier:
243+
exchanged_auth_credential.oauth2.code_verifier = code_verifier
243244

244245
return exchanged_auth_credential

src/google/adk/auth/auth_preprocessor.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
# Prefix used by toolset auth credential IDs.
3535
# Auth requests with this prefix are for toolset authentication (before tool
3636
# listing) and don't require resuming a function call.
37-
TOOLSET_AUTH_CREDENTIAL_ID_PREFIX = '_adk_toolset_auth_'
37+
TOOLSET_AUTH_CREDENTIAL_ID_PREFIX = "_adk_toolset_auth_"
3838

3939

4040
async def _store_auth_and_collect_resume_targets(
@@ -132,7 +132,7 @@ async def run_async(
132132
self, invocation_context: InvocationContext, llm_request: LlmRequest
133133
) -> AsyncGenerator[Event, None]:
134134
agent = invocation_context.agent
135-
if not hasattr(agent, 'canonical_tools'):
135+
if agent is None or not hasattr(agent, "canonical_tools"):
136136
return
137137
events = invocation_context._get_events(current_branch=True)
138138
if not events:
@@ -147,7 +147,7 @@ async def run_async(
147147
last_event_with_content = event
148148
break
149149

150-
if not last_event_with_content or last_event_with_content.author != 'user':
150+
if not last_event_with_content or last_event_with_content.author != "user":
151151
return
152152

153153
responses = last_event_with_content.get_function_responses()

src/google/adk/auth/auth_provider_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
class AuthProviderRegistry:
2727
"""Registry for auth provider instances."""
2828

29-
def __init__(self):
29+
def __init__(self) -> None:
3030
self._providers: dict[type[AuthScheme], BaseAuthProvider] = {}
3131

3232
def register(

src/google/adk/auth/auth_schemes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class OAuthGrantType(str, Enum):
6868
PASSWORD = "password"
6969

7070
@staticmethod
71-
def from_flow(flow: OAuthFlows) -> "OAuthGrantType":
71+
def from_flow(flow: OAuthFlows) -> Optional["OAuthGrantType"]:
7272
"""Converts an OAuthFlows object to a OAuthGrantType."""
7373
if flow.clientCredentials:
7474
return OAuthGrantType.CLIENT_CREDENTIALS

src/google/adk/auth/auth_tool.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import hashlib
1818
import json
19+
from typing import Any
1920
from typing import Optional
2021

2122
from pydantic import BaseModel
@@ -36,7 +37,8 @@ def _stable_model_digest(model: BaseModel) -> str:
3637
"""
3738
if getattr(model, "model_extra", None):
3839
model = model.model_copy(deep=True)
39-
model.model_extra.clear()
40+
if model.model_extra is not None:
41+
model.model_extra.clear()
4042

4143
dumped = model.model_dump(by_alias=True, exclude_none=True, mode="json")
4244
canonical_json = json.dumps(
@@ -79,12 +81,12 @@ class AuthConfig(BaseModelWithConfig):
7981
service.
8082
"""
8183

82-
def __init__(self, **data):
84+
def __init__(self, **data: Any) -> None:
8385
super().__init__(**data)
8486
if self.credential_key:
8587
return
8688
for obj in (self.raw_auth_credential, self.auth_scheme):
87-
if not obj or not getattr(obj, "model_extra", None):
89+
if not obj or not obj.model_extra:
8890
continue
8991
for key in ("credential_key", "credentialKey"):
9092
value = obj.model_extra.get(key)
@@ -94,7 +96,7 @@ def __init__(self, **data):
9496
self.credential_key = self.get_credential_key()
9597

9698
@deprecated("This method is deprecated. Use credential_key instead.")
97-
def get_credential_key(self):
99+
def get_credential_key(self) -> str:
98100
"""Builds a stable key based on auth_scheme and raw_auth_credential.
99101
100102
This is used to save/load credentials to/from a credential service when
@@ -105,7 +107,8 @@ def get_credential_key(self):
105107

106108
if auth_scheme.model_extra:
107109
auth_scheme = auth_scheme.model_copy(deep=True)
108-
auth_scheme.model_extra.clear()
110+
if auth_scheme.model_extra is not None:
111+
auth_scheme.model_extra.clear()
109112

110113
type_ = auth_scheme.type_
111114
type_name = type_.name if type_ and hasattr(type_, "name") else str(type_)
@@ -118,7 +121,8 @@ def get_credential_key(self):
118121
auth_credential = self.raw_auth_credential
119122
if auth_credential and auth_credential.model_extra:
120123
auth_credential = auth_credential.model_copy(deep=True)
121-
auth_credential.model_extra.clear()
124+
if auth_credential.model_extra is not None:
125+
auth_credential.model_extra.clear()
122126
if auth_credential and auth_credential.oauth2:
123127
auth_credential = auth_credential.model_copy(deep=True)
124128
if auth_credential.oauth2:

src/google/adk/auth/credential_manager.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
from .auth_credential import AuthCredential
2828
from .auth_credential import AuthCredentialTypes
2929
from .auth_provider_registry import AuthProviderRegistry
30-
from .auth_schemes import AuthScheme
3130
from .auth_schemes import AuthSchemeType
3231
from .auth_schemes import CustomAuthScheme
3332
from .auth_schemes import ExtendedOAuth2
@@ -43,7 +42,8 @@
4342

4443

4544
def _rehydrate_custom_scheme(
46-
scheme: CustomAuthScheme, supported_schemes: Sequence[type[AuthScheme]]
45+
scheme: CustomAuthScheme,
46+
supported_schemes: Sequence[type[CustomAuthScheme]],
4747
) -> CustomAuthScheme:
4848
"""Rehydrate a CustomAuthScheme into one of the given supported_schemes."""
4949
incoming_type = scheme.type_
@@ -231,10 +231,11 @@ async def get_auth_credential(
231231
await self._validate_credential()
232232

233233
# Step 2: Check if credential is already ready (no processing needed)
234-
if self._is_credential_ready():
234+
raw_auth_credential = self._auth_config.raw_auth_credential
235+
if self._is_credential_ready() and raw_auth_credential is not None:
235236
# Return a copy to avoid leaking mutations across invocations/users when
236237
# tools share a long-lived AuthConfig instance.
237-
return self._auth_config.raw_auth_credential.model_copy(deep=True)
238+
return raw_auth_credential.model_copy(deep=True)
238239

239240
# Step 3: Try to load existing processed credential
240241
credential = await self._load_existing_credential(context)
@@ -438,7 +439,7 @@ def _missing_oauth_info(self) -> bool:
438439
auth_scheme = self._auth_config.auth_scheme
439440
if isinstance(auth_scheme, OAuth2):
440441
flows = auth_scheme.flows
441-
return (
442+
return bool(
442443
flows.implicit
443444
and not flows.implicit.authorizationUrl
444445
or flows.password

src/google/adk/auth/exchanger/credential_exchanger_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
class CredentialExchangerRegistry:
2929
"""Registry for credential exchanger instances."""
3030

31-
def __init__(self):
31+
def __init__(self) -> None:
3232
self._exchangers: Dict[AuthCredentialTypes, BaseCredentialExchanger] = {}
3333

3434
def register(

src/google/adk/auth/exchanger/oauth2_credential_exchanger.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ async def _exchange_authorization_code(
186186
boolean indicating whether the credential was exchanged.
187187
"""
188188
client, token_endpoint = create_oauth2_session(auth_scheme, auth_credential)
189-
if not client:
189+
if not client or not auth_credential.oauth2:
190190
logger.warning(
191191
"Could not create OAuth2 session for authorization code exchange"
192192
)

src/google/adk/auth/refresher/credential_refresher_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
class CredentialRefresherRegistry:
3030
"""Registry for credential refresher instances."""
3131

32-
def __init__(self):
32+
def __init__(self) -> None:
3333
self._refreshers: Dict[AuthCredentialTypes, BaseCredentialRefresher] = {}
3434

3535
def register(

0 commit comments

Comments
 (0)