Skip to content
This repository was archived by the owner on Mar 6, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
44 changes: 35 additions & 9 deletions google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
import datetime
from email.message import Message
import hashlib
import logging
import sys
from typing import Optional, Dict, Any
import urllib

from google.auth import exceptions
Expand All @@ -28,15 +30,8 @@
# expiry.
REFRESH_THRESHOLD = datetime.timedelta(minutes=3, seconds=45)

_SENSITIVE_FIELDS = {
"accessToken",
"access_token",
"id_token",
"client_id",
"refresh_token",
"client_secret",
}

# TODO(https://github.com/googleapis/google-auth-library-python/issues/1684): Audit and update the list below.
_SENSITIVE_FIELDS = {"accessToken", "access_token", "id_token", "client_id", "refresh_token", "client_secret"}

def copy_docstring(source_class):
"""Decorator that copies a method's docstring from another class.
Expand Down Expand Up @@ -311,3 +306,34 @@ def _hash_value(value, field_name: str) -> str:
hash_object.update(encoded_value)
hex_digest = hash_object.hexdigest()
return f"hashed_{field_name}-{hex_digest}"


def request_log(logger: logging.Logger, method: str, url: str, body: Optional[Any], headers: Optional[Dict[str, str]]) -> None:
"""
Logs an HTTP request at the DEBUG level.

Args:
logger: The logging.Logger instance to use.
method: The HTTP method (e.g., "GET", "POST").
url: The URL of the request.
body: The request body (can be None).
headers: The request headers (can be None).
"""
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1680): Log only if enabled.
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1682): Add httpRequest extra to log event.
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1681): Hash sensitive information.
logger.debug("Making request: %s %s", method, url)


def response_log(logger: logging.Logger, response: Any) -> None:
"""
Logs an HTTP response at the DEBUG level.

Args:
logger: The logging.Logger instance to use.
response: The HTTP response object to log.
"""
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1680): Log only if enabled.
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1683): Add httpResponse extra to log event.
# TODO(https://github.com/googleapis/google-auth-library-python/issues/1681): Hash sensitive information.
logger.debug("Response received...")
7 changes: 7 additions & 0 deletions google/auth/aio/transport/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"""

import asyncio
import logging
from typing import AsyncGenerator, Mapping, Optional

try:
Expand All @@ -29,6 +30,10 @@
from google.auth import exceptions
from google.auth.aio import transport

from _helpers import request_log, response_log

_LOGGER = logging.getLogger(__name__)


class Response(transport.Response):
"""
Expand Down Expand Up @@ -155,6 +160,7 @@ async def __call__(
self._session = aiohttp.ClientSession()

client_timeout = aiohttp.ClientTimeout(total=timeout)
request_log(_LOGGER, method, url, body, headers)
response = await self._session.request(
method,
url,
Expand All @@ -163,6 +169,7 @@ async def __call__(
timeout=client_timeout,
**kwargs,
)
response_log(_LOGGER, response)
return Response(response)

except aiohttp.ClientError as caught_exc:
Expand Down
8 changes: 7 additions & 1 deletion google/auth/transport/_aiohttp_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@
import functools

import aiohttp # type: ignore
import logging
import urllib3 # type: ignore

from google.auth import exceptions
from google.auth import transport
from google.auth.transport import requests

from _helpers import request_log, response_log

_LOGGER = logging.getLogger(__name__)

# Timeout can be re-defined depending on async requirement. Currently made 60s more than
# sync timeout.
_DEFAULT_TIMEOUT = 180 # in seconds
Expand Down Expand Up @@ -182,10 +187,11 @@ async def __call__(
self.session = aiohttp.ClientSession(
auto_decompress=False
) # pragma: NO COVER
requests._LOGGER.debug("Making request: %s %s", method, url)
request_log(_LOGGER, method, url, body, headers)
response = await self.session.request(
method, url, data=body, headers=headers, timeout=timeout, **kwargs
)
response_log(_LOGGER, response)
return _CombinedResponse(response)

except aiohttp.ClientError as caught_exc:
Expand Down
5 changes: 4 additions & 1 deletion google/auth/transport/_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from google.auth import exceptions
from google.auth import transport

from _helpers import request_log, response_log

_LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -99,10 +101,11 @@ def __call__(
connection = http_client.HTTPConnection(parts.netloc, timeout=timeout)

try:
_LOGGER.debug("Making request: %s %s", method, url)

request_log(_LOGGER, method, url, body, headers)
connection.request(method, path, body=body, headers=headers, **kwargs)
response = connection.getresponse()
response_log(_LOGGER, response)
return Response(response)

except (http_client.HTTPException, socket.error) as caught_exc:
Expand Down
5 changes: 4 additions & 1 deletion google/auth/transport/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
import google.auth.transport._mtls_helper
from google.oauth2 import service_account

from _helpers import request_log, response_log

_LOGGER = logging.getLogger(__name__)

_DEFAULT_TIMEOUT = 120 # in seconds
Expand Down Expand Up @@ -182,10 +184,11 @@ def __call__(
google.auth.exceptions.TransportError: If any exception occurred.
"""
try:
_LOGGER.debug("Making request: %s %s", method, url)
request_log(_LOGGER, method, url, body, headers)
response = self.session.request(
method, url, data=body, headers=headers, timeout=timeout, **kwargs
)
response_log(_LOGGER, response)
return _Response(response)
except requests.exceptions.RequestException as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
Expand Down
5 changes: 4 additions & 1 deletion google/auth/transport/urllib3.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
else: # pragma: NO COVER
RequestMethods = urllib3.request.RequestMethods # type: ignore

from _helpers import request_log, response_log

_LOGGER = logging.getLogger(__name__)


Expand Down Expand Up @@ -136,10 +138,11 @@ def __call__(
kwargs["timeout"] = timeout

try:
_LOGGER.debug("Making request: %s %s", method, url)
request_log(_LOGGER, method, url, body, headers)
response = self.http.request(
method, url, body=body, headers=headers, **kwargs
)
response_log(_LOGGER, response)
return _Response(response)
except urllib3.exceptions.HTTPError as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
Expand Down