Skip to content

Commit

Permalink
python(feature): Allow using openssl certs with REST (#181)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcsiftstack authored Feb 27, 2025
1 parent 59fb28d commit 2a18380
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion python/lib/sift_py/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@ class SiftRestConfig(TypedDict):
- `apikey`: User-generated API key generated via the Sift application.
- `retry`: Urllib3 Retry configuration. If not provided, a default of 3 retries is used.
- `use_ssl`: INTERNAL USE. Meant to be used for local development.
- `cert_via_openssl`: Enable this if you want to use OpenSSL to load the certificates.
Run `pip install sift-stack-py[openssl]` to install the dependencies required to use this option.
Default is False.
"""

uri: str
apikey: str
retry: NotRequired[Retry]
use_ssl: NotRequired[bool]
cert_via_openssl: NotRequired[bool]


def compute_uri(restconf: SiftRestConfig) -> str:
Expand All @@ -37,6 +41,29 @@ def compute_uri(restconf: SiftRestConfig) -> str:
return f"http://{clean_uri}"


class _SiftHTTPAdapter(HTTPAdapter):
"""Sift specific HTTP adapter."""

def __init__(self, rest_conf: SiftRestConfig, *args, **kwargs):
self._rest_conf = rest_conf
kwargs["max_retries"] = rest_conf.get("retry", _DEFAULT_REST_RETRY)
super().__init__(*args, **kwargs)

def init_poolmanager(self, *args, **kwargs):
if self._rest_conf.get("cert_via_openssl", False):
try:
import ssl

context = ssl.create_default_context()
context.load_default_certs()
kwargs["ssl_context"] = context
except ImportError as e:
raise Exception(
"Missing required dependencies for cert_via_openssl. Run `pip install sift-stack-py[openssl]` to install the required dependencies."
) from e
return super().init_poolmanager(*args, **kwargs)


class _RestService(ABC):
"""
Abstract service that implements a REST session.
Expand All @@ -49,6 +76,7 @@ def __init__(self, rest_conf: SiftRestConfig):

self._session = requests.Session()
self._session.headers = {"Authorization": f"Bearer {self._apikey}"}
adapter = HTTPAdapter(max_retries=rest_conf.get("retry", _DEFAULT_REST_RETRY))

adapter = _SiftHTTPAdapter(rest_conf)
self._session.mount("https://", adapter)
self._session.mount("http://", adapter)

0 comments on commit 2a18380

Please sign in to comment.