Initial production analytics foundation
This commit is contained in:
commit
f017d187eb
30 files changed
+1219
No files matched your search
@@ -0,0 +1,6 @@
|
||||
"""ENLYZE adapter boundary; concrete API behavior awaits verification."""
|
||||
|
||||
from .exploration import ExplorationClient, ExplorationSettings, load_secret_file
|
||||
from .ports import EnlyzeGateway
|
||||
|
||||
__all__ = ["EnlyzeGateway", "ExplorationClient", "ExplorationSettings", "load_secret_file"]
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Small, read-only HTTP boundary for observing an unverified ENLYZE API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Mapping
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode, urljoin, urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
class ExplorationError(RuntimeError):
|
||||
"""Base error whose message is safe to show to an operator."""
|
||||
|
||||
|
||||
class ConfigurationError(ExplorationError):
|
||||
"""Raised when local exploration configuration is incomplete or unsafe."""
|
||||
|
||||
|
||||
class AuthenticationError(ExplorationError):
|
||||
"""Raised for HTTP 401/403 without exposing credentials or response bodies."""
|
||||
|
||||
|
||||
class HttpResponseError(ExplorationError):
|
||||
"""Raised for a non-successful HTTP response."""
|
||||
|
||||
|
||||
class NonJsonResponseError(ExplorationError):
|
||||
"""Raised when a successful response cannot be decoded as JSON."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExplorationSettings:
|
||||
"""Local HTTP settings for documented ENLYZE Bearer-token access."""
|
||||
|
||||
base_url: str
|
||||
timeout_seconds: float = 20.0
|
||||
api_key: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls, environment: Mapping[str, str] | None = None) -> ExplorationSettings:
|
||||
environment = environment or os.environ
|
||||
base_url = environment.get("ENLYZE_BASE_URL", "").strip()
|
||||
api_key = environment.get("ENLYZE_API_KEY", "").strip() or None
|
||||
timeout_value = environment.get("ENLYZE_HTTP_TIMEOUT_SECONDS", "20")
|
||||
|
||||
if not base_url:
|
||||
raise ConfigurationError("ENLYZE_BASE_URL must be set for API exploration.")
|
||||
try:
|
||||
timeout_seconds = float(timeout_value)
|
||||
except ValueError as error:
|
||||
raise ConfigurationError("ENLYZE_HTTP_TIMEOUT_SECONDS must be a number.") from error
|
||||
if timeout_seconds <= 0:
|
||||
raise ConfigurationError("ENLYZE_HTTP_TIMEOUT_SECONDS must be greater than zero.")
|
||||
return cls(base_url.rstrip("/") + "/", timeout_seconds, api_key)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExplorationResponse:
|
||||
"""JSON response plus safe metadata useful for API investigation."""
|
||||
|
||||
status_code: int
|
||||
path: str
|
||||
headers: Mapping[str, str]
|
||||
body: Any
|
||||
|
||||
|
||||
class ExplorationClient:
|
||||
"""Client for documented, read-only exploration operations."""
|
||||
|
||||
def __init__(self, settings: ExplorationSettings) -> None:
|
||||
self._settings = settings
|
||||
|
||||
def get(self, path: str, query: Mapping[str, str] | None = None) -> ExplorationResponse:
|
||||
"""Request one relative path and decode its JSON response."""
|
||||
return self._request_json("GET", path, query=query)
|
||||
|
||||
def post_json(self, path: str, payload: Mapping[str, Any]) -> ExplorationResponse:
|
||||
"""Issue a documented read-only POST operation with a JSON body."""
|
||||
return self._request_json("POST", path, payload=payload)
|
||||
|
||||
def _request_json(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
query: Mapping[str, str] | None = None,
|
||||
payload: Mapping[str, Any] | None = None,
|
||||
) -> ExplorationResponse:
|
||||
parsed_path = urlsplit(path)
|
||||
if (
|
||||
not path.startswith("/")
|
||||
or path.startswith("//")
|
||||
or parsed_path.scheme
|
||||
or parsed_path.netloc
|
||||
or ".." in parsed_path.path.split("/")
|
||||
):
|
||||
raise ConfigurationError("PATH must be a relative path beginning with one slash.")
|
||||
|
||||
encoded_query = urlencode(query or {})
|
||||
request_path = f"{path}?{encoded_query}" if encoded_query else path
|
||||
request_url = urljoin(self._settings.base_url, request_path.lstrip("/"))
|
||||
request_headers = {"Accept": "application/json"}
|
||||
request_body = None
|
||||
if payload is not None:
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
request_body = json.dumps(payload).encode("utf-8")
|
||||
if self._settings.api_key:
|
||||
request_headers["Authorization"] = f"Bearer {self._settings.api_key}"
|
||||
|
||||
request = Request(request_url, data=request_body, headers=request_headers, method=method)
|
||||
try:
|
||||
with urlopen(request, timeout=self._settings.timeout_seconds) as response: # noqa: S310
|
||||
raw_body = response.read()
|
||||
status_code = response.status
|
||||
response_headers = dict(response.headers.items())
|
||||
except HTTPError as error:
|
||||
if error.code in {401, 403}:
|
||||
raise AuthenticationError(f"Authentication or authorization failed (HTTP {error.code}).") from error
|
||||
raise HttpResponseError(f"HTTP request failed with status {error.code}.") from error
|
||||
except URLError as error:
|
||||
raise HttpResponseError("HTTP request could not be completed.") from error
|
||||
|
||||
try:
|
||||
body = json.loads(raw_body)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
content_type = response_headers.get("Content-Type", "unknown")
|
||||
raise NonJsonResponseError(
|
||||
f"Expected a JSON response; received Content-Type {content_type!r}."
|
||||
) from error
|
||||
|
||||
return ExplorationResponse(status_code, request_path, response_headers, body)
|
||||
|
||||
|
||||
def load_secret_file(path: str | os.PathLike[str]) -> dict[str, str]:
|
||||
"""Read simple dotenv-style assignments without executing local secret content."""
|
||||
secrets: dict[str, str] = {}
|
||||
try:
|
||||
lines = open(path, encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return secrets
|
||||
with lines:
|
||||
for line_number, line in enumerate(lines, start=1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
if stripped.startswith("export "):
|
||||
stripped = stripped.removeprefix("export ").lstrip()
|
||||
if "=" not in stripped:
|
||||
raise ConfigurationError(f"Invalid secret-file assignment on line {line_number}.")
|
||||
key, raw_value = stripped.split("=", 1)
|
||||
key = key.strip()
|
||||
if not key.isidentifier():
|
||||
raise ConfigurationError(f"Invalid secret-file variable name on line {line_number}.")
|
||||
try:
|
||||
parsed = shlex.split(raw_value, comments=True, posix=True)
|
||||
except ValueError as error:
|
||||
raise ConfigurationError(f"Invalid secret-file value on line {line_number}.") from error
|
||||
if len(parsed) > 1:
|
||||
raise ConfigurationError(f"Invalid secret-file value on line {line_number}.")
|
||||
secrets[key] = parsed[0] if parsed else ""
|
||||
return secrets
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Ports intentionally avoid unverified ENLYZE endpoint or payload assumptions."""
|
||||
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
class EnlyzeGateway(Protocol):
|
||||
"""Marker for a verified ENLYZE adapter, defined after API exploration."""
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Conservative sanitization for reviewable API fixtures and CLI output."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
_SECRET_KEY = re.compile(
|
||||
r"(?:authorization|token|api[_-]?key|password|secret|cookie|credential|session)", re.IGNORECASE
|
||||
)
|
||||
_IDENTIFIER_KEY = re.compile(r"(?:^|[_-])(id|uuid|guid)(?:$|[_-])", re.IGNORECASE)
|
||||
_SENSITIVE_TEXT_KEY = re.compile(
|
||||
r"(?:email|phone|first[_-]?name|last[_-]?name|full[_-]?name|user[_-]?name|customer|site|tenant|name)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_HOST_KEY = re.compile(r"(?:host|hostname|base[_-]?url|url|uri|endpoint)", re.IGNORECASE)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _SanitizationContext:
|
||||
identifiers: dict[tuple[str, str], str | int] = field(default_factory=dict)
|
||||
|
||||
def replacement_identifier(self, key: str, value: object) -> str | int:
|
||||
original = str(value)
|
||||
identity = (key.lower(), original)
|
||||
if identity not in self.identifiers:
|
||||
number = len(self.identifiers) + 1
|
||||
self.identifiers[identity] = 1000 + number if isinstance(value, int) else f"redacted-{key}-{number}"
|
||||
return self.identifiers[identity]
|
||||
|
||||
|
||||
def sanitize(value: Any) -> Any:
|
||||
"""Return a structurally equivalent value with common sensitive fields replaced."""
|
||||
return _sanitize(value, _SanitizationContext())
|
||||
|
||||
|
||||
def _sanitize(value: Any, context: _SanitizationContext(), key: str | None = None) -> Any:
|
||||
if isinstance(value, Mapping):
|
||||
return {str(item_key): _sanitize(item_value, context, str(item_key)) for item_key, item_value in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_sanitize(item, context, key) for item in value]
|
||||
if isinstance(value, tuple):
|
||||
return [_sanitize(item, context, key) for item in value]
|
||||
if key and _SECRET_KEY.search(key):
|
||||
return "<redacted-secret>"
|
||||
if key and _IDENTIFIER_KEY.search(key) and isinstance(value, (str, int)) and not isinstance(value, bool):
|
||||
return context.replacement_identifier(key, value)
|
||||
if key and _HOST_KEY.search(key) and isinstance(value, str):
|
||||
return _redact_host(value)
|
||||
if key and _SENSITIVE_TEXT_KEY.search(key) and isinstance(value, str):
|
||||
return f"<redacted-{key}>"
|
||||
return value
|
||||
|
||||
|
||||
def _redact_host(value: str) -> str:
|
||||
parsed = urlsplit(value)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return urlunsplit((parsed.scheme, "redacted-host.invalid", parsed.path, parsed.query, parsed.fragment))
|
||||
return "<redacted-host>"
|
||||
Reference in new issue
Block a user