From ff871c0301a7636d598016456a5b0af3c5090b9c Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Wed, 4 Nov 2026 20:53:33 +0000 Subject: [PATCH] feat(core): configurable TLS verification of the Egeria platform certificate pyegeria has always created its httpx clients with verify=False (_globals.enable_ssl_check), so it never checked the Egeria platform's certificate. It is now configurable, using the same layering as egeria_max_page_size: PYEGERIA_SSL_VERIFY / PYEGERIA_CA_BUNDLE (env or .env) override "Pyegeria SSL Verify" / "Pyegeria CA Bundle" under Environment in config.json. - Default stays off: the quickstart platforms use self-signed certificates. - Verify on, no bundle: httpx checks against certifi, which has the emSign G3 floor from 6.2.21. - Verify on with a bundle: an SSLContext that trusts that PEM file, e.g. the quickstart's own chain, to verify a self-signed platform. - A bundle path that doesn't exist raises at import rather than silently falling back to unverified. The three httpx client constructions read _globals.ssl_verify when a session is created, so a program can also set it in code. enable_ssl_check stays a bool for existing importers. Verified live against a 6.3-SNAPSHOT quickstart platform: off connects; on refuses with CERTIFICATE_VERIFY_FAILED (self-signed); on with the platform's chain as the CA bundle connects. Micro-tests: 0 failed of 1799. Signed-off-by: Dan Wolfson --- config/README.md | 10 ++ config/env | 4 + pyegeria/core/_base_platform_client.py | 5 +- pyegeria/core/_base_server_client.py | 3 +- pyegeria/core/_globals.py | 46 ++++++- pyegeria/core/config.py | 16 +++ tests/micro-tests/test_globals_ssl_verify.py | 128 +++++++++++++++++++ 7 files changed, 208 insertions(+), 4 deletions(-) create mode 100644 tests/micro-tests/test_globals_ssl_verify.py diff --git a/config/README.md b/config/README.md index 8102b12e..6deefe41 100644 --- a/config/README.md +++ b/config/README.md @@ -177,6 +177,16 @@ You can override many values via environment variables; `config/env` contains co - `PYEGERIA_NORMALIZE_MERMAID` (`True`/`False`) - Logging - `PYEGERIA_ENABLE_LOGGING`, `PYEGERIA_LOG_DIRECTORY`, `PYEGERIA_CONSOLE_LOG_LVL`, `PYEGERIA_FILE_LOG_LVL`, `PYEGERIA_CONSOLE_FILTER_LEVELS` +- TLS verification of the Egeria platform's certificate + - `PYEGERIA_SSL_VERIFY` (`True`/`False`, default `False`); JSON key `"Pyegeria SSL Verify"` under `Environment`. + Off by default because the quickstart platforms use self-signed certificates. Turn it on + for any platform with a certificate from a trusted CA. + - `PYEGERIA_CA_BUNDLE` (path to a PEM file); JSON key `"Pyegeria CA Bundle"`. Used only when + verification is on: pyegeria then trusts this bundle instead of certifi's. Point it at your own + CA (or the quickstart's certificate chain) to verify a self-signed platform. A path that + doesn't exist stops pyegeria at import with an error, rather than silently not verifying. + - Programs can also set `pyegeria.core._globals.ssl_verify` (anything httpx accepts as + `verify`, e.g. an `ssl.SSLContext`) before creating clients. Values provided via environment variables take precedence over JSON and defaults. diff --git a/config/env b/config/env index 02005720..8807cdf9 100644 --- a/config/env +++ b/config/env @@ -28,6 +28,10 @@ PYEGERIA_USER_REPORT_SPECS_DIR="~/.pyegeria/report_specs" # Deprecated: kept for backward compatibility if set in external environments # PYEGERIA_USER_FORMAT_SETS_DIR="~/.pyegeria/format_sets" EGERIA_WIDTH=130 +# Verify the Egeria platform's TLS certificate (default off: quickstart certs are self-signed) +# PYEGERIA_SSL_VERIFY=true +# PEM bundle to trust instead of certifi's; only used when PYEGERIA_SSL_VERIFY is on +# PYEGERIA_CA_BUNDLE="~/certs/egeria-ca.pem" # Preferred variable name EGERIA_USER=erinoverview # Deprecated alias kept for external environments; not used by loader diff --git a/pyegeria/core/_base_platform_client.py b/pyegeria/core/_base_platform_client.py index cb859f17..e8f65762 100644 --- a/pyegeria/core/_base_platform_client.py +++ b/pyegeria/core/_base_platform_client.py @@ -27,6 +27,7 @@ PyegeriaUnknownException, PyegeriaClientException, PyegeriaTimeoutException, PyegeriaUnauthorizedException ) +from pyegeria.core import _globals from pyegeria.core._globals import enable_ssl_check, max_paging_size from pyegeria.core._validators import ( validate_name, @@ -65,7 +66,7 @@ async def _post_for_bearer_token(url: str, data: dict, headers: dict, user_id: s """ context = {"caller method": "create_egeria_bearer_token"} try: - async with AsyncClient(verify=enable_ssl_check) as client: + async with AsyncClient(verify=_globals.ssl_verify) as client: response = await client.post(url, json=data, headers=headers) except httpx.TimeoutException as e: raise PyegeriaTimeoutException(context, {"endpoint": url, "error_kind": "timeout"}, e) @@ -230,7 +231,7 @@ def session(self) -> AsyncClient: if not hasattr(self._thread_local, "session") or stale: self._thread_local.session_loop = loop self._thread_local.session = AsyncClient( - verify=enable_ssl_check, + verify=_globals.ssl_verify, timeout=httpx.Timeout(timeout=float(self.timeout), connect=10.0), limits=httpx.Limits( max_connections=10, diff --git a/pyegeria/core/_base_server_client.py b/pyegeria/core/_base_server_client.py index d07a35e5..20d0132d 100644 --- a/pyegeria/core/_base_server_client.py +++ b/pyegeria/core/_base_server_client.py @@ -24,6 +24,7 @@ PyegeriaUnknownException, PyegeriaClientException, PyegeriaTimeoutException, PyegeriaNotFoundException, PyegeriaUnauthorizedException ) +from pyegeria.core import _globals from pyegeria.core._globals import enable_ssl_check, max_paging_size from pyegeria.core._base_platform_client import _apply_for_lineage_default, _post_for_bearer_token from pyegeria.core._validators import ( @@ -175,7 +176,7 @@ def session(self) -> AsyncClient: if not hasattr(self._thread_local, "session") or stale: self._thread_local.session_loop = loop self._thread_local.session = AsyncClient( - verify=enable_ssl_check, + verify=_globals.ssl_verify, timeout=httpx.Timeout(timeout=float(self.timeout), connect=10.0), ) return self._thread_local.session diff --git a/pyegeria/core/_globals.py b/pyegeria/core/_globals.py index 74639d68..65306cd5 100644 --- a/pyegeria/core/_globals.py +++ b/pyegeria/core/_globals.py @@ -7,6 +7,7 @@ This common file is used to set some global values and enumerations used by the overall package. """ +import os from enum import Enum from typing import Any @@ -40,7 +41,50 @@ def resolve_enum(enum_class: type[Enum], value: str | int) -> int | None: is_debug = False disable_ssl_warnings = True -enable_ssl_check = False + + +def resolve_ssl_verify(verify: bool, ca_bundle: str = "") -> "bool | ssl.SSLContext": + """Turn the SSL settings into the value httpx takes as ``verify``. + + * ``verify`` off -> ``False``: the Egeria platform's certificate is not checked + (the historical behaviour, needed for the quickstart's self-signed certificates). + * ``verify`` on, no bundle -> ``True``: httpx checks against certifi's bundle. + * ``verify`` on with a bundle -> an ``SSLContext`` that trusts that PEM file. + + A bundle that can't be loaded raises: falling back to "don't verify" would + quietly undo the setting, and falling back to certifi would hide the typo + behind a confusing certificate error later. + """ + if not verify: + return False + if not ca_bundle: + return True + import ssl + path = os.path.expanduser(os.path.expandvars(ca_bundle)) + if not os.path.isfile(path): + raise FileNotFoundError( + f"Pyegeria CA Bundle / PYEGERIA_CA_BUNDLE is set to {ca_bundle!r}, but {path!r} is not a file" + ) + return ssl.create_default_context(cafile=path) + + +# TLS verification of the Egeria platform's certificate. Configurable through +# PYEGERIA_SSL_VERIFY / PYEGERIA_CA_BUNDLE, the same names in .env, or +# "Pyegeria SSL Verify" / "Pyegeria CA Bundle" in config.json (see +# pyegeria.core.config.EnvironmentConfig). Default off, as before. +# enable_ssl_check stays a plain bool for existing importers; ssl_verify is +# what the HTTP clients pass to httpx. The clients read ssl_verify from this +# module when they create a session, so a program can also set +# pyegeria.core._globals.ssl_verify itself before connecting. +try: + from pyegeria.core.config import settings as _ssl_settings + _ssl_env = _ssl_settings.Environment + enable_ssl_check = bool(getattr(_ssl_env, "pyegeria_ssl_verify", False)) + _ca_bundle = str(getattr(_ssl_env, "pyegeria_ca_bundle", "") or "") +except Exception: # noqa: BLE001 -- config not ready yet; keep the historical default + enable_ssl_check = False + _ca_bundle = "" +ssl_verify = resolve_ssl_verify(enable_ssl_check, _ca_bundle) # Default page size for paged find/relationship queries. Env-configurable # (EGERIA_MAX_PAGE_SIZE / "Egeria Max Page Size" in config.json/.env, see diff --git a/pyegeria/core/config.py b/pyegeria/core/config.py index 12685aac..fd7a6624 100644 --- a/pyegeria/core/config.py +++ b/pyegeria/core/config.py @@ -63,6 +63,13 @@ class PyegeriaSettings(BaseSettings): # env-configurable means a future limit change is a .env edit, not a grep across # every hardcoded page_size literal in every caller. egeria_max_page_size: int = 500 + # TLS verification of the Egeria platform's certificate (pyegeria.core._globals + # .ssl_verify). Off by default because the quickstart platforms use self-signed + # certificates; turn on for any deployment with a real certificate. + pyegeria_ssl_verify: bool = False + # Optional CA bundle (PEM) to verify against instead of certifi's, e.g. the + # quickstart's own CA. Only used when pyegeria_ssl_verify is on. + pyegeria_ca_bundle: str = "" # Renamed: format_sets -> report_specs pyegeria_user_report_specs_dir: str = "~/.pyegeria/report_specs" egeria_user_name: str = Field(default="", validation_alias="EGERIA_USER") @@ -107,6 +114,8 @@ class EnvironmentConfig(BaseModel): """Environment configuration settings""" egeria_width: int = Field(default=200, alias="Egeria Width") egeria_max_page_size: int = Field(default=500, alias="Egeria Max Page Size") + pyegeria_ssl_verify: bool = Field(default=False, alias="Pyegeria SSL Verify") + pyegeria_ca_bundle: str = Field(default="", alias="Pyegeria CA Bundle") egeria_outbox: str = Field(default="egeria-outbox", alias="Egeria Outbox") egeria_inbox: str = Field(default="egeria-inbox", alias="Egeria Inbox") dr_egeria_inbox: str = Field(default="egeria-inbox/dr-egeria-inbox", alias="Dr.Egeria Inbox") @@ -346,6 +355,13 @@ def load_app_config(env_file: str | None = None): env["egeria_width"] = env["Egeria Width"] env["Egeria Max Page Size"] = int(os.getenv("EGERIA_MAX_PAGE_SIZE", env.get("Egeria Max Page Size", env_settings.egeria_max_page_size))) env["egeria_max_page_size"] = env["Egeria Max Page Size"] + # TLS verification: PYEGERIA_SSL_VERIFY > .env > config.json > False. + env["Pyegeria SSL Verify"] = _parse_bool_value( + os.getenv("PYEGERIA_SSL_VERIFY", env.get("Pyegeria SSL Verify", env_settings.pyegeria_ssl_verify)) + ) + env["pyegeria_ssl_verify"] = env["Pyegeria SSL Verify"] + env["Pyegeria CA Bundle"] = os.getenv("PYEGERIA_CA_BUNDLE", env.get("Pyegeria CA Bundle", env_settings.pyegeria_ca_bundle)) or "" + env["pyegeria_ca_bundle"] = env["Pyegeria CA Bundle"] # Egeria Outbox (new) env["Egeria Outbox"] = os.getenv("EGERIA_OUTBOX", env.get("Egeria Outbox", "egeria-outbox")) env["Egeria Inbox"] = os.getenv("EGERIA_INBOX", env.get("Egeria Inbox", "egeria-inbox")) diff --git a/tests/micro-tests/test_globals_ssl_verify.py b/tests/micro-tests/test_globals_ssl_verify.py new file mode 100644 index 00000000..be971998 --- /dev/null +++ b/tests/micro-tests/test_globals_ssl_verify.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Unit tests for configurable TLS verification of the Egeria platform's +certificate: pyegeria.core._globals.enable_ssl_check / ssl_verify, driven by +PYEGERIA_SSL_VERIFY / PYEGERIA_CA_BUNDLE (or "Pyegeria SSL Verify" / +"Pyegeria CA Bundle" in config.json). + +Uses the same reset-then-reload pattern as test_globals_max_paging_size.py. +""" +import importlib +import os +import ssl + +import certifi +import pytest + +import pyegeria.core.config as config_module +import pyegeria.core._globals as globals_module +from pyegeria.core._globals import resolve_ssl_verify + +_ENV_VARS = ("PYEGERIA_SSL_VERIFY", "PYEGERIA_CA_BUNDLE") + + +@pytest.fixture +def clean_ssl_env(): + saved = {k: os.environ.pop(k, None) for k in _ENV_VARS} + config_module._app_config = None + yield + for k in _ENV_VARS: + os.environ.pop(k, None) + if saved[k] is not None: + os.environ[k] = saved[k] + config_module._app_config = None + importlib.reload(globals_module) + + +def _reload(): + config_module._app_config = None + importlib.reload(globals_module) + + +# --- resolve_ssl_verify ------------------------------------------------------- + +def test_resolve_off_is_false_even_with_bundle(): + assert resolve_ssl_verify(False) is False + assert resolve_ssl_verify(False, "/no/such/file.pem") is False + + +def test_resolve_on_without_bundle_uses_httpx_default(): + assert resolve_ssl_verify(True) is True + assert resolve_ssl_verify(True, "") is True + + +def test_resolve_on_with_bundle_builds_context(): + ctx = resolve_ssl_verify(True, certifi.where()) + assert isinstance(ctx, ssl.SSLContext) + assert ctx.verify_mode == ssl.CERT_REQUIRED + assert ctx.check_hostname is True + + +def test_resolve_missing_bundle_raises_rather_than_falling_back(): + with pytest.raises(FileNotFoundError, match="PYEGERIA_CA_BUNDLE"): + resolve_ssl_verify(True, "/no/such/ca-bundle.pem") + + +# --- configuration wiring ----------------------------------------------------- + +def test_default_is_off(clean_ssl_env): + _reload() + assert globals_module.enable_ssl_check is False + assert globals_module.ssl_verify is False + + +@pytest.mark.parametrize("value", ["true", "1", "yes", "on"]) +def test_env_var_turns_verification_on(clean_ssl_env, value): + os.environ["PYEGERIA_SSL_VERIFY"] = value + _reload() + assert globals_module.enable_ssl_check is True + assert globals_module.ssl_verify is True + + +def test_env_var_with_ca_bundle(clean_ssl_env): + os.environ["PYEGERIA_SSL_VERIFY"] = "true" + os.environ["PYEGERIA_CA_BUNDLE"] = certifi.where() + _reload() + assert globals_module.enable_ssl_check is True + assert isinstance(globals_module.ssl_verify, ssl.SSLContext) + + +def test_env_var_false_overrides_config_json(clean_ssl_env, monkeypatch, tmp_path): + cfg = tmp_path / "config.json" + cfg.write_text('{"Environment": {"Pyegeria SSL Verify": true}}') + monkeypatch.setenv("PYEGERIA_CONFIG_DIRECTORY", str(tmp_path)) + monkeypatch.setenv("PYEGERIA_CONFIG_FILE", "config.json") + _reload() + assert globals_module.enable_ssl_check is True # from config.json + + os.environ["PYEGERIA_SSL_VERIFY"] = "false" + _reload() + assert globals_module.enable_ssl_check is False # env wins + + +def test_clients_pass_ssl_verify_to_httpx(clean_ssl_env, monkeypatch): + # The session reads _globals.ssl_verify when it is created, so setting it + # in code (after import) also takes effect. + from pyegeria.core._base_server_client import BaseServerClient + + monkeypatch.setattr(BaseServerClient, "check_connection", lambda self: "ok", raising=False) + sentinel = ssl.create_default_context(cafile=certifi.where()) + monkeypatch.setattr(globals_module, "ssl_verify", sentinel) + + captured = {} + import pyegeria.core._base_server_client as bsc + + real = bsc.AsyncClient + + def spy(*args, **kwargs): + captured["verify"] = kwargs.get("verify") + return real(*args, **kwargs) + + monkeypatch.setattr(bsc, "AsyncClient", spy) + client = BaseServerClient.__new__(BaseServerClient) + import threading + client._thread_local = threading.local() + client.timeout = 30 + _ = client.session + assert captured["verify"] is sentinel