From 6fcc8543531eb0c649bba2b62773062cebaed358 Mon Sep 17 00:00:00 2001 From: David Perl Date: Wed, 2 Dec 2026 14:40:32 +0100 Subject: [PATCH] add forwarded auth infra --- mx_bec/automation_permission.py | 269 +++++++++++++++++++++++ mx_bec/endpoints.py | 38 ++++ mx_bec/external_services/aaredaq.py | 146 ++++-------- mx_bec/messages.py | 45 ++++ mx_bec/service.py | 9 +- pyproject.toml | 1 + tests/unit/test_aaredaq.py | 202 +++++------------ tests/unit/test_automation_permission.py | 208 ++++++++++++++++++ tests/unit/test_service.py | 16 +- 9 files changed, 675 insertions(+), 259 deletions(-) create mode 100644 mx_bec/automation_permission.py create mode 100644 tests/unit/test_automation_permission.py diff --git a/mx_bec/automation_permission.py b/mx_bec/automation_permission.py new file mode 100644 index 0000000..41e6429 --- /dev/null +++ b/mx_bec/automation_permission.py @@ -0,0 +1,269 @@ +"""Permission for the AareBec service to act on a user's behalf. + +Secured actions (mounting a sample, ...) are carried out by a server which wants to know which +user is asking: what is kept of AareDAQ, which issues a bearer token to a user who authenticates +by Kerberos. The service has no user identity of its own, so a client forwards the user's token: + +1. the service generates an RSA key pair when it starts and publishes the public key on + `AuthEndpoints.forwarded_auth_public_key()`; +2. the client gets a token from the server, encrypts it for that public key and adds it to the + stream `AuthEndpoints.automation_permission()` (`grant_automation_permission` does both); +3. the service decrypts the token with its private key, which never leaves the process, and uses + it for the secured actions until another token arrives. + +Every client can read the stream, hence the encryption. A token is longer than what RSA can +encrypt directly, so it is encrypted with a one-off AES-256-GCM key, which in turn is encrypted +for the service with RSA-OAEP. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import time +from dataclasses import dataclass, field +from threading import Lock +from typing import TYPE_CHECKING + +from bec_lib.logger import bec_logger +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from mx_bec.endpoints import AuthEndpoints +from mx_bec.messages import ( + MXAutomationPermissionMessage, + MXAutomationPermissionStatusMessage, + MXForwardedAuthPublicKeyMessage, +) + +if TYPE_CHECKING: + from bec_lib.redis_connector import RedisConnector + + from mx_bec.service import AareBec + +logger = bec_logger.logger + +RSA_KEY_SIZE = 2048 +RSA_PUBLIC_EXPONENT = 65537 +AES_KEY_BYTES = 32 +GCM_NONCE_BYTES = 12 +# set to "1" (or "true"/"on"/"yes") in the environment of the service to turn the authentication on +ENABLED_ENV_VAR = "MX_BEC_AUTOMATION_PERMISSION" + + +class AutomationPermissionError(RuntimeError): + """The service has no permission to act on a user's behalf.""" + + +@dataclass(frozen=True) +class AuthInfo: + """What a user gave the service so that it can act on their behalf.""" + + username: str + token: str = field(repr=False) # keep it out of logs + received_at: float = field(default_factory=time.time) + + @property + def claims(self) -> dict: + """What the token says about the user, if it is a JWT (as the tokens of AareDAQ are: + `sub`, `pgroups`, `staff`, `exp`). NOT verified: the service does not have the key the + token was signed with, so this is for information only.""" + try: + payload = self.token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (IndexError, ValueError): + return {} + return claims if isinstance(claims, dict) else {} + + @property + def pgroups(self) -> list[str] | None: + """The pgroups named in the token, or None if it does not name any.""" + pgroups = self.claims.get("pgroups") + if not isinstance(pgroups, list): + return None + return [str(pgroup) for pgroup in pgroups] + + +def _oaep() -> padding.OAEP: + return padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None + ) + + +def _b64(data: bytes) -> str: + return base64.b64encode(data).decode("ascii") + + +def key_id(public_key_pem: str) -> str: + """A short fingerprint of a public key, to tell which key a token was encrypted for.""" + return hashlib.sha256(public_key_pem.encode("ascii")).hexdigest()[:16] + + +def encrypt_token( + public_key: MXForwardedAuthPublicKeyMessage, username: str, token: str +) -> MXAutomationPermissionMessage: + """Encrypt `token` so that only the service which published `public_key` can read it.""" + rsa_key = serialization.load_pem_public_key(public_key.public_key_pem.encode("ascii")) + if not isinstance(rsa_key, rsa.RSAPublicKey): + raise AutomationPermissionError("The published forwarded auth key is not an RSA key") + aes_key, nonce = AESGCM.generate_key(bit_length=AES_KEY_BYTES * 8), os.urandom(GCM_NONCE_BYTES) + # the username and key id are authenticated with the token, so they cannot be swapped + associated = f"{public_key.key_id}:{username}".encode() + return MXAutomationPermissionMessage( + username=username, + key_id=public_key.key_id, + encrypted_key=_b64(rsa_key.encrypt(aes_key, _oaep())), + nonce=_b64(nonce), + encrypted_token=_b64(AESGCM(aes_key).encrypt(nonce, token.encode(), associated)), + ) + + +def grant_automation_permission(connector: RedisConnector, username: str, token: str) -> None: + """For clients: give the AareBec service permission to act for `username` with their + `token`, encrypted for the public key which the service published.""" + public_key = connector.get(AuthEndpoints.forwarded_auth_public_key()) + if public_key is None: + raise AutomationPermissionError( + "The AareBec service has not published a public key: is it running?" + ) + msg = encrypt_token(public_key, username, token) + connector.xadd(AuthEndpoints.automation_permission(), {"data": msg}, max_size=1) + + +class AutomationPermission: + """Holds the permission of the AareBec service to act on a user's behalf: the token which a + client forwarded, see the module documentation. + + The authentication is off by default (`enabled=False`): `token` is then None without a + forwarded token, and what uses it carries on as it would without this class. If it is on, + asking for the token without one having been forwarded is an AutomationPermissionError. A + forwarded token is taken up either way. + """ + + def __init__(self, client: AareBec, enabled: bool = False) -> None: + self._client = client + self.enabled = enabled + self._lock = Lock() + self._auth_info: AuthInfo | None = None + self._private_key = rsa.generate_private_key( + public_exponent=RSA_PUBLIC_EXPONENT, key_size=RSA_KEY_SIZE + ) + self.public_key_pem = ( + self._private_key.public_key() + .public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo, + ) + .decode("ascii") + ) + self.key_id = key_id(self.public_key_pem) + self._listening = False + + @staticmethod + def enabled_in_environment() -> bool: + return os.environ.get(ENABLED_ENV_VAR, "").strip().lower() in ("1", "true", "on", "yes") + + def start(self) -> None: + """Publish the public key and listen for forwarded tokens. Needs the client's connector, + so it is called once the client has started.""" + connector = self._client.connector + connector.set_and_publish( + AuthEndpoints.forwarded_auth_public_key(), + MXForwardedAuthPublicKeyMessage(public_key_pem=self.public_key_pem, key_id=self.key_id), + ) + connector.register(AuthEndpoints.automation_permission(), cb=self._on_permission) + self._listening = True + self._publish_status() + logger.info( + f"Automation permission: published public key {self.key_id}, authentication is " + f"{'on' if self.enabled else 'off'}" + ) + + def shutdown(self) -> None: + if self._listening: + self._client.connector.unregister( + AuthEndpoints.automation_permission(), cb=self._on_permission + ) + self.clear() + self._listening = False + + def _on_permission(self, msg_dict: dict, **_kwargs) -> None: + """Take up the token forwarded on the stream. What cannot be decrypted is ignored, and + the permission the service already has is kept.""" + msg: MXAutomationPermissionMessage = msg_dict["data"] + try: + token = self._decrypt(msg) + except Exception as e: # pylint: disable=broad-except + logger.warning(f"Ignoring the automation permission sent for {msg.username}: {e}") + return + with self._lock: + self._auth_info = AuthInfo(username=msg.username, token=token) + logger.info(f"Automation permission granted by {msg.username}") + self._publish_status() + + def _decrypt(self, msg: MXAutomationPermissionMessage) -> str: + if msg.key_id != self.key_id: + raise AutomationPermissionError( + f"it was encrypted for the key {msg.key_id}, not the current key {self.key_id}" + ) + aes_key = self._private_key.decrypt(base64.b64decode(msg.encrypted_key), _oaep()) + associated = f"{msg.key_id}:{msg.username}".encode() + token = AESGCM(aes_key).decrypt( + base64.b64decode(msg.nonce), base64.b64decode(msg.encrypted_token), associated + ) + return token.decode() + + @property + def auth_info(self) -> AuthInfo | None: + """The forwarded permission, if there is one.""" + with self._lock: + return self._auth_info + + @property + def granted(self) -> bool: + return self.auth_info is not None + + @property + def token(self) -> str | None: + """The forwarded token for secured actions. Without one: None if the authentication is + off, an AutomationPermissionError if it is on.""" + if (info := self.auth_info) is not None: + return info.token + if self.enabled: + raise AutomationPermissionError( + "No user has given the AareBec service permission to act on their behalf: " + "authenticate from a client first (grant_automation_permission)" + ) + return None + + def clear(self) -> None: + """Forget the forwarded permission, e.g. once the server has rejected its token.""" + with self._lock: + self._auth_info = None + self._publish_status() + + def status(self) -> MXAutomationPermissionStatusMessage: + """The current permission, as published on `AuthEndpoints.automation_permission_status()`.""" + info = self.auth_info + if info is None: + return MXAutomationPermissionStatusMessage(granted=False) + claims = info.claims + staff, expires_at = claims.get("staff"), claims.get("exp") + return MXAutomationPermissionStatusMessage( + granted=True, + username=info.username, + pgroups=info.pgroups, + staff=staff if isinstance(staff, bool) else None, + expires_at=float(expires_at) if isinstance(expires_at, (int, float)) else None, + received_at=info.received_at, + ) + + def _publish_status(self) -> None: + """Publish the status, once the service has started (before, there is no connector).""" + if self._listening: + self._client.connector.set_and_publish( + AuthEndpoints.automation_permission_status(), self.status() + ) diff --git a/mx_bec/endpoints.py b/mx_bec/endpoints.py index 38565e1..f452ac1 100644 --- a/mx_bec/endpoints.py +++ b/mx_bec/endpoints.py @@ -2,6 +2,9 @@ from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp from bec_lib.messages import AvailableResourceMessage, BoolConfigDefaultFalse from mx_bec.messages import ( + MXAutomationPermissionMessage, + MXAutomationPermissionStatusMessage, + MXForwardedAuthPublicKeyMessage, MXMeasurementSequenceMessage, MXQueueChangedMessage, MXSampleExecutionMessage, @@ -58,6 +61,41 @@ class StateEndpoints: ) +class AuthEndpoints: + """Endpoints through which a client gives the AareBec service permission to act on a user's + behalf, see `mx_bec.automation_permission`.""" + + @staticmethod + def forwarded_auth_public_key(): + """The public key which the AareBec service generated when it started. Clients encrypt + the token they forward with it.""" + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/auth/forwarded_auth_public_key", + message_type=MXForwardedAuthPublicKeyMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + @staticmethod + def automation_permission(): + """Stream to which clients add a user's encrypted token. The AareBec service listens to + it and takes up the latest one.""" + return EndpointInfo( + endpoint=f"{EndpointType.USER.value}/mx/auth/automation_permission", + message_type=MXAutomationPermissionMessage, + message_op=MessageOp.STREAM, + ) + + @staticmethod + def automation_permission_status(): + """The current permission of the AareBec service: whether a token has been forwarded, + by whom, and for which pgroups. Updated by the service whenever it changes.""" + return EndpointInfo( + endpoint=f"{EndpointType.INFO.value}/mx/auth/automation_permission_status", + message_type=MXAutomationPermissionStatusMessage, + message_op=MessageOp.SET_PUBLISH, + ) + + class ActorEndpoints: """Per-actor configuration, keyed by the actor's `config_key`.""" diff --git a/mx_bec/external_services/aaredaq.py b/mx_bec/external_services/aaredaq.py index cd0fcc3..a403af1 100644 --- a/mx_bec/external_services/aaredaq.py +++ b/mx_bec/external_services/aaredaq.py @@ -1,13 +1,9 @@ from __future__ import annotations -import json -import subprocess -import time from typing import TYPE_CHECKING, Any import requests from aarecommon.config.beamline import cfg_get, mx_beamline -from aarecommon.models.auth import BatonStatus from aarecommon.models.beamline import MXBeamline from bec_lib.logger import bec_logger @@ -25,11 +21,8 @@ DEFAULT_CERT_PATHS = { MXBeamline.X06DA: "/sls/x06da/misc/.cert/6d.crt", MXBeamline.X10SA: "/sls/x10sa/misc/.cert/10s.crt", } -TOKEN_TIMEOUT_S = 120.0 -REQUEST_TIMEOUT_S = 30.0 # for quick calls such as the baton endpoints +REQUEST_TIMEOUT_S = 30.0 MOUNT_TIMEOUT_S = 600.0 # the mount endpoint blocks until the sample is mounted -BATON_WAIT_S = 60.0 # covers the server's 30 s for the current holder to answer a request -BATON_POLL_INTERVAL_S = 1.0 class AareDaqError(RuntimeError): @@ -40,11 +33,10 @@ class AareDaq: """Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses: mounting a sample. - Mirrors how the AareDAQ GUI talks to the server: a bearer token is obtained once, lazily, by - Kerberos (`curl --negotiate` against the Apache proxy in front of the server, exactly as - `aare.gui.auth.auth` does), and is renewed once if the server answers 401. The server URL and - its certificate come from the aarecommon beamline config unless given. AareDAQ only mounts - for the session holding the beamline baton, so it is taken first if not held yet. + The service has no identity of its own towards AareDAQ: every request is made with the + bearer token of a user who gave the service permission to act on their behalf, see + `mx_bec.automation_permission`. Without such a token no request is made. The server URL and + its certificate come from the aarecommon beamline config unless given. """ def __init__( @@ -53,7 +45,6 @@ class AareDaq: self._client = client self._url = url self._cert_path = cert_path - self._token: str | None = None self._session = requests.Session() @property @@ -74,34 +65,16 @@ class AareDaq: raise AareDaqError(f"No AareDAQ certificate configured for beamline {beamline}") return self._cert_path - @property - def token(self) -> str: - if self._token is None: - self._token = self._request_token() - return self._token - - def _request_token(self) -> str: - """POST /token through the Kerberos (SPNEGO) proxy; needs a valid ticket (kinit).""" - cmd = ["curl", "-s", "--cacert", self.cert_path, "--negotiate", "-u", ":", "-XPOST"] - cmd.append(f"{self.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: + def _token(self) -> str: + """The token which a user forwarded to the service. Needed for every request, whether + or not the automation permission is enforced otherwise.""" + info = self._client.automation_permission.auth_info + if info is None: raise AareDaqError( - f"AareDAQ token request failed (curl exit {result.returncode}): " - f"{result.stderr[:500]}. Is the Kerberos ticket valid (kinit)?" + "No token for AareDAQ: a user must first give the AareBec service permission to " + "act on their behalf (mx_bec.automation_permission.grant_automation_permission)" ) - try: - token = json.loads(result.stdout).get("access_token") - except json.JSONDecodeError as e: - raise AareDaqError(f"AareDAQ token response is not JSON: {result.stdout[:500]}") from e - if not isinstance(token, str) or not token: - raise AareDaqError(f"AareDAQ token response has no access_token: {result.stdout[:500]}") - return token + return info.token def _request( self, @@ -112,34 +85,33 @@ class AareDaq: body: dict[str, Any] | None = None, timeout_s: float = REQUEST_TIMEOUT_S, ) -> Any: - """Call `endpoint` with the bearer token and return the decoded JSON response. A 401 is - retried once with a fresh token; any other error becomes an AareDaqError.""" - for attempt in range(2): - try: - resp = self._session.request( - method, - f"{self.url}{endpoint}", - params=params, - json=body, - headers={"Authorization": f"Bearer {self.token}"}, - verify=self.cert_path, - timeout=timeout_s, - ) - except requests.RequestException as e: - raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e - if resp.status_code == 401 and attempt == 0: - logger.info("AareDAQ rejected the token, requesting a new one") - self._token = None - continue - if not resp.ok: - raise AareDaqError( - f"AareDAQ {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}" - ) - return resp.json() - raise AssertionError("unreachable") # pragma: no cover - - def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any: - return self._request("GET", endpoint, timeout_s=timeout_s) + """Call `endpoint` with the forwarded bearer token and return the decoded JSON response. + If the server rejects the token (401), the permission is dropped, so that a user has to + grant it again. Any error becomes an AareDaqError.""" + token = self._token() + try: + resp = self._session.request( + method, + f"{self.url}{endpoint}", + params=params, + json=body, + headers={"Authorization": f"Bearer {token}"}, + verify=self.cert_path, + timeout=timeout_s, + ) + except requests.RequestException as e: + raise AareDaqError(f"AareDAQ {method} {endpoint} failed: {e}") from e + if resp.status_code == 401: + self._client.automation_permission.clear() + raise AareDaqError( + f"AareDAQ rejected the forwarded token for {method} {endpoint} (401): it may " + f"have expired. Grant the automation permission again. {resp.text[:500]}" + ) + if not resp.ok: + raise AareDaqError( + f"AareDAQ {method} {endpoint} failed with {resp.status_code}: {resp.text[:500]}" + ) + return resp.json() def _post( self, @@ -151,48 +123,10 @@ class AareDaq: ) -> Any: return self._request("POST", endpoint, params=params, body=body, timeout_s=timeout_s) - # ---- baton: AareDAQ only runs hardware operations for the session holding the baton ---- - - def baton_status(self) -> BatonStatus: - return BatonStatus.model_validate(self._get("/baton/status")) - - def take_baton( - self, wait_s: float = BATON_WAIT_S, poll_interval_s: float = BATON_POLL_INTERVAL_S - ) -> None: - """Take the baton. Granted at once if the beamline is vacant (or we are staff); otherwise - the current holder is asked, and we poll until they accept or their time to answer runs - out, for up to `wait_s`. Raises AareDaqError if refused or not granted in time.""" - result = self._post("/baton/request", timeout_s=REQUEST_TIMEOUT_S) - if result.get("granted") or result.get("already_holder"): - logger.info(f"AareDAQ baton: {result.get('message')}") - return - if not (result.get("pending") or result.get("queued")): - raise AareDaqError(f"AareDAQ refused the baton request: {result.get('message')}") - logger.info(f"AareDAQ baton: {result.get('message')}; waiting for it") - deadline = time.monotonic() + wait_s - while True: - time.sleep(poll_interval_s) - result = self._get("/baton/check_timeout") - if result.get("granted"): - logger.info("AareDAQ baton acquired") - return - if result.get("refused"): - raise AareDaqError("AareDAQ baton request was refused by the current holder") - if time.monotonic() > deadline: - raise AareDaqError(f"AareDAQ baton not granted within {wait_s} s: {result}") - - def ensure_baton(self) -> None: - """Take the baton unless this session already holds it.""" - if not self.baton_status().you_are_holder: - self.take_baton() - - # ---- hardware operations ---- - def mount_sample( self, dbid: int, reference: bool = False, timeout_s: float = MOUNT_TIMEOUT_S ) -> None: """Mount the sample with database id `dbid` (from the reference tools if `reference`).""" - self.ensure_baton() logger.info(f"AareDAQ: mounting sample {dbid}{' (reference tool)' if reference else ''}") self._post( "/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s diff --git a/mx_bec/messages.py b/mx_bec/messages.py index 5b7d202..4af4920 100644 --- a/mx_bec/messages.py +++ b/mx_bec/messages.py @@ -59,3 +59,48 @@ class OpticalPredictionMessage(BECMessage): timestamp: float = Field(default_factory=time.time) prediction: LatestPredictionModel + + +class MXForwardedAuthPublicKeyMessage(BECMessage): + """The public key of the AareBec service, for clients to encrypt the token with which they + give the service permission to act on their behalf.""" + + msg_type: ClassVar[str] = "mx_forwarded_auth_public_key_message" + + public_key_pem: str = Field(description="RSA public key, PEM encoded SubjectPublicKeyInfo") + key_id: str = Field(description="Fingerprint of the key, changes when the service restarts") + + +class MXAutomationPermissionMessage(BECMessage): + """A user's token for secured actions, encrypted for the AareBec service: the token is + encrypted with a one-off AES-256-GCM key, and that key with the service's RSA public key + (OAEP, SHA-256). The binary fields are base64 encoded.""" + + msg_type: ClassVar[str] = "mx_automation_permission_message" + + username: str = Field(description="Who the token belongs to") + key_id: str = Field(description="`key_id` of the public key the token was encrypted for") + encrypted_key: str = Field(description="The AES key, RSA-OAEP encrypted") + nonce: str = Field(description="The AES-GCM nonce") + encrypted_token: str = Field(description="The token, AES-GCM encrypted") + + +class MXAutomationPermissionStatusMessage(BECMessage): + """Whether the AareBec service has permission to act on a user's behalf, and whose. The + pgroups and expiry are read from the forwarded token as it is: only the server which issued + the token can verify it.""" + + msg_type: ClassVar[str] = "mx_automation_permission_status_message" + + granted: bool = Field(description="Whether a user's token has been forwarded") + username: str | None = Field(default=None, description="Who forwarded the token") + pgroups: list[str] | None = Field( + default=None, description="The pgroups named in the token, if it names any" + ) + staff: bool | None = Field(default=None, description="The staff flag of the token, if any") + expires_at: float | None = Field( + default=None, description="When the token expires (unix time), if it says" + ) + received_at: float | None = Field( + default=None, description="When the token was forwarded (unix time)" + ) diff --git a/mx_bec/service.py b/mx_bec/service.py index b4cdecf..4138dca 100644 --- a/mx_bec/service.py +++ b/mx_bec/service.py @@ -10,6 +10,7 @@ from bec_lib.logger import bec_logger from redis.client import Redis from mx_bec.actor_manager import AareActorManager +from mx_bec.automation_permission import AutomationPermission from mx_bec.constants import AareBecWorkflowState from mx_bec.endpoints import QueueEndpoints from mx_bec.external_services.aaredaq import AareDaq @@ -55,7 +56,11 @@ class AareBec(BECClient): self.actor_manager: AareActorManager | None = None self.optical_prediction = OpticalPrediction(client=self) self.jfjoch = JFJoch(client=self) # connects lazily on first use - self.aaredaq = AareDaq(client=self) # authenticates lazily on first use + # permission to act on a user's behalf, forwarded by a client; off unless set in the env + self.automation_permission = AutomationPermission( + client=self, enabled=AutomationPermission.enabled_in_environment() + ) + self.aaredaq = AareDaq(client=self) # uses the token forwarded to automation_permission self.tasks = MxTasks[Server](self) self.task_queue: MxTaskQueue | None = None self.sample_info: SampleInfo | None = None @@ -69,6 +74,7 @@ class AareBec(BECClient): def start(self): super().start() + self.automation_permission.start() self._start_actor_manager() self.task_queue = MxTaskQueue(self, self.tasks) self.task_queue.start() @@ -121,6 +127,7 @@ class AareBec(BECClient): self.actor_manager.shutdown() self.actor_manager = None if self.started: # the connector only exists once the client has been started + self.automation_permission.shutdown() self.connector.unregister(QueueEndpoints.task_request(), cb=self._on_task_request) if self.task_queue is not None: self.task_queue.shutdown() diff --git a/pyproject.toml b/pyproject.toml index 305055a..8686295 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ "aarelcinfer_client @ https://gitea.psi.ch/api/packages/mx/pypi/files/aarelcinfer-client/0.2.0/aarelcinfer_client-0.2.0-py3-none-any.whl", "jfjoch_client @ https://gitea.psi.ch/api/packages/mx/pypi/files/jfjoch-client/1.0.0rc188/jfjoch_client-1.0.0rc188-py3-none-any.whl", "bec_lib>=3.130.3", + "cryptography", "bec-server>=3.130.3", "bec-ipython-client>=3.130.3", "ophyd_devices>=1.46", diff --git a/tests/unit/test_aaredaq.py b/tests/unit/test_aaredaq.py index 1cd0e12..3cb596e 100644 --- a/tests/unit/test_aaredaq.py +++ b/tests/unit/test_aaredaq.py @@ -1,18 +1,14 @@ -import subprocess -from unittest.mock import MagicMock, call, patch +from unittest.mock import MagicMock, patch import pytest -from aarecommon.models.auth import BatonStatus +import requests +from mx_bec.automation_permission import AuthInfo from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" -def _curl_result(stdout='{"access_token": "' + TOKEN + '"}', returncode=0, stderr=""): - return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) - - def _response(status_code=200, json_data=None, text=""): resp = MagicMock(status_code=status_code, ok=200 <= status_code < 300, text=text) resp.json.return_value = json_data @@ -20,47 +16,31 @@ def _response(status_code=200, json_data=None, text=""): @pytest.fixture -def curl(): - with patch( - "mx_bec.external_services.aaredaq.subprocess.run", return_value=_curl_result() - ) as run: - yield run - - -def _status(you_are_holder: bool) -> dict: - return BatonStatus(you_are_holder=you_are_holder).model_dump(mode="json") +def client(): + """An AareBec to which a user has forwarded their token.""" + client = MagicMock() + client.automation_permission.auth_info = AuthInfo(username="e12345", token=TOKEN) + return client @pytest.fixture -def daq(curl): - """Client with a mocked HTTP session: by default this session holds the baton and every - POST answers "OK".""" - daq = AareDaq(MagicMock(), url=URL, cert_path=CERT) +def daq(client): + """Client with a mocked HTTP session, which answers "OK" unless `daq._response` is set.""" + daq = AareDaq(client, url=URL, cert_path=CERT) daq._session = MagicMock() - responses = {"GET": _response(json_data=_status(True)), "POST": _response(json_data="OK")} - daq._session.request.side_effect = lambda method, *a, **k: responses[method] - daq._responses = responses + daq._response = _response(json_data="OK") + daq._session.request.side_effect = lambda *a, **k: daq._response return daq -def _calls(daq, method): - """(url, kwargs) of the recorded requests of the given method, in order.""" - return [ - (c.args[1], c.kwargs) for c in daq._session.request.call_args_list if c.args[0] == method - ] +def _calls(daq): + """(method, url, kwargs) of the recorded requests, in order.""" + return [(c.args[0], c.args[1], c.kwargs) for c in daq._session.request.call_args_list] -def _set_posts(daq, *responses): - """Make successive POSTs answer with the given responses (GETs keep the default).""" - posts = iter(responses) - daq._session.request.side_effect = lambda method, *a, **k: ( - next(posts) if method == "POST" else daq._responses["GET"] - ) - - -def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch): +def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(client, monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) - daq = AareDaq(MagicMock()) # must not need the beamline environment yet + daq = AareDaq(client) # must not need the beamline environment yet with ( patch("mx_bec.external_services.aaredaq.mx_beamline", return_value="X10SA"), patch( @@ -72,40 +52,11 @@ def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monke assert cfg_get.call_args_list[0].args[0] == "gui.daq.daq_url" -def test_token_is_requested_lazily_by_kerberos_curl(daq, curl): - curl.assert_not_called() - assert daq.token == TOKEN - assert daq.token == 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"), - ], -) -def test_token_request_failures(daq, curl, result, match): - curl.return_value = result - with pytest.raises(AareDaqError, match=match): - _ = daq.token - - -def test_token_request_timeout(daq, curl): - curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) - with pytest.raises(AareDaqError, match="token request failed"): - _ = daq.token - - -def test_mount_sample(daq): +def test_mount_sample_uses_the_forwarded_token(daq): daq.mount_sample(42) - assert _calls(daq, "POST") == [ + assert _calls(daq) == [ ( + "POST", f"{URL}/sample/mount", { "params": {"dbid": 42, "reference": False}, @@ -118,92 +69,43 @@ def test_mount_sample(daq): ] -def test_expired_token_is_renewed_once(daq, curl): - curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')] - _set_posts(daq, _response(401), _response(json_data="OK")) - daq.mount_sample(1) - headers = [kwargs["headers"]["Authorization"] for _, kwargs in _calls(daq, "POST")] - assert headers == [f"Bearer {TOKEN}", "Bearer new"] - assert daq.token == "new" +def test_mount_sample_from_the_reference_tools(daq): + daq.mount_sample(7, reference=True) + [(_, _, kwargs)] = _calls(daq) + assert kwargs["params"] == {"dbid": 7, "reference": True} -def test_persistent_401_is_an_error(daq): - _set_posts(daq, _response(401, text="nope"), _response(401, text="nope")) - with pytest.raises(AareDaqError, match="401"): +def test_no_request_is_made_without_a_forwarded_token(daq, client): + client.automation_permission.auth_info = None + with pytest.raises(AareDaqError, match="No token for AareDAQ"): daq.mount_sample(1) - assert len(_calls(daq, "POST")) == 2 + daq._session.request.assert_not_called() -def test_http_error_reports_status_and_body(daq): - _set_posts(daq, _response(422, text='{"detail": "bad request"}')) +def test_the_latest_forwarded_token_is_used(daq, client): + daq.mount_sample(1) + client.automation_permission.auth_info = AuthInfo(username="e99999", token="new") + daq.mount_sample(2) + headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(daq)] + assert headers == [f"Bearer {TOKEN}", "Bearer new"] + + +def test_a_rejected_token_drops_the_permission(daq, client): + daq._response = _response(401, text="nope") + with pytest.raises(AareDaqError, match="rejected the forwarded token"): + daq.mount_sample(1) + assert len(_calls(daq)) == 1 # there is no other token to try again with + client.automation_permission.clear.assert_called_once_with() + + +def test_http_error_reports_status_and_body(daq, client): + daq._response = _response(422, text='{"detail": "bad request"}') with pytest.raises(AareDaqError, match="422.*bad request"): daq.mount_sample(1) + client.automation_permission.clear.assert_not_called() -# ---- baton ---- - - -def test_baton_status(daq): - assert daq.baton_status() == BatonStatus(you_are_holder=True) - [(url, kwargs)] = _calls(daq, "GET") - assert url == f"{URL}/baton/status" and kwargs["timeout"] == 30.0 - - -def test_hardware_calls_skip_the_baton_request_when_already_holder(daq): - daq.mount_sample(1) - assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/sample/mount"] - - -def test_hardware_calls_take_the_baton_first(daq): - daq._responses["GET"] = _response(json_data=_status(False)) - _set_posts(daq, _response(json_data={"granted": True}), _response(json_data="OK")) - daq.mount_sample(1) - assert [url for url, _ in _calls(daq, "POST")] == [ - f"{URL}/baton/request", - f"{URL}/sample/mount", - ] - - -@pytest.mark.parametrize("result", [{"granted": True}, {"already_holder": True}]) -def test_take_baton_immediately(daq, result): - _set_posts(daq, _response(json_data=result)) - daq.take_baton() - assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/request"] - - -def test_take_baton_refused_by_policy(daq): - _set_posts(daq, _response(json_data={"error": True, "message": "disabled by policy"})) - with pytest.raises(AareDaqError, match="disabled by policy"): - daq.take_baton() - - -def test_take_baton_waits_for_the_holder(daq): - _set_posts(daq, _response(json_data={"pending": True, "message": "asked"})) - checks = iter([{"pending": True, "remaining_seconds": 20}, {"granted": True}]) - daq._responses["GET"] = MagicMock() - daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200 - daq._responses["GET"].json.side_effect = lambda: next(checks) - with patch("mx_bec.external_services.aaredaq.time.sleep") as sleep: - daq.take_baton(poll_interval_s=0.5) - assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2 - sleep.assert_called_with(0.5) - - -def test_take_baton_refused_by_holder(daq): - _set_posts(daq, _response(json_data={"pending": True})) - daq._responses["GET"] = _response(json_data={"refused": True}) - with ( - patch("mx_bec.external_services.aaredaq.time.sleep"), - pytest.raises(AareDaqError, match="refused"), - ): - daq.take_baton() - - -def test_take_baton_gives_up_after_wait(daq): - _set_posts(daq, _response(json_data={"queued": True})) - daq._responses["GET"] = _response(json_data={"queued": True}) - with ( - patch("mx_bec.external_services.aaredaq.time.sleep"), - pytest.raises(AareDaqError, match="not granted"), - ): - daq.take_baton(wait_s=0) +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) diff --git a/tests/unit/test_automation_permission.py b/tests/unit/test_automation_permission.py new file mode 100644 index 0000000..dad6be0 --- /dev/null +++ b/tests/unit/test_automation_permission.py @@ -0,0 +1,208 @@ +import base64 +import json +import time +from unittest.mock import MagicMock + +import fakeredis +import pytest +from bec_lib.redis_connector import RedisConnector + +from mx_bec.automation_permission import ( + ENABLED_ENV_VAR, + AutomationPermission, + AutomationPermissionError, + encrypt_token, + grant_automation_permission, +) +from mx_bec.endpoints import AuthEndpoints +from mx_bec.messages import MXAutomationPermissionMessage, MXForwardedAuthPublicKeyMessage + +# as long as a real token, which is far more than RSA 2048 can encrypt directly +TOKEN = "eyJhbGciOiJIUzI1NiJ9." + "x" * 600 + ".signature" + + +@pytest.fixture(scope="module") +def keypair_permission(): + """Generating a key pair is slow, so the tests of one module share one.""" + return AutomationPermission(MagicMock()) + + +@pytest.fixture +def permission(keypair_permission): + keypair_permission._client = MagicMock() + keypair_permission.enabled = False + keypair_permission.clear() + return keypair_permission + + +def _public_key(permission) -> MXForwardedAuthPublicKeyMessage: + return MXForwardedAuthPublicKeyMessage( + public_key_pem=permission.public_key_pem, key_id=permission.key_id + ) + + +def test_generates_a_2048_bit_rsa_key_pair(permission): + assert permission._private_key.key_size == 2048 + assert permission.public_key_pem.startswith("-----BEGIN PUBLIC KEY-----") + + +def test_authentication_is_off_by_default(monkeypatch): + monkeypatch.delenv(ENABLED_ENV_VAR, raising=False) + assert not AutomationPermission.enabled_in_environment() + monkeypatch.setenv(ENABLED_ENV_VAR, "1") + assert AutomationPermission.enabled_in_environment() + + +def test_start_publishes_the_public_key_and_listens_to_the_stream(permission): + permission.start() + connector = permission._client.connector + endpoint, msg = connector.set_and_publish.call_args_list[0].args + assert endpoint == AuthEndpoints.forwarded_auth_public_key() + assert msg == _public_key(permission) + connector.register.assert_called_once_with( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + permission.shutdown() + connector.unregister.assert_called_once_with( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + + +def test_a_forwarded_token_populates_the_auth_info(permission): + assert permission.auth_info is None and not permission.granted + msg = encrypt_token(_public_key(permission), "e12345", TOKEN) + permission._on_permission({"data": msg}) + assert permission.granted + assert (permission.auth_info.username, permission.auth_info.token) == ("e12345", TOKEN) + assert permission.token == TOKEN + assert TOKEN not in repr(permission.auth_info) + + +def test_the_token_is_not_readable_on_the_stream(permission): + msg = encrypt_token(_public_key(permission), "e12345", TOKEN) + assert TOKEN not in msg.model_dump_json() + # a fresh key for every message + assert ( + encrypt_token(_public_key(permission), "e12345", TOKEN).encrypted_key != msg.encrypted_key + ) + + +def test_without_a_token_only_an_enabled_permission_refuses(permission): + assert permission.token is None + permission.enabled = True + with pytest.raises(AutomationPermissionError, match="No user has given"): + _ = permission.token + + +@pytest.mark.parametrize( + "tamper", + [ + lambda msg: msg.model_copy(update={"username": "someone_else"}), + lambda msg: msg.model_copy(update={"key_id": "0" * 16}), + lambda msg: msg.model_copy(update={"encrypted_token": msg.encrypted_token[4:]}), + lambda msg: msg.model_copy(update={"encrypted_key": "not base64!"}), + ], +) +def test_a_message_which_cannot_be_decrypted_keeps_the_current_permission(permission, tamper): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", TOKEN)}) + bad = tamper(encrypt_token(_public_key(permission), "e99999", "other token")) + permission._on_permission({"data": bad}) + assert (permission.auth_info.username, permission.token) == ("e12345", TOKEN) + + +def test_a_token_for_another_services_key_is_ignored(permission): + other = AutomationPermission(MagicMock()) + permission._on_permission({"data": encrypt_token(_public_key(other), "e12345", TOKEN)}) + assert not permission.granted + + +def test_clear_forgets_the_permission(permission): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", TOKEN)}) + permission.clear() + assert not permission.granted + + +@pytest.fixture +def connector(): + conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis()) + conn._managed_connection.flushall() + yield conn + conn.shutdown() + + +def test_client_grants_permission_through_redis(permission, connector): + """The whole path: the service publishes its key and listens, the client reads the key and + adds the encrypted token to the stream, the service decrypts it.""" + permission._client.connector = connector + permission.start() + try: + grant_automation_permission(connector, "e12345", TOKEN) + deadline = time.monotonic() + 5 + while not permission.granted and time.monotonic() < deadline: + time.sleep(0.01) + assert permission.granted + assert (permission.auth_info.username, permission.token) == ("e12345", TOKEN) + on_stream = connector.get_last(AuthEndpoints.automation_permission(), "data") + assert isinstance(on_stream, MXAutomationPermissionMessage) + finally: + permission.shutdown() + + +def test_client_cannot_grant_permission_without_a_published_key(): + connector = MagicMock() + connector.get.return_value = None + with pytest.raises(AutomationPermissionError, match="has not published a public key"): + grant_automation_permission(connector, "e12345", TOKEN) + connector.xadd.assert_not_called() + + +def _jwt(claims: dict) -> str: + """A token shaped like those of AareDAQ (the signature is not checked by the service).""" + + def segment(data: dict) -> str: + return base64.urlsafe_b64encode(json.dumps(data).encode()).decode().rstrip("=") + + return f"{segment({'alg': 'HS256', 'typ': 'JWT'})}.{segment(claims)}.signature" + + +def _published_status(permission): + endpoint, msg = permission._client.connector.set_and_publish.call_args.args + assert endpoint == AuthEndpoints.automation_permission_status() + return msg + + +def test_status_is_published_on_start_grant_and_clear(permission): + permission.start() + status = _published_status(permission) + assert not status.granted + assert (status.username, status.pgroups, status.staff, status.expires_at) == (None,) * 4 + + claims = {"sub": "e12345", "pgroups": ["p16371", "p20000"], "staff": False, "exp": 1.8e9} + token = _jwt(claims | {"session": 1}) + permission._on_permission({"data": encrypt_token(_public_key(permission), "e12345", token)}) + status = _published_status(permission) + assert (status.granted, status.username) == (True, "e12345") + assert status.pgroups == ["p16371", "p20000"] + assert (status.staff, status.expires_at) == (False, 1.8e9) + assert status.received_at == permission.auth_info.received_at + assert token not in status.model_dump_json() + + permission.clear() + status = _published_status(permission) + assert (status.granted, status.username, status.pgroups) == (False, None, None) + permission.shutdown() + + +def test_status_has_no_pgroups_for_a_token_which_names_none(permission): + permission.start() + for token in (TOKEN, "not a jwt", _jwt({"sub": "e12345"})): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e1", token)}) + status = _published_status(permission) + assert (status.granted, status.pgroups, status.expires_at) == (True, None, None) + permission.shutdown() + + +def test_status_is_not_published_before_start(permission): + permission._on_permission({"data": encrypt_token(_public_key(permission), "e1", TOKEN)}) + permission._client.connector.set_and_publish.assert_not_called() + assert permission.status().granted diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index 509bf7b..f52c3d1 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -6,7 +6,7 @@ from bec_lib.service_config import ServiceConfig from bec_lib.tests.utils import ConnectorMock from mx_bec.constants import AareBecWorkflowState -from mx_bec.endpoints import QueueEndpoints +from mx_bec.endpoints import AuthEndpoints, QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage from mx_bec.service import DUMMY_ENERGY_EV, DUMMY_FULL_FLUX_PH_S, AareBec from mx_bec.tasks import MxTasks, RoleT, Server, task @@ -74,11 +74,23 @@ def test_shutdown_stops_actor_manager_and_task_queue(service): def test_start_registers_task_request_callback(started_service): service, *_ = started_service - service.connector.register.assert_called_once_with( + service.connector.register.assert_any_call( QueueEndpoints.task_request(), cb=service._on_task_request ) +def test_start_publishes_the_forwarded_auth_public_key_and_listens(started_service): + service, *_ = started_service + permission = service.automation_permission + assert not permission.enabled # off unless turned on in the environment + endpoint, msg = service.connector.set_and_publish.call_args_list[0].args + assert endpoint == AuthEndpoints.forwarded_auth_public_key() + assert msg.public_key_pem == permission.public_key_pem + service.connector.register.assert_any_call( + AuthEndpoints.automation_permission(), cb=permission._on_permission + ) + + def test_shutdown_unregisters_task_request_callback(service): service.started = True service.connector = MagicMock()