Skip to content

Commit da2a778

Browse files
ponyisiCopilot
andauthored
Fail on authentication tokens without expiration (#597)
* Fail on tokens without expiration Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 2e24a67 commit da2a778

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

servicex/servicex_adapter.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,21 @@ def _get_bearer_token_file():
8585
bearer_token = f.read().strip()
8686
return bearer_token
8787

88+
@staticmethod
89+
def _get_token_expiration(token) -> int:
90+
decoded_token = jwt.decode(token, verify=False)
91+
if "exp" not in decoded_token:
92+
raise RuntimeError(
93+
"Authentication token does not have expiration set. "
94+
f"Token data: {decoded_token}"
95+
)
96+
return decoded_token["exp"]
97+
8898
async def _get_authorization(self, force_reauth: bool = False) -> Dict[str, str]:
8999
now = time.time()
90100
if (
91101
self.token
92-
and jwt.decode(self.token, verify=False)["exp"] - now > 60
102+
and self._get_token_expiration(self.token) - now > 60
93103
and not force_reauth
94104
):
95105
# if less than one minute validity, renew
@@ -105,7 +115,7 @@ async def _get_authorization(self, force_reauth: bool = False) -> Dict[str, str]
105115
if (
106116
not self.token
107117
or force_reauth
108-
or float(jwt.decode(self.token, verify=False)["exp"]) - now < 60
118+
or self._get_token_expiration(self.token) - now < 60
109119
):
110120
await self._get_token()
111121
return {"Authorization": f"Bearer {self.token}"}

tests/test_servicex_adapter.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -106,16 +106,18 @@ async def test_get_transforms_wlcg_bearer_token(
106106
)
107107
token_file.close()
108108

109-
os.environ["BEARER_TOKEN_FILE"] = token_file.name
109+
with patch.dict(os.environ, {"BEARER_TOKEN_FILE": token_file.name}):
110+
# Try with no expiration at all
111+
with pytest.raises(RuntimeError):
112+
await servicex.get_transforms()
110113

111-
# Try with an expired token
112-
with pytest.raises(AuthorizationError) as err:
113-
decode.return_value = {"exp": 0.0}
114-
await servicex.get_transforms()
115-
assert "ServiceX access token request rejected:" in str(err.value)
114+
# Try with an expired token
115+
with pytest.raises(AuthorizationError) as err:
116+
decode.return_value = {"exp": 0.0}
117+
await servicex.get_transforms()
118+
assert "ServiceX access token request rejected:" in str(err.value)
116119

117120
os.remove(token_file.name)
118-
del os.environ["BEARER_TOKEN_FILE"]
119121

120122

121123
@pytest.mark.asyncio

0 commit comments

Comments
 (0)