|
| 1 | +# ------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# ------------------------------------ |
| 5 | +# cspell:ignore cafile |
| 6 | +import os |
| 7 | +import urllib.parse |
| 8 | +from typing import Optional, Any |
| 9 | + |
| 10 | +from azure.core.rest import HttpRequest |
| 11 | + |
| 12 | + |
| 13 | +class TokenBindingTransportMixin: |
| 14 | + """Mixin class providing URL validation, CA file tracking, and proxy URL functionality for transport classes.""" |
| 15 | + |
| 16 | + def __init__(self, **kwargs: Any) -> None: |
| 17 | + """Initialize CA file tracking and proxy attributes.""" |
| 18 | + self._ca_file = kwargs.pop("ca_file", None) |
| 19 | + self._ca_data = kwargs.pop("ca_data", None) |
| 20 | + self._proxy_endpoint = kwargs.pop("proxy_endpoint", None) |
| 21 | + self._sni = kwargs.pop("sni", None) |
| 22 | + |
| 23 | + self._ca_file_mtime: Optional[float] = None |
| 24 | + |
| 25 | + if self._ca_file and self._ca_data: |
| 26 | + raise ValueError("Both ca_file and ca_data are set. Only one should be set") |
| 27 | + |
| 28 | + if self._proxy_endpoint: |
| 29 | + self._validate_url(self._proxy_endpoint) |
| 30 | + |
| 31 | + # If we have a ca_file, read it once and store as ca_data |
| 32 | + if self._ca_file: |
| 33 | + self._load_ca_file_to_data() |
| 34 | + |
| 35 | + super().__init__() |
| 36 | + |
| 37 | + def _validate_url(self, url: str) -> None: |
| 38 | + """Validate that a URL meets security requirements for HTTPS connections. |
| 39 | +
|
| 40 | + :param url: The URL to validate. |
| 41 | + :type url: str |
| 42 | + :raises ValueError: If the URL does not meet security requirements. |
| 43 | + """ |
| 44 | + parsed_url = urllib.parse.urlparse(url) |
| 45 | + if parsed_url.scheme != "https": |
| 46 | + raise ValueError(f"Endpoint URL ({url}) must use the 'https' scheme. Got '{parsed_url.scheme}' instead.") |
| 47 | + if parsed_url.username or parsed_url.password: |
| 48 | + raise ValueError(f"Endpoint URL ({url}) must not contain username or password.") |
| 49 | + if parsed_url.fragment: |
| 50 | + raise ValueError(f"Endpoint URL ({url}) must not contain a fragment.") |
| 51 | + if parsed_url.query: |
| 52 | + raise ValueError(f"Endpoint URL ({url}) must not contain query parameters.") |
| 53 | + |
| 54 | + def _load_ca_file_to_data(self) -> None: |
| 55 | + """Load CA file content into ca_data and track modification time. |
| 56 | +
|
| 57 | + :raises ValueError: If the CA file is empty on first read. |
| 58 | + """ |
| 59 | + try: |
| 60 | + with open(self._ca_file, "r", encoding="utf-8") as f: |
| 61 | + content = f.read() |
| 62 | + |
| 63 | + # Check if the file is empty |
| 64 | + if not content: |
| 65 | + # If no prior ca_data exists (first read), fail |
| 66 | + if self._ca_data is None: |
| 67 | + raise ValueError(f"CA file ({self._ca_file}) is empty. Cannot establish secure connection.") |
| 68 | + # If we had prior ca_data, keep it (mid-rotation scenario) |
| 69 | + return |
| 70 | + |
| 71 | + # File has content, update ca_data and tracking |
| 72 | + self._ca_data = content |
| 73 | + self._ca_file_mtime = os.path.getmtime(self._ca_file) |
| 74 | + except (OSError, IOError) as e: |
| 75 | + # If no prior ca_data exists (first read), fail |
| 76 | + if self._ca_data is None: |
| 77 | + raise ValueError(f"Failed to read CA file ({self._ca_file}): {e}") from e |
| 78 | + # If we can't read the file, keep existing ca_data but clear mtime |
| 79 | + # so we'll try to reload on the next change check |
| 80 | + self._ca_file_mtime = None |
| 81 | + |
| 82 | + def _has_ca_file_changed(self) -> bool: |
| 83 | + """Check if the CA file has changed since last load. |
| 84 | +
|
| 85 | + :return: True if the CA file has changed, False otherwise. |
| 86 | + :rtype: bool |
| 87 | + """ |
| 88 | + if not self._ca_file: |
| 89 | + return False |
| 90 | + |
| 91 | + if not os.path.exists(self._ca_file): |
| 92 | + # File was deleted, consider this a change if we had data before |
| 93 | + return self._ca_data is not None or self._ca_file_mtime is not None |
| 94 | + |
| 95 | + try: |
| 96 | + # Check modification time |
| 97 | + current_mtime = os.path.getmtime(self._ca_file) |
| 98 | + return self._ca_file_mtime != current_mtime |
| 99 | + except (OSError, IOError): |
| 100 | + # If we can't read the file stats, assume it changed |
| 101 | + return True |
| 102 | + |
| 103 | + def _update_request_url(self, request: HttpRequest) -> None: |
| 104 | + """Update the request URL to use proxy endpoint if configured. |
| 105 | +
|
| 106 | + :param request: The HTTP request object to update. |
| 107 | + :type request: ~azure.core.rest.HttpRequest |
| 108 | + """ |
| 109 | + if self._proxy_endpoint: |
| 110 | + parsed_request_url = urllib.parse.urlparse(request.url) |
| 111 | + parsed_proxy_url = urllib.parse.urlparse(self._proxy_endpoint) |
| 112 | + combined_path = parsed_proxy_url.path.rstrip("/") + "/" + parsed_request_url.path.lstrip("/") |
| 113 | + new_url = urllib.parse.urlunparse( |
| 114 | + ( |
| 115 | + parsed_proxy_url.scheme, |
| 116 | + parsed_proxy_url.netloc, |
| 117 | + combined_path, |
| 118 | + parsed_request_url.params, |
| 119 | + parsed_request_url.query, |
| 120 | + parsed_request_url.fragment, |
| 121 | + ) |
| 122 | + ) |
| 123 | + request.url = new_url |
0 commit comments