Repository navigation
feat(temporal): add workload identity authentication #560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
mzohaib-scale
wants to merge
3
commits into
scaleapi:main
from
mzohaib-scale:VULN-2040/temporal-authentication
+415
−20
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| """Renewable Azure Workload Identity authentication for Temporal clients.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import time | ||
| import asyncio | ||
| import logging | ||
| from typing import Any, Protocol | ||
| from dataclasses import field, dataclass | ||
| from collections.abc import Callable, Awaitable | ||
|
|
||
| from temporalio.client import Client | ||
| from azure.identity.aio import WorkloadIdentityCredential | ||
| from azure.core.credentials import AccessToken | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _AUTH_SCOPE_ENV = "TEMPORAL_AUTH_SCOPE" | ||
| _REFRESH_MARGIN_SECONDS = 300 | ||
| _MIN_REFRESH_DELAY_SECONDS = 30 | ||
| _RETRY_DELAY_SECONDS = 30 | ||
|
|
||
|
|
||
| class AsyncTokenCredential(Protocol): | ||
| async def get_token(self, *scopes: str) -> AccessToken: ... | ||
|
|
||
| async def close(self) -> None: ... | ||
|
|
||
|
|
||
| @dataclass(eq=False) | ||
| class TemporalTokenSession: | ||
| """Keep a Temporal client's bearer token current for the process lifetime.""" | ||
|
|
||
| client: Client | ||
| credential: AsyncTokenCredential | ||
| scope: str | ||
| token: AccessToken | ||
| now: Callable[[], float] = time.time | ||
| sleep: Callable[[float], Awaitable[None]] = asyncio.sleep | ||
| _task: asyncio.Task[None] | None = field(default=None, init=False) | ||
|
|
||
| def start(self) -> None: | ||
| self._task = asyncio.create_task(self._run()) | ||
| _ACTIVE_SESSIONS.add(self) | ||
| self._task.add_done_callback(lambda _: _ACTIVE_SESSIONS.discard(self)) | ||
|
|
||
| async def refresh_once(self) -> bool: | ||
| """Replace the token only after a valid refresh succeeds.""" | ||
| try: | ||
| refreshed = await self.credential.get_token(self.scope) | ||
| if refreshed.expires_on <= self.now(): | ||
| raise ValueError("Azure returned an expired Temporal access token") | ||
| except Exception: | ||
| log = logger.error if self.token.expires_on <= self.now() else logger.warning | ||
| log("Temporal access token refresh failed; retaining the current token", exc_info=True) | ||
| return False | ||
|
|
||
| self.client.api_key = refreshed.token | ||
| self.token = refreshed | ||
| return True | ||
|
|
||
| async def _run(self) -> None: | ||
| try: | ||
| delay = max( | ||
| _MIN_REFRESH_DELAY_SECONDS, | ||
| self.token.expires_on - self.now() - _REFRESH_MARGIN_SECONDS, | ||
| ) | ||
| while True: | ||
| await self.sleep(delay) | ||
| delay = ( | ||
| max( | ||
| _MIN_REFRESH_DELAY_SECONDS, | ||
| self.token.expires_on - self.now() - _REFRESH_MARGIN_SECONDS, | ||
| ) | ||
| if await self.refresh_once() | ||
| else _RETRY_DELAY_SECONDS | ||
| ) | ||
| finally: | ||
| await self.credential.close() | ||
|
|
||
|
|
||
| _ACTIVE_SESSIONS: set[TemporalTokenSession] = set() | ||
|
|
||
|
|
||
| async def connect_temporal_client(connect_options: dict[str, Any]) -> Client: | ||
| """Connect anonymously by default, or with renewable Workload Identity.""" | ||
| scope = os.environ.get(_AUTH_SCOPE_ENV) | ||
| if not scope: | ||
| return await Client.connect(**connect_options) | ||
|
|
||
| credential = WorkloadIdentityCredential() | ||
| try: | ||
| token = await credential.get_token(scope) | ||
| if token.expires_on <= time.time(): | ||
| raise ValueError("Azure returned an expired Temporal access token") | ||
| authenticated_options = dict(connect_options) | ||
| if authenticated_options.get("tls") is None: | ||
| authenticated_options["tls"] = False | ||
| client = await Client.connect(api_key=token.token, **authenticated_options) | ||
|
mzohaib-scale marked this conversation as resolved.
Resolved
|
||
| except Exception: | ||
| await credential.close() | ||
| raise | ||
|
|
||
| TemporalTokenSession( | ||
| client=client, | ||
| credential=credential, | ||
| scope=scope, | ||
| token=token, | ||
| ).start() | ||
| return client | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.