Skip to content
Draft
Show file tree
Hide file tree
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
92 changes: 74 additions & 18 deletions mailjet_rest/__init__.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,47 @@
"""Mailjet REST API Python Wrapper."""

from mailjet_rest.client import Client, Config
from mailjet_rest.errors import (
ActionDeniedError,
ApiError,
ApiRateLimitError,
AuthorizationError,
CriticalApiError,
DoesNotExistError,
MailjetApiError,
MailjetAuthError,
MailjetNetworkError,
TimeoutError, # ruff: ignore[builtin-import-shadowing]
ValidationError,
)
from mailjet_rest.utils.version import get_version


__version__: str = get_version()
from __future__ import annotations

import importlib
from typing import TYPE_CHECKING, Any


if TYPE_CHECKING:
from mailjet_rest.client import Client, Config
from mailjet_rest.errors import (
ActionDeniedError,
ApiError,
ApiRateLimitError,
AuthorizationError,
CriticalApiError,
DoesNotExistError,
MailjetApiError,
MailjetAuthError,
MailjetNetworkError,
TimeoutError, # ruff: ignore[builtin-import-shadowing]
ValidationError,
)
from mailjet_rest.utils.version import get_version

__version__: str


_LAZY_EXPORTS: dict[str, tuple[str, str]] = {
"ActionDeniedError": ("mailjet_rest.errors", "ActionDeniedError"),
"ApiError": ("mailjet_rest.errors", "ApiError"),
"ApiRateLimitError": ("mailjet_rest.errors", "ApiRateLimitError"),
"AuthorizationError": ("mailjet_rest.errors", "AuthorizationError"),
"Client": ("mailjet_rest.client", "Client"),
"Config": ("mailjet_rest.client", "Config"),
"CriticalApiError": ("mailjet_rest.errors", "CriticalApiError"),
"DoesNotExistError": ("mailjet_rest.errors", "DoesNotExistError"),
"MailjetApiError": ("mailjet_rest.errors", "MailjetApiError"),
"MailjetAuthError": ("mailjet_rest.errors", "MailjetAuthError"),
"MailjetNetworkError": ("mailjet_rest.errors", "MailjetNetworkError"),
"TimeoutError": ("mailjet_rest.errors", "TimeoutError"),
"ValidationError": ("mailjet_rest.errors", "ValidationError"),
"get_version": ("mailjet_rest.utils.version", "get_version"),
}

__all__ = [
"ActionDeniedError",
Expand All @@ -35,3 +59,35 @@
"ValidationError",
"get_version",
]


def __getattr__(name: str) -> Any:
"""Resolve top-level SDK exports lazily via PEP 562.

Returns:
Any: The resolved class, function, or version string.
"""
if name == "__version__":
version_mod = importlib.import_module("mailjet_rest.utils.version")
value = version_mod.get_version()
globals()[name] = value
return value

target = _LAZY_EXPORTS.get(name)
if target is None:
msg = f"module 'mailjet_rest' has no attribute {name!r}"
raise AttributeError(msg)

module_name, attr_name = target
value = getattr(importlib.import_module(module_name), attr_name)
globals()[name] = value
return value


def __dir__() -> list[str]:
"""Return top-level exports including lazy attributes for introspection tools.

Returns:
list[str]: Sorted list of exposed attributes.
"""
return sorted({*globals(), *__all__, "__version__"})
17 changes: 14 additions & 3 deletions mailjet_rest/builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import base64
import errno
import json
import mimetypes
import os
import stat
import sys
Expand All @@ -30,6 +29,8 @@
class ChunkedStreamer:
"""Generator for encoding large file attachments."""

__slots__ = ()

@staticmethod
def encode_file(
path: str | Path,
Expand Down Expand Up @@ -254,7 +255,12 @@ def attach_file(
target = SecurityGuard.validate_attachment_path(file_path, base_dir)
SecurityGuard.check_file_size(target)

ctype = content_type or mimetypes.guess_type(target)[0] or "application/octet-stream"
if content_type is not None:
ctype = content_type
else:
import mimetypes # ruff: ignore[import-outside-top-level]

ctype = mimetypes.guess_type(target)[0] or "application/octet-stream"

if "Attachments" not in self._payload:
self._payload["Attachments"] = []
Expand All @@ -279,7 +285,12 @@ def attach_inline(
target = SecurityGuard.validate_attachment_path(file_path, base_dir)
SecurityGuard.check_file_size(target)

ctype = content_type or mimetypes.guess_type(target)[0] or "application/octet-stream"
if content_type is not None:
ctype = content_type
else:
import mimetypes # ruff: ignore[import-outside-top-level]

ctype = mimetypes.guess_type(target)[0] or "application/octet-stream"

if "InlinedAttachments" not in self._payload:
self._payload["InlinedAttachments"] = []
Expand Down
91 changes: 67 additions & 24 deletions mailjet_rest/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from __future__ import annotations

import difflib
import logging
import secrets
import sys
Expand Down Expand Up @@ -98,6 +97,8 @@ class Client:
endpoint attributes based on the static routing registry.
"""

__slots__ = ("_closed", "_endpoint_cache", "_lock", "_session", "auth", "config")

_MUTATING_METHODS: ClassVar[frozenset[str]] = frozenset({"POST", "PUT", "PATCH", "DELETE"})

_RETRY_STRATEGY: ClassVar[JitterRetry] = JitterRetry(
Expand Down Expand Up @@ -138,37 +139,61 @@ def __init__(

self._lock = threading.RLock()
self._closed = False
self._session: requests.Session | None = None
self._endpoint_cache: dict[str, Endpoint] = {}
self.config = Config(**kwargs) if config is None else config
self.session = requests.Session()
resolved_verify = SecurityGuard.resolve_tls_verify(self.config.verify)
self.session.verify = resolved_verify
SecurityGuard.resolve_tls_verify(self.config.verify)

# Delegate auth validation and coercion to SecurityGuard
self.auth = SecurityGuard.validate_and_coerce_auth(auth)

if getattr(self.config, "enable_security_audit", False):
SecurityGuard.enable_audit_logging()

def _build_session(self) -> requests.Session:
resolved_verify = SecurityGuard.resolve_tls_verify(self.config.verify)
session = requests.Session()
session.verify = resolved_verify

session.auth = self.auth if isinstance(self.auth, SecretAuth) else None
if isinstance(self.auth, str):
self.session.auth = None
self.session.headers.update({"Authorization": f"Bearer {self.auth}"})
elif isinstance(self.auth, SecretAuth):
self.session.auth = self.auth
else:
self.session.auth = None # type: ignore[unreachable]
session.headers.update({"Authorization": f"Bearer {self.auth}"})

self.session.headers.update({"User-Agent": self.config.user_agent})
session.headers.update({"User-Agent": self.config.user_agent})

ca_bundle = resolved_verify if isinstance(resolved_verify, str) else None
adapter = SecureHTTPAdapter(
ca_bundle=ca_bundle,
pool_connections=100,
pool_maxsize=100,
pool_connections=self.config.pool_connections,
pool_maxsize=self.config.pool_maxsize,
max_retries=self._RETRY_STRATEGY,
)
self.session.mount("https://", adapter)
session.mount("https://", adapter)
return session

self._endpoint_cache: dict[str, Endpoint] = {}
@property
def session(self) -> requests.Session:
"""Lazily create and return the underlying thread-safe HTTP session.

if getattr(self.config, "enable_security_audit", False):
SecurityGuard.enable_audit_logging()
Returns:
requests.Session: The configured session instance.
"""
with self._lock:
if self._session is None:
if self._closed:
closed_session = requests.Session()
closed_session.auth = None
closed_session.headers.clear()
closed_session.close()
self._session = closed_session
else:
self._session = self._build_session()
return self._session

@session.setter
def session(self, value: requests.Session | None) -> None:
with self._lock:
self._session = value

def __enter__(self) -> Self:
"""Enter the context manager and return the client instance.
Expand Down Expand Up @@ -213,12 +238,28 @@ def close(self) -> None:
"""Secure resource teardown closing internal sockets."""
with self._lock:
self._closed = True
session = getattr(self, "session", None)
session = self._session
if session is not None:
session.auth = None
session.headers.clear()
session.close()

def __del__(self) -> None:
"""Optionally emit ResourceWarning on GC teardown when Config.warn_unclosed is enabled."""
try:
cfg = object.__getattribute__(self, "config")
session = object.__getattribute__(self, "_session")
closed = object.__getattribute__(self, "_closed")
except (OSError, RuntimeError, AttributeError):
return

if getattr(cfg, "warn_unclosed", False) and session is not None and not closed:
warnings.warn(
"Unclosed Mailjet Client session; call client.close() or use a context manager.",
ResourceWarning,
stacklevel=2,
)

def __getattr__(self, name: str) -> Endpoint:
"""O(1) Route mapping.

Expand All @@ -238,9 +279,12 @@ def __getattr__(self, name: str) -> Endpoint:
# Fail fast for typos: Only check simple un-composited names.
# A cutoff of 0.8 catches obvious mistakes like 'snd'->'send' or 'session'->'session',
# but allows legitimate dynamic endpoints to pass through to the fallback.
if "_" not in name and name not in ROUTE_MAP and difflib.get_close_matches(name, dir(self), n=1, cutoff=0.8):
msg = f"'{self.__class__.__name__}' has no endpoint or attribute '{name}'."
raise AttributeError(msg)
if "_" not in name and name not in ROUTE_MAP:
import difflib # ruff: ignore[import-outside-top-level]

if difflib.get_close_matches(name, dir(self), n=1, cutoff=0.8):
msg = f"'{self.__class__.__name__}' has no endpoint or attribute '{name}'."
raise AttributeError(msg)

# If it doesn't exist, we fall back to assuming it's a dynamic path
# which will be safely encoded by sanitize_segment during _build_url
Expand Down Expand Up @@ -416,8 +460,6 @@ def api_call( # ruff: ignore[complex-structure]
# Strip None filters
clean_filters = {k: v for k, v in filters.items() if v is not None} if filters else None

trace_suffix, _ = self._extract_telemetry(data, req_headers)

try:
response = self._execute_request(
method=method,
Expand All @@ -443,7 +485,8 @@ def api_call( # ruff: ignore[complex-structure]
self._handle_api_error(e)

else:
if response.status_code in {200, 201, 204}:
if response.status_code in {200, 201, 204} and logger.isEnabledFor(logging.DEBUG):
trace_suffix, _ = self._extract_telemetry(data, req_headers)
self._log_request(method, url, response, trace_suffix)
return response

Expand Down
20 changes: 20 additions & 0 deletions mailjet_rest/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class Config:
enable_security_audit (bool): Enable runtime PEP 578 security audit event emission.
verify (bool | str | Path): TLS verification setting or path to a custom CA bundle.
auto_idempotency_mode (AutoIdempotencyMode): Strategy for auto-populating Idempotency-Key.
pool_connections (int): Number of urllib3 connection pools to cache per Client.
pool_maxsize (int): Maximum number of persistent connections saved per pool.
warn_unclosed (bool): Emit ResourceWarning on garbage collection if session was not closed.
"""

ALLOWED_ROOT_DOMAIN: ClassVar[str] = "mailjet.com"
Expand All @@ -38,6 +41,15 @@ class Config:
enable_security_audit: bool = False
verify: bool | str | Path = True
auto_idempotency_mode: AutoIdempotencyMode = "fingerprint"
pool_connections: int = 100
pool_maxsize: int = 100
warn_unclosed: bool = False

@staticmethod
def _validate_pool_size(name: str, value: int) -> None:
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
msg = f"{name} must be an integer >= 1, got {value!r}."
raise ValueError(msg)

def __post_init__(self) -> None:
"""Validate configuration for secure transport and resource limits (OWASP Input Validation)."""
Expand All @@ -58,3 +70,11 @@ def __post_init__(self) -> None:
if self.auto_idempotency_mode not in _VALID_IDEMPOTENCY_MODES:
msg = f"Invalid auto_idempotency_mode {self.auto_idempotency_mode!r}; expected one of {sorted(_VALID_IDEMPOTENCY_MODES)}."
raise ValueError(msg)

# 5. Validate connection pool bounds and warning flags
self._validate_pool_size("pool_connections", self.pool_connections)
self._validate_pool_size("pool_maxsize", self.pool_maxsize)
raw_warn: object = self.warn_unclosed
if not isinstance(raw_warn, bool):
msg = f"warn_unclosed must be a bool, got {type(raw_warn).__name__}."
raise TypeError(msg)
4 changes: 1 addition & 3 deletions mailjet_rest/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,7 @@ def _build_headers(self, custom_headers: Mapping[str, str | None] | None = None)

if custom_headers:
clean_custom = SecurityGuard.sanitize_headers(dict(custom_headers))
merged: dict[str, str | None] = dict(base_headers)
merged.update(clean_custom)
return merged
return {**base_headers, **clean_custom}
return dict(base_headers)

@staticmethod
Expand Down
2 changes: 1 addition & 1 deletion mailjet_rest/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
_DEFAULT_TIMEOUT: Final[int] = 60
_JSON_HEADERS: Final = MappingProxyType({"Content-Type": "application/json"})
_TEXT_HEADERS: Final = MappingProxyType({"Content-Type": "text/plain"})
_ALLOWED_TRACE_FIELDS: Final[set[str]] = {"CustomID", "TemplateID"}
_ALLOWED_TRACE_FIELDS: Final[frozenset[str]] = frozenset({"CustomID", "TemplateID"})


class EmailAddress(TypedDict):
Expand Down
Loading
Loading