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
20 changes: 20 additions & 0 deletions google/auth/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,26 @@ def utcnow():
return now


def utcfromtimestamp(timestamp):
"""Returns the UTC datetime from a timestamp.

Args:
timestamp (float): The timestamp to convert.

Returns:
datetime: The time in UTC.
"""
# We used datetime.utcfromtimestamp() before, since it's deprecated from
# python 3.12, we are using datetime.fromtimestamp(timestamp, timezone.utc)
# now. "utcfromtimestamp()" is offset-native (no timezone info), but
# "fromtimestamp(timestamp, timezone.utc)" is offset-aware (with timezone
# info). This will cause datetime comparison problem. For backward
# compatibility, we need to remove the timezone info.
dt = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
dt = dt.replace(tzinfo=None)
return dt


def datetime_to_secs(value):
"""Convert a datetime object to the number of seconds since the UNIX epoch.

Expand Down
3 changes: 1 addition & 2 deletions google/auth/app_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
https://cloud.google.com/appengine/docs/python/appidentity/
"""

import datetime

from google.auth import _helpers
from google.auth import credentials
Expand Down Expand Up @@ -128,7 +127,7 @@ def refresh(self, request):
scopes = self._scopes if self._scopes is not None else self._default_scopes
# pylint: disable=unused-argument
token, ttl = app_identity.get_access_token(scopes, self._service_account_id)
expiry = datetime.datetime.utcfromtimestamp(ttl)
expiry = _helpers.utcfromtimestamp(ttl)

self.token, self.expiry = token, expiry

Expand Down
2 changes: 1 addition & 1 deletion google/auth/compute_engine/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ def _call_metadata_identity_endpoint(self, request):
raise new_exc from caught_exc

_, payload, _, _ = jwt._unverified_decode(id_token)
return id_token, datetime.datetime.utcfromtimestamp(payload["exp"])
return id_token, _helpers.utcfromtimestamp(payload["exp"])

def refresh(self, request):
"""Refreshes the ID token.
Expand Down
2 changes: 1 addition & 1 deletion google/auth/impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ def refresh(self, request):
raise new_exc from caught_exc

self.token = id_token
self.expiry = datetime.utcfromtimestamp(
self.expiry = _helpers.utcfromtimestamp(
jwt.decode(id_token, verify=False)["exp"]
)

Expand Down
4 changes: 2 additions & 2 deletions google/oauth2/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ def call_iam_generate_id_token_endpoint(
raise new_exc from caught_exc

payload = jwt.decode(id_token, verify=False)
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
expiry = _helpers.utcfromtimestamp(payload["exp"])

return id_token, expiry

Expand Down Expand Up @@ -420,7 +420,7 @@ def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
raise new_exc from caught_exc

payload = jwt.decode(id_token, verify=False)
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
expiry = _helpers.utcfromtimestamp(payload["exp"])

return id_token, expiry, response_data

Expand Down
4 changes: 2 additions & 2 deletions google/oauth2/_client_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@
.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
"""

import datetime
import http.client as http_client
import json
import urllib

from google.auth import _exponential_backoff
from google.auth import _helpers
from google.auth import exceptions
from google.auth import jwt
from google.oauth2 import _client as client
Expand Down Expand Up @@ -227,7 +227,7 @@ async def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
raise new_exc from caught_exc

payload = jwt.decode(id_token, verify=False)
expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
expiry = _helpers.utcfromtimestamp(payload["exp"])

return id_token, expiry, response_data

Expand Down
40 changes: 26 additions & 14 deletions tests/compute_engine/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ def test_default_state(self, get):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -791,7 +791,7 @@ def test_make_authorization_grant_assertion(self, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -823,7 +823,7 @@ def test_with_service_account(self, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -879,7 +879,7 @@ def test_token_uri(self):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -1001,7 +1001,7 @@ def test_with_target_audience_integration(self):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -1040,7 +1040,7 @@ def test_with_quota_project(self, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand All @@ -1062,7 +1062,7 @@ def test_with_token_uri(self, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand Down Expand Up @@ -1170,7 +1170,7 @@ def test_with_quota_project_integration(self):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand All @@ -1181,7 +1181,11 @@ def test_refresh_success(self, id_token_jwt_grant, sign, get, utcnow):
]
sign.side_effect = [b"signature"]
id_token_jwt_grant.side_effect = [
("idtoken", datetime.datetime.utcfromtimestamp(3600), {})
(
"idtoken",
datetime.datetime.fromtimestamp(3600, tz=datetime.timezone.utc),
{},
)
]

request = mock.create_autospec(transport.Request, instance=True)
Expand All @@ -1194,7 +1198,9 @@ def test_refresh_success(self, id_token_jwt_grant, sign, get, utcnow):

# Check that the credentials have the token and proper expiration
assert self.credentials.token == "idtoken"
assert self.credentials.expiry == (datetime.datetime.utcfromtimestamp(3600))
assert self.credentials.expiry == (
datetime.datetime.fromtimestamp(3600, tz=datetime.timezone.utc)
)

# Check the credential info
assert self.credentials.service_account_email == "service-account@example.com"
Expand All @@ -1205,7 +1211,7 @@ def test_refresh_success(self, id_token_jwt_grant, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand All @@ -1232,7 +1238,7 @@ def test_refresh_error(self, sign, get, utcnow):

@mock.patch(
"google.auth._helpers.utcnow",
return_value=datetime.datetime.utcfromtimestamp(0),
return_value=datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc),
)
@mock.patch("google.auth.compute_engine._metadata.get", autospec=True)
@mock.patch("google.auth.iam.Signer.sign", autospec=True)
Expand All @@ -1243,7 +1249,11 @@ def test_before_request_refreshes(self, id_token_jwt_grant, sign, get, utcnow):
]
sign.side_effect = [b"signature"]
id_token_jwt_grant.side_effect = [
("idtoken", datetime.datetime.utcfromtimestamp(3600), {})
(
"idtoken",
datetime.datetime.fromtimestamp(3600, tz=datetime.timezone.utc),
{},
)
]

request = mock.create_autospec(transport.Request, instance=True)
Expand Down Expand Up @@ -1312,7 +1322,9 @@ def test_get_id_token_from_metadata(
}

assert cred.token == SAMPLE_ID_TOKEN
assert cred.expiry == datetime.datetime.utcfromtimestamp(SAMPLE_ID_TOKEN_EXP)
assert cred.expiry == datetime.datetime.fromtimestamp(
SAMPLE_ID_TOKEN_EXP, tz=datetime.timezone.utc
).replace(tzinfo=None)
assert cred._use_metadata_identity_endpoint
assert cred._signer is None
assert cred._token_uri is None
Expand Down
8 changes: 4 additions & 4 deletions tests/oauth2/test__client.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def test_jwt_grant_no_access_token():


def test_call_iam_generate_id_token_endpoint():
now = _helpers.utcnow()
now = _helpers.utcnow().astimezone(datetime.timezone.utc)
id_token_expiry = _helpers.datetime_to_secs(now)
id_token = jwt.encode(SIGNER, {"exp": id_token_expiry}).decode("utf-8")
request = make_request({"token": id_token})
Expand Down Expand Up @@ -343,7 +343,7 @@ def test_call_iam_generate_id_token_endpoint():
# Check result
assert token == id_token
# JWT does not store microseconds
now = now.replace(microsecond=0)
now = now.replace(microsecond=0).replace(tzinfo=None)
assert expiry == now


Expand All @@ -368,7 +368,7 @@ def test_call_iam_generate_id_token_endpoint_no_id_token():


def test_id_token_jwt_grant():
now = _helpers.utcnow()
now = _helpers.utcnow().astimezone(datetime.timezone.utc)
id_token_expiry = _helpers.datetime_to_secs(now)
id_token = jwt.encode(SIGNER, {"exp": id_token_expiry}).decode("utf-8")
request = make_request({"id_token": id_token, "extra": "data"})
Expand All @@ -385,7 +385,7 @@ def test_id_token_jwt_grant():
# Check result
assert token == id_token
# JWT does not store microseconds
now = now.replace(microsecond=0)
now = now.replace(microsecond=0).replace(tzinfo=None)
assert expiry == now
assert extra_data["extra"] == "data"

Expand Down
47 changes: 47 additions & 0 deletions tests/test__helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,3 +677,50 @@ def test_parse_response_no_json_method():

def test_parse_response_none():
assert _helpers._parse_response(None) is None


class TestUtcFromTimestamp:
"""Tests for the utcfromtimestamp utility function."""

@pytest.mark.parametrize(
"ts, expected",
[
(1704067200.0, datetime.datetime(2024, 1, 1, 0, 0, 0)),
(0.0, datetime.datetime(1970, 1, 1, 0, 0, 0)),
(1704067200.500123, datetime.datetime(2024, 1, 1, 0, 0, 0, 500123)),
(-31536000.0, datetime.datetime(1969, 1, 1, 0, 0, 0)),
(1000000000.0, datetime.datetime(2001, 9, 9, 1, 46, 40)),
],
ids=[
"standard_timestamp",
"unix_epoch",
"subsecond_precision",
"negative_timestamp",
"timezone_independence",
],
)
def test_success_cases(self, ts, expected):
"""Verify correct UTC conversion and that the result is offset-naive."""
result = _helpers.utcfromtimestamp(ts)

# 1. Check the datetime value is correct
assert result == expected

# 2. Check it is naive (tzinfo is None) for backward compatibility
assert result.tzinfo is None

@pytest.mark.parametrize(
"invalid_input",
["string", None, [123]],
ids=["type_string", "type_none", "type_list"],
)
def test_invalid_types(self, invalid_input):
"""Verify that passing invalid types raises a TypeError."""
with pytest.raises(TypeError):
_helpers.utcfromtimestamp(invalid_input)

def test_out_of_range(self):
"""Test very large timestamps that exceed platform limits."""
with pytest.raises((OverflowError, OSError, ValueError)):
# Large enough to fail on most systems (Year 300,000+)
_helpers.utcfromtimestamp(9999999999999)
17 changes: 12 additions & 5 deletions tests/test_impersonated_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,10 @@ def test_id_token_success(
id_creds.refresh(request)

assert id_creds.token == ID_TOKEN_DATA
assert id_creds.expiry == datetime.datetime.utcfromtimestamp(ID_TOKEN_EXPIRY)
expected_expiry = datetime.datetime.fromtimestamp(
ID_TOKEN_EXPIRY, tz=datetime.timezone.utc
).replace(tzinfo=None)
assert id_creds.expiry == expected_expiry

def test_id_token_metrics(self, mock_donor_credentials):
credentials = self.make_credentials(lifetime=None)
Expand All @@ -1070,9 +1073,10 @@ def test_id_token_metrics(self, mock_donor_credentials):
id_creds.refresh(None)

assert id_creds.token == ID_TOKEN_DATA
assert id_creds.expiry == datetime.datetime.utcfromtimestamp(
ID_TOKEN_EXPIRY
)
expected_expiry = datetime.datetime.fromtimestamp(
ID_TOKEN_EXPIRY, tz=datetime.timezone.utc
).replace(tzinfo=None)
assert id_creds.expiry == expected_expiry
assert (
mock_post.call_args.kwargs["headers"]["x-goog-api-client"]
== ID_TOKEN_REQUEST_METRICS_HEADER_VALUE
Expand Down Expand Up @@ -1180,7 +1184,10 @@ def test_id_token_with_target_audience(
id_creds.refresh(request)

assert id_creds.token == ID_TOKEN_DATA
assert id_creds.expiry == datetime.datetime.utcfromtimestamp(ID_TOKEN_EXPIRY)
expected_expiry = datetime.datetime.fromtimestamp(
ID_TOKEN_EXPIRY, tz=datetime.timezone.utc
).replace(tzinfo=None)
assert id_creds.expiry == expected_expiry
assert id_creds._include_email is True

def test_id_token_invalid_cred(
Expand Down
4 changes: 2 additions & 2 deletions tests_async/oauth2/test__client_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ async def test_jwt_grant_no_access_token():

@pytest.mark.asyncio
async def test_id_token_jwt_grant():
now = _helpers.utcnow()
now = _helpers.utcnow().astimezone(datetime.timezone.utc)
id_token_expiry = _helpers.datetime_to_secs(now)
id_token = jwt.encode(test_client.SIGNER, {"exp": id_token_expiry}).decode("utf-8")
request = make_request({"id_token": id_token, "extra": "data"})
Expand All @@ -260,7 +260,7 @@ async def test_id_token_jwt_grant():
# Check result
assert token == id_token
# JWT does not store microseconds
now = now.replace(microsecond=0)
now = now.replace(microsecond=0).replace(tzinfo=None)
assert expiry == now
assert extra_data["extra"] == "data"

Expand Down
Loading