-
Notifications
You must be signed in to change notification settings - Fork 4
feat(webdav): add bearer_token_command for dynamic token acquisition #95
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
Merged
skshetry
merged 9 commits into
treeverse:main
from
GreenHatHG:feat/webdav-dynamic-token-command
Dec 5, 2025
Merged
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2a40b8d
feat(webdav): add bearer_token_command config for dynamic token retri…
6b06f7f
refactor(dvc_webdav): ensure BearerAuthClient is initialized only once
da92966
refactor: fix linter warnings
17c381f
refactor(webdav): remove token persistence logic to enforce in-memory…
83636e0
feat(webdav): refactor Bearer auth to use httpx.Auth with automatic 4…
773944a
fix(dvc_webdav): remove manual response body reading in BearerAuth
9817666
tests(BearerAuth): add test cases
cf26794
tests(BearerAuth): remove excessive bearer_auth test cases
1f629db
test: add pytest-mock as test dependency
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,161 @@ | ||
| import logging | ||
| import shlex | ||
| import subprocess | ||
| import sys | ||
| import threading | ||
| from typing import Optional, Union | ||
|
|
||
| import httpx | ||
|
|
||
| logger = logging.getLogger("dvc") | ||
|
|
||
|
|
||
| def _log_with_thread(level: int, msg: str, *args) -> None: | ||
| """ | ||
| Universal helper to inject thread identity into logs. | ||
| Output format: [Thread-Name] Message... | ||
| """ | ||
| if logger.isEnabledFor(level): | ||
| thread_name = threading.current_thread().name | ||
| log_fmt = f"[{thread_name}] " + msg | ||
| logger.log(level, log_fmt, *args) | ||
|
|
||
|
|
||
| def execute_command(command: Union[list[str], str], timeout: int = 10) -> str: | ||
| """Executes a command to retrieve the token.""" | ||
| if isinstance(command, str): | ||
| command = shlex.split(command) | ||
|
|
||
| try: | ||
| result = subprocess.run( # noqa: S603 | ||
| command, | ||
| shell=False, | ||
| capture_output=True, | ||
| text=True, | ||
| check=True, | ||
| timeout=timeout, | ||
| encoding="utf-8", | ||
| ) | ||
| except ( | ||
| FileNotFoundError, | ||
| subprocess.TimeoutExpired, | ||
| subprocess.CalledProcessError, | ||
| ValueError, | ||
| OSError, | ||
| ) as e: | ||
| error_header = "\n" + "=" * 60 | ||
| error_msg = ( | ||
| f"{error_header}\n[CRITICAL] Bearer Token Retrieval Failed.\n" | ||
| "DVC may misinterpret this as 'File Not Found' and skip files.\n" | ||
| f"Command: {command}\n" | ||
| f"Error: {e}" | ||
| ) | ||
|
|
||
| if isinstance(e, subprocess.CalledProcessError): | ||
| error_msg += f"\nStderr: {e.stderr.strip()}" | ||
|
|
||
| error_msg += f"\n{error_header}\n" | ||
|
|
||
| logger.critical(error_msg) | ||
| sys.stderr.write(error_msg) | ||
| sys.stderr.flush() | ||
|
|
||
| # Re-raise the exception so the caller knows it failed. | ||
| # DVC might catch this and swallow it, but we've done our duty to notify. | ||
| raise | ||
|
|
||
| token = result.stdout.strip() | ||
| if not token: | ||
| raise ValueError("Command executed successfully but returned an empty token.") | ||
| return token | ||
|
|
||
|
|
||
| class BearerAuthClient(httpx.Client): | ||
| """HTTPX client that adds Bearer token authentication using a command. | ||
|
|
||
| Args: | ||
| bearer_token_command: The command to run to get the Bearer token. | ||
| **kwargs: Additional arguments to pass to the httpx.Client constructor. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| bearer_token_command: str, | ||
| **kwargs, | ||
| ): | ||
| super().__init__(**kwargs) | ||
| if ( | ||
| not isinstance(bearer_token_command, str) | ||
| or not bearer_token_command.strip() | ||
| ): | ||
| raise ValueError( | ||
| "[BearerAuthClient] bearer_token_command must be a non-empty string" | ||
| ) | ||
| self.bearer_token_command = bearer_token_command | ||
| self._token: Optional[str] = None | ||
| self._lock = threading.Lock() | ||
|
|
||
| def _refresh_token(self) -> None: | ||
| """Execute token command and update state.""" | ||
| _log_with_thread( | ||
| logging.DEBUG, "[BearerAuthClient] Refreshing token via command..." | ||
| ) | ||
|
|
||
| try: | ||
| new_token = execute_command(self.bearer_token_command) | ||
| # execute_command guarantees non-empty string or raises ValueError | ||
|
|
||
| self._token = new_token | ||
| self.headers["Authorization"] = f"Bearer {new_token}" | ||
|
|
||
| _log_with_thread( | ||
| logging.DEBUG, "[BearerAuthClient] Token refreshed successfully." | ||
| ) | ||
| except Exception: | ||
| # Clean up state on failure | ||
| self._token = None | ||
| raise | ||
|
|
||
| def _ensure_token(self) -> None: | ||
| """Ensure a token exists before making requests""" | ||
| if self._token: | ||
| return | ||
|
|
||
| with self._lock: | ||
| if not self._token: | ||
| self._refresh_token() | ||
|
|
||
| def request(self, *args, **kwargs) -> httpx.Response: | ||
| """Wraps httpx.request with auto-refresh logic for 401 Unauthorized.""" | ||
| self._ensure_token() | ||
| response = super().request(*args, **kwargs) | ||
|
|
||
| if response.status_code != 401: | ||
| return response | ||
|
|
||
| _log_with_thread( | ||
| logging.DEBUG, "[BearerAuthClient] Received 401. Attempting recovery." | ||
| ) | ||
| sent_auth_header = response.request.headers.get("Authorization") | ||
|
|
||
| try: | ||
| with self._lock: | ||
| current_auth_header = self.headers.get("Authorization") | ||
| if sent_auth_header == current_auth_header: | ||
| self._refresh_token() | ||
| else: | ||
| _log_with_thread( | ||
| logging.DEBUG, | ||
| "[BearerAuthClient] Token already refreshed by another thread. " | ||
| "Retrying.", | ||
| ) | ||
| except Exception: | ||
| logger.exception( | ||
| "[BearerAuthClient] Recovery failed: Token refresh threw exception" | ||
| ) | ||
| return response | ||
|
|
||
| # Retry the request with the new valid token | ||
| # We must close the old 401 response to free connections | ||
| response.close() | ||
| return super().request(*args, **kwargs) | ||
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.