Skip to content
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

python(feature): Allow using openssl certs with REST #181

Merged
merged 1 commit into from
Feb 27, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading