Skip to content
Merged
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
10 changes: 10 additions & 0 deletions config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 4 additions & 0 deletions config/env
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions pyegeria/core/_base_platform_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion pyegeria/core/_base_server_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down
46 changes: 45 additions & 1 deletion pyegeria/core/_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions pyegeria/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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"))
Expand Down
128 changes: 128 additions & 0 deletions tests/micro-tests/test_globals_ssl_verify.py
Original file line number Diff line number Diff line change
@@ -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
Loading