diff --git a/src/aare/daq/aaredb.py b/src/aare/daq/aaredb.py index e9edd5a7..d2ab607e 100644 --- a/src/aare/daq/aaredb.py +++ b/src/aare/daq/aaredb.py @@ -1,8 +1,11 @@ import os +from pathlib import Path import aareDB +import urllib3 from aarecommon.config.logger import setup_logger from aarecommon.config.logger_events import log_timing +from aarecommon.errors.exception_handler import AareDBCommunicationError from aarecommon.models.beamline import MXBeamline from aareDB.models.puck_with_tell_position import PuckWithTellPosition from aareDB.models.sample import Sample @@ -10,6 +13,9 @@ from pydantic import BaseModel logger = setup_logger("aareDAQ") +DEFAULT_HOST = "https://mx-aaredb-dmz-01.psi.ch/dispatcher" +SECRETS_DIR = "/etc/ssl/certs/secrets" + class LoadedSampleInfo(BaseModel): """An aareDB sample together with where it currently sits in this beamline's TELL.""" @@ -22,21 +28,44 @@ class LoadedSampleInfo(BaseModel): class AareWrapper: - def __init__(self, bl: MXBeamline, host: str = "https://mx-aaredb-dmz-01.psi.ch/dispatcher"): + """Client for the aareDB dispatcher (runner API), authenticated by mTLS + shared password. + + The server certificate is verified against the OS trust store (the dispatcher serves a + public DigiCert certificate); set ``AAREDB_CA_CERT`` to pin a custom bundle instead. + Client identity defaults to the beamline queue hosts' layout and can be overridden with + ``AAREDB_HOST``, ``AAREDB_CLIENT_CERT`` and ``AAREDB_CLIENT_KEY``. + """ + + def __init__(self, bl: MXBeamline, host: str | None = None): + host = host or os.getenv("AAREDB_HOST", DEFAULT_HOST) + beamline_name = bl.value.lower() configuration = aareDB.Configuration(host=host) # --- mTLS & SSL CONFIGURATION --- - # 1. Trust the Server (CA that signed mx-aaredb-dmz-01) + # 1. Trust the Server. None lets urllib3 load the OS trust store, which is where + # the DigiCert roots behind mx-aaredb-dmz-01 live. The old pinned + # mx-aaredb-dmz-01_Full_Chain_CA.pem holds the retired PSI-internal chain and + # fails with "self-signed certificate in certificate chain". configuration.verify_ssl = True - configuration.ssl_ca_cert = "/etc/ssl/certs/secrets/mx-aaredb-dmz-01_Full_Chain_CA.pem" + configuration.ssl_ca_cert = os.getenv("AAREDB_CA_CERT") # 2. Present Machine Identity (The certs that worked in curl) - beamline_name = bl.value.lower() - configuration.cert_file = ( - f"/etc/ssl/certs/secrets/mx-{beamline_name}-queue-01_from_dmz-01.crt" + configuration.cert_file = os.getenv( + "AAREDB_CLIENT_CERT", f"{SECRETS_DIR}/mx-{beamline_name}-queue-01_from_dmz-01.crt" ) - configuration.key_file = ( - f"/etc/ssl/certs/secrets/mx-{beamline_name}-queue-01_from_dmz-01.key" + configuration.key_file = os.getenv( + "AAREDB_CLIENT_KEY", f"{SECRETS_DIR}/mx-{beamline_name}-queue-01_from_dmz-01.key" + ) + for what, path in ( + ("CA bundle", configuration.ssl_ca_cert), + ("client certificate", configuration.cert_file), + ("client key", configuration.key_file), + ): + if path is not None and not Path(path).is_file(): + logger.warning(f"aareDB {what} not found at {path}; calls to aareDB will fail") + logger.info( + f"aareDB client: host={host} ca={configuration.ssl_ca_cert or 'system trust store'} " + f"cert={configuration.cert_file}" ) # 3. Initialize the Client with this config @@ -48,9 +77,31 @@ class AareWrapper: self._tell_api = aareDB.TellsRunnerApi(self.client) self._bl = bl + def _loaded_pucks(self) -> list[PuckWithTellPosition]: + tell = self._bl.value.upper() + try: + return self._tell_api.get_pucks_with_tell_position(tell=tell) + except aareDB.ApiException as e: + raise AareDBCommunicationError( + f"aareDB rejected the TELL puck listing: {e.status} {e.reason}", + operation="get_pucks_with_tell_position", + endpoint=f"/protected_router/tell_runner/with-tell-position?tell={tell}", + base_url=self._host, + status_code=e.status, + critical=True, + ) from e + except (urllib3.exceptions.HTTPError, OSError) as e: + # Connection refused, TLS verification, missing cert files, DNS, ... + raise AareDBCommunicationError( + f"Could not reach aareDB: {e}", + operation="get_pucks_with_tell_position", + endpoint=f"/protected_router/tell_runner/with-tell-position?tell={tell}", + base_url=self._host, + critical=True, + ) from e + def _find_loaded(self, sample_id: int) -> tuple[PuckWithTellPosition, Sample] | None: - pucks = self._tell_api.get_pucks_with_tell_position(tell=self._bl.value.upper()) - for puck in pucks: + for puck in self._loaded_pucks(): for sample in puck.samples or []: if sample.id == sample_id: return puck, sample diff --git a/tests/unit/daq/test_aaredb.py b/tests/unit/daq/test_aaredb.py index 790aa324..70dc7602 100644 --- a/tests/unit/daq/test_aaredb.py +++ b/tests/unit/daq/test_aaredb.py @@ -1,6 +1,9 @@ from unittest.mock import MagicMock, patch +import aareDB import pytest +import urllib3 +from aarecommon.errors.exception_handler import AareDBCommunicationError from aareDB.models.puck_with_tell_position import PuckWithTellPosition from aareDB.models.sample import Sample @@ -91,3 +94,66 @@ def test_get_sample_info(wrapper): def test_get_sample_info_missing(wrapper): wrapper._tell_api.get_pucks_with_tell_position.return_value = [_puck(1, 2)] assert wrapper.get_sample_info(99) is None + + +def test_env_overrides_connection_settings(mock_bl, tmp_path, monkeypatch): + ca, crt, key = (tmp_path / n for n in ("ca.pem", "client.crt", "client.key")) + for f in (ca, crt, key): + f.write_text("x") + monkeypatch.setenv("AAREDB_HOST", "https://aaredb-test.example/dispatcher") + monkeypatch.setenv("AAREDB_CA_CERT", str(ca)) + monkeypatch.setenv("AAREDB_CLIENT_CERT", str(crt)) + monkeypatch.setenv("AAREDB_CLIENT_KEY", str(key)) + with patch("aare.daq.aaredb.aareDB.ApiClient") as api_client: + AareWrapper(mock_bl) + cfg = api_client.call_args.args[0] + assert cfg.host == "https://aaredb-test.example/dispatcher" + assert cfg.ssl_ca_cert == str(ca) + assert cfg.cert_file == str(crt) + assert cfg.key_file == str(key) + assert cfg.verify_ssl is True + + +def test_default_paths_follow_beamline(mock_bl, monkeypatch): + for var in ("AAREDB_HOST", "AAREDB_CA_CERT", "AAREDB_CLIENT_CERT", "AAREDB_CLIENT_KEY"): + monkeypatch.delenv(var, raising=False) + with patch("aare.daq.aaredb.aareDB.ApiClient") as api_client: + AareWrapper(mock_bl) + cfg = api_client.call_args.args[0] + assert cfg.host == "https://mx-aaredb-dmz-01.psi.ch/dispatcher" + # No pinned bundle: urllib3 falls back to the OS trust store, which has the DigiCert roots + assert cfg.ssl_ca_cert is None + assert cfg.verify_ssl is True + assert cfg.cert_file == "/etc/ssl/certs/secrets/mx-x10sa-queue-01_from_dmz-01.crt" + assert cfg.key_file == "/etc/ssl/certs/secrets/mx-x10sa-queue-01_from_dmz-01.key" + + +@pytest.mark.parametrize( + "raised", + [ + urllib3.exceptions.MaxRetryError( + None, "/x", reason=urllib3.exceptions.SSLError("bad cert") + ), + urllib3.exceptions.SSLError("CERTIFICATE_VERIFY_FAILED"), + FileNotFoundError("/etc/ssl/certs/secrets/missing.pem"), + ConnectionRefusedError(), + ], +) +def test_transport_errors_become_aaredb_communication_error(wrapper, raised): + wrapper._tell_api.get_pucks_with_tell_position.side_effect = raised + with pytest.raises(AareDBCommunicationError) as e: + wrapper.get_sample_info(1) + assert e.value.critical is True + assert e.value.base_url == "https://mx-aaredb-dmz-01.psi.ch/dispatcher" + assert "tell=X10SA" in e.value.endpoint + assert "Could not reach aareDB" in str(e.value) + + +def test_api_error_becomes_aaredb_communication_error(wrapper): + wrapper._tell_api.get_pucks_with_tell_position.side_effect = aareDB.ApiException( + status=401, reason="Unauthorized" + ) + with pytest.raises(AareDBCommunicationError) as e: + wrapper.find_loaded_sample(1) + assert e.value.status_code == 401 + assert "401" in str(e.value) diff --git a/tests/unit/daq/test_server.py b/tests/unit/daq/test_server.py index c3199fa4..be2020bb 100644 --- a/tests/unit/daq/test_server.py +++ b/tests/unit/daq/test_server.py @@ -1,6 +1,7 @@ from unittest.mock import MagicMock, patch import pytest +from aarecommon.errors.exception_handler import AareDBCommunicationError from aarecommon.models.models import DewarAddress, SampleShortInfo from aareDB.models.sample import Sample @@ -233,3 +234,20 @@ def test_sample_info_not_loaded_is_400(client, mock_aaredb): response = client.get("/sample/999", headers=AUTH) assert response.status_code == 400 assert response.json()["exception_class"] == "SampleException" + + +def test_sample_info_aaredb_unreachable_is_503(client, mock_aaredb): + mock_aaredb.get_sample_info.side_effect = AareDBCommunicationError( + "Could not reach aareDB: CERTIFICATE_VERIFY_FAILED", + operation="get_pucks_with_tell_position", + base_url="https://mx-aaredb-dmz-01.psi.ch/dispatcher", + critical=True, + ) + with _as_user(["p12345"]): + response = client.get("/sample/1", headers=AUTH) + assert response.status_code == 503 + body = response.json() + assert body["critical"] is True + assert body["exception_class"] == "AareDBCommunicationError" + assert "CERTIFICATE_VERIFY_FAILED" in body["message"] + assert body["context"]["base_url"] == "https://mx-aaredb-dmz-01.psi.ch/dispatcher"