diff --git a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py index d624b39..79cf99e 100644 --- a/mx_bec/bec_widgets/widgets/aare_bec/__init__.py +++ b/mx_bec/bec_widgets/widgets/aare_bec/__init__.py @@ -1,4 +1,5 @@ from .actors_config import MxActorConfigWidget +from .automation_permission import MxAutomationPermissionWidget from .sample_queue import SampleQueueWidget from .sample_spreadsheet_display import SampleSpreadsheetDisplay from .task_panel import MxTaskPanel @@ -6,6 +7,7 @@ from .task_queue import MxTaskQueueWidget __all__ = [ "MxActorConfigWidget", + "MxAutomationPermissionWidget", "SampleQueueWidget", "SampleSpreadsheetDisplay", "MxTaskPanel", diff --git a/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py b/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py new file mode 100644 index 0000000..d200908 --- /dev/null +++ b/mx_bec/bec_widgets/widgets/aare_bec/automation_permission.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from datetime import datetime +from threading import Thread + +from bec_lib.logger import bec_logger +from bec_widgets.utils.bec_connector import ConnectionConfig +from bec_widgets.utils.bec_widget import BECWidget +from bec_widgets.utils.error_popups import SafeSlot +from qtpy.QtCore import Signal +from qtpy.QtWidgets import QFormLayout, QLabel, QPushButton, QVBoxLayout, QWidget + +from mx_bec.automation_permission import grant_automation_permission +from mx_bec.endpoints import AuthEndpoints +from mx_bec.external_services.aaredaq import request_user_token +from mx_bec.messages import MXAutomationPermissionStatusMessage + +logger = bec_logger.logger + +NOT_SET = "-" + + +def _time(timestamp: float | None) -> str: + if timestamp is None: + return NOT_SET + return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S") + + +class MxAutomationPermissionWidget(BECWidget, QWidget): + """ + Widget to give the AareBec service permission to act on the user's behalf (to mount samples, + ...), and to show the permission it currently has. + + The button gets a token for the user running the GUI from AareDAQ, which needs a valid + Kerberos ticket, and forwards it to the service, encrypted for the public key the service + published. The status is what the service publishes on `automation_permission_status`. + """ + + PLUGIN = True + ICON_NAME = "key" + USER_ACCESS = ["grant_permission", "refresh"] + + # the token request runs on a worker thread; its outcome is shown on the GUI thread + _grant_finished = Signal(str) + + def __init__( + self, + parent: QWidget | None = None, + client=None, + config: ConnectionConfig | None = None, + gui_id: str | None = None, + **kwargs, + ) -> None: + super().__init__(parent=parent, client=client, config=config, gui_id=gui_id, **kwargs) + self._worker: Thread | None = None + + self._granted = QLabel(parent=self) + self._username = QLabel(parent=self) + self._pgroups = QLabel(parent=self) + self._pgroups.setWordWrap(True) + self._staff = QLabel(parent=self) + self._received_at = QLabel(parent=self) + self._expires_at = QLabel(parent=self) + form = QFormLayout() + form.addRow("Permission", self._granted) + form.addRow("User", self._username) + form.addRow("Pgroups", self._pgroups) + form.addRow("Staff", self._staff) + form.addRow("Granted at", self._received_at) + form.addRow("Token expires", self._expires_at) + + self._button = QPushButton("Authenticate and grant permission", parent=self) + self._button.clicked.connect(self.grant_permission) + self._message = QLabel(parent=self) + self._message.setWordWrap(True) + + layout = QVBoxLayout(self) + layout.addLayout(form) + layout.addWidget(self._button) + layout.addWidget(self._message) + layout.addStretch() + + self._grant_finished.connect(self._on_grant_finished) + # released automatically by BECWidget.cleanup() (disconnect_owner) + self.bec_dispatcher.connect_slot( + self._on_status, AuthEndpoints.automation_permission_status() + ) + self.refresh() + + @SafeSlot() + def refresh(self): + """Reload the permission status from Redis.""" + self._show_status(self.client.connector.get(AuthEndpoints.automation_permission_status())) + + @SafeSlot(dict, dict) + def _on_status(self, content: dict, _metadata: dict): + self._show_status(MXAutomationPermissionStatusMessage(**content)) + + def _show_status(self, status: MXAutomationPermissionStatusMessage | None) -> None: + if status is None: + self._granted.setText("unknown: the AareBec service has not published a status") + for label in (self._username, self._pgroups, self._staff): + label.setText(NOT_SET) + self._received_at.setText(NOT_SET) + self._expires_at.setText(NOT_SET) + return + self._granted.setText("granted" if status.granted else "not granted") + self._username.setText(status.username or NOT_SET) + self._pgroups.setText(", ".join(status.pgroups) if status.pgroups else NOT_SET) + self._staff.setText(NOT_SET if status.staff is None else "yes" if status.staff else "no") + self._received_at.setText(_time(status.received_at)) + self._expires_at.setText(_time(status.expires_at)) + + @SafeSlot() + def grant_permission(self): + """Get a token for the current user from AareDAQ and forward it to the AareBec service. + Returns at once; the outcome is shown in the widget.""" + if self._worker is not None and self._worker.is_alive(): + return + self._button.setEnabled(False) + self._message.setText("Authenticating with AareDAQ...") + self._worker = Thread(target=self._grant, name="mx-grant-permission", daemon=True) + self._worker.start() + + def _grant(self) -> None: + """Runs on the worker thread: the token request can take a while.""" + try: + username, token = request_user_token() + grant_automation_permission(self.client.connector, username, token) + except Exception as e: # pylint: disable=broad-except + logger.warning(f"Could not grant the automation permission: {e}") + self._grant_finished.emit(f"Failed: {e}") + return + self._grant_finished.emit(f"Token of {username} forwarded to the AareBec service.") + + @SafeSlot(str) + def _on_grant_finished(self, message: str): + self._message.setText(message) + self._button.setEnabled(True) + + def cleanup(self): + if self._worker is not None: + self._worker.join(timeout=1) + super().cleanup() diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index a403af1..64ce499 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json +import subprocess from typing import TYPE_CHECKING, Any import requests @@ -22,6 +24,7 @@ DEFAULT_CERT_PATHS = { MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", } REQUEST_TIMEOUT_S = 30.0 +TOKEN_TIMEOUT_S = 120.0 MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted @@ -29,6 +32,55 @@ class AareDaqError(RuntimeError): """A call to the AareDAQ server failed.""" +def configured_url() -> str: + """The URL of the AareDAQ server, from the aarecommon beamline config.""" + beamline = mx_beamline() + if (url := cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline))) is None: + raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}") + return url + + +def configured_cert_path() -> str: + """The certificate of the AareDAQ server, from the aarecommon beamline config.""" + beamline = mx_beamline() + if (cert_path := cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline))) is None: + raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}") + return cert_path + + +def request_user_token(url: str | None = None, cert_path: str | None = None) -> tuple[str, str]: + """For clients, not the service: get an AareDAQ token for the user running this process and + return (username, token). Authenticates by Kerberos (`curl --negotiate` against the Apache + proxy in front of the server, as the AareDAQ GUI does), so it needs a valid ticket (kinit). + The token can then be forwarded to the AareBec service, see `mx_bec.automation_permission`. + """ + url, cert_path = url or configured_url(), cert_path or configured_cert_path() + cmd = ["curl", "-s", "--cacert", cert_path, "--negotiate", "-u", ":", "-XPOST", f"{url}/token"] + try: + result = subprocess.run( + cmd, capture_output=True, text=True, timeout=TOKEN_TIMEOUT_S, check=False + ) + except (OSError, subprocess.TimeoutExpired) as e: + raise AareDaqError(f"AareDAQ token request failed: {e}") from e + if result.returncode != 0: + raise AareDaqError( + f"AareDAQ token request failed (curl exit {result.returncode}): " + f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?" + ) + try: + response = json.loads(result.stdout) + except json.JSONDecodeError as e: + raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e + token = response.get("access_token") if isinstance(response, dict) else None + if not isinstance(token, str) or not token: + raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}") + info = response.get("info") + username = info.get("sub") if isinstance(info, dict) else None + if not isinstance(username, str) or not username: + raise AareDaqError("AareDAQ token response does not say which user the token is for") + return username, token + + class AareDaq: """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: mounting a sample. @@ -50,19 +102,13 @@ class AareDaq: @property def url(self) -> str: if self._url is None: - beamline = mx_beamline() - self._url = cfg_get("gui.daq.daq_url", DEFAULT_URLS.get(beamline)) - if self._url is None: - raise AareDaqError(f"No AareDAQ URL configured for beamline {beamline}") + self._url = configured_url() return self._url @property def cert_path(self) -> str: if self._cert_path is None: - beamline = mx_beamline() - self._cert_path = cfg_get("gui.daq.cert_path", DEFAULT_CERT_PATHS.get(beamline)) - if self._cert_path is None: - raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}") + self._cert_path = configured_cert_path() return self._cert_path def _token(self) -> str: diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index 3cb596e..f65facb 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -1,10 +1,12 @@ +import json +import subprocess from unittest.mock import MagicMock, patch import pytest import requests from mx_bec.automation_permission import AuthInfo -from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError +from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError, request_user_token URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" @@ -109,3 +111,51 @@ def test_connection_error_becomes_an_aaredaq_error(daq): daq._session.request.side_effect = requests.ConnectionError("no route") with pytest.raises(AareDaqError, match="no route"): daq.mount_sample(1) + + +# ---- the token request, which clients (not the service) make for the user running them ---- + + +def _curl_result(stdout=None, returncode=0, stderr=""): + if stdout is None: + stdout = json.dumps( + {"access_token": TOKEN, "token_type": "bearer", "info": {"sub": "e12345"}} + ) + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) + + +@pytest.fixture +def curl(): + with patch( + "mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result() + ) as run: + yield run + + +def test_user_token_is_requested_by_kerberos_curl(curl): + assert request_user_token(URL, CERT) == ("e12345", TOKEN) + curl.assert_called_once() + cmd = curl.call_args.args[0] + assert cmd[0] == "curl" and "--negotiate" in cmd and cmd[-1] == f"{URL}/token" + assert cmd[cmd.index("--cacert") + 1] == CERT + + +@pytest.mark.parametrize( + "result, match", + [ + (_curl_result(returncode=6, stderr="could not resolve"), "curl exit 6"), + (_curl_result(stdout=""), "not JSON"), + (_curl_result(stdout="{}"), "no access_token"), + (_curl_result(stdout='{"access_token": "t"}'), "which user"), + ], +) +def test_user_token_request_failures(curl, result, match): + curl.return_value = result + with pytest.raises(AareDaqError, match=match): + request_user_token(URL, CERT) + + +def test_user_token_request_timeout(curl): + curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) + with pytest.raises(AareDaqError, match="token request failed"): + request_user_token(URL, CERT) diff --git a/tests/unit/test_automation_permission_widget.py b/tests/unit/test_automation_permission_widget.py new file mode 100644 index 0000000..58ad77a --- /dev/null +++ b/tests/unit/test_automation_permission_widget.py @@ -0,0 +1,83 @@ +from unittest.mock import MagicMock, patch + +import pytest + +from mx_bec.bec_widgets.widgets.aare_bec import MxAutomationPermissionWidget +from mx_bec.endpoints import AuthEndpoints +from mx_bec.external_services.aaredaq import AareDaqError +from mx_bec.messages import MXAutomationPermissionStatusMessage + +WIDGET = "mx_bec.bec_widgets.widgets.aare_bec.automation_permission" +GRANTED = MXAutomationPermissionStatusMessage( + granted=True, + username="e12345", + pgroups=["p16371", "p20000"], + staff=False, + expires_at=1.8e9, + received_at=1.7e9, +) + + +@pytest.fixture +def client(): + client = MagicMock() + client.connector.get.return_value = None + return client + + +@pytest.fixture +def widget(qtbot, client): + widget = MxAutomationPermissionWidget(client=client) + qtbot.addWidget(widget) + yield widget + widget.cleanup() + + +def test_shows_that_no_status_is_published(widget, client): + client.connector.get.assert_called_with(AuthEndpoints.automation_permission_status()) + assert widget._granted.text().startswith("unknown") + assert widget._username.text() == "-" + + +def test_shows_the_status_read_on_refresh(widget, client): + client.connector.get.return_value = GRANTED + widget.refresh() + assert widget._granted.text() == "granted" + assert widget._username.text() == "e12345" + assert widget._pgroups.text() == "p16371, p20000" + assert widget._staff.text() == "no" + assert widget._received_at.text() != "-" and widget._expires_at.text() != "-" + + +def test_shows_status_updates_from_the_service(widget): + widget._on_status(GRANTED.content, {}) + assert widget._granted.text() == "granted" + widget._on_status(MXAutomationPermissionStatusMessage(granted=False).content, {}) + assert widget._granted.text() == "not granted" + assert (widget._username.text(), widget._pgroups.text(), widget._staff.text()) == ("-",) * 3 + + +def test_button_gets_a_token_and_forwards_it(widget, client, qtbot): + with ( + patch(f"{WIDGET}.request_user_token", return_value=("e12345", "token")) as request, + patch(f"{WIDGET}.grant_automation_permission") as grant, + qtbot.waitSignal(widget._grant_finished, timeout=5000), + ): + widget._button.click() + request.assert_called_once_with() + grant.assert_called_once_with(client.connector, "e12345", "token") + assert "e12345" in widget._message.text() + assert "token" not in widget._message.text().replace("Token of", "") + assert widget._button.isEnabled() + + +def test_a_failed_token_request_is_shown(widget, qtbot): + with ( + patch(f"{WIDGET}.request_user_token", side_effect=AareDaqError("no ticket (kinit)")), + patch(f"{WIDGET}.grant_automation_permission") as grant, + qtbot.waitSignal(widget._grant_finished, timeout=5000), + ): + widget.grant_permission() + grant.assert_not_called() + assert widget._message.text() == "Failed: no ticket (kinit)" + assert widget._button.isEnabled()