make aaredaq usable from client

This commit is contained in:
perl_d committed 2026-12-03 11:23:28 +01:00
1 parent 56d41ce42a
commit 403f3da8f3
2 files changed
+248 -42

No files matched your search

+123 -40
View File
@@ -8,6 +8,7 @@ import requests
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.models.beamline import MXBeamline
from bec_lib.logger import bec_logger
from pydantic import BaseModel, ConfigDict
if TYPE_CHECKING:
from mx_bec.service import AareBec
@@ -32,6 +33,21 @@ class AareDaqError(RuntimeError):
"""A call to the AareDAQ server failed."""
class LoadedSampleInfo(BaseModel):
"""An aareDB sample together with where it sits in the beamline's TELL: what AareDAQ answers
to `GET /sample/{sample_id}` (`aare.daq.aaredb.LoadedSampleInfo`). The sample record itself
is kept as the plain dictionary of the aareDB `Sample`, as mx_bec does not depend on the
aareDB client."""
model_config = ConfigDict(extra="allow")
sample: dict[str, Any]
puck_name: str
puck_pgroup: str
dewar_name: str | None = None
tell_position: str | None = None
def configured_url() -> str:
"""The URL of the AareDAQ server, from the aarecommon beamline config."""
beamline = mx_beamline()
@@ -81,23 +97,88 @@ def request_user_token(url: str | None = None, cert_path: str | None = None) ->
return username, token
class AareDaq:
"""Client for the part of the AareDAQ REST API (aaredaq `server.py`) which AareBec still uses:
mounting a sample.
class _ForwardedToken:
"""For the AareBec service: the token which a user forwarded to it, see
`mx_bec.automation_permission`. The service has no identity of its own towards AareDAQ."""
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__(self, client: AareBec) -> None:
self._client = client
def get(self) -> str:
# needed for every request, whether or not the permission is enforced otherwise
info = self._client.automation_permission.auth_info
if info is None:
raise AareDaqError(
"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)"
)
return info.token
def rejected(self) -> bool:
"""The server did not accept the token: drop the permission, so that a user has to grant
it again. There is no other token to try again with."""
self._client.automation_permission.clear()
return False
rejected_hint = "it may have expired. Grant the automation permission again."
class _UserToken:
"""For a user's own process: the token given, or else one requested from AareDAQ for the
user running the process when it is first needed (by Kerberos, see `request_user_token`)."""
def __init__(self, daq: AareDaq, token: str | None) -> None:
self._daq = daq
self._token = token
self._given = token is not None
def get(self) -> str:
if self._token is None:
_, self._token = request_user_token(self._daq.url, self._daq.cert_path)
return self._token
def rejected(self) -> bool:
"""The server did not accept the token. A token which was requested here is requested
again, once; one which was given cannot be renewed."""
if self._given:
return False
logger.info("AareDAQ rejected the token, requesting a new one")
self._token = None
return True
rejected_hint = "it may have expired."
class AareDaq:
"""Client for the part of the AareDAQ REST API (aaredaq `server.py`) which mx_bec uses.
Every request carries the bearer token of a user, which comes from one of two places:
- `AareDaq(client=aare_bec)`, in the AareBec service: the token which a user forwarded to
the service, see `mx_bec.automation_permission`. Without one no request is made, and if
the server rejects it the permission is dropped.
- `AareDaq()` or `AareDaq(token=...)`, in a user's own process (a BEC client, the GUI): the
user's own token. If none is given, one is requested for the user running the process
when it is first needed, which needs a valid Kerberos ticket, and requested again once if
the server rejects it.
The server URL and its certificate come from the aarecommon beamline config unless given.
"""
def __init__(
self, client: AareBec, url: str | None = None, cert_path: str | None = None
self,
client: AareBec | None = None,
url: str | None = None,
cert_path: str | None = None,
token: str | None = None,
) -> None:
self._client = client
if client is not None and token is not None:
raise ValueError("Give either the AareBec service (forwarded token) or a token")
self._url = url
self._cert_path = cert_path
self._session = requests.Session()
self._token_source: _ForwardedToken | _UserToken = (
_ForwardedToken(client) if client is not None else _UserToken(self, token)
)
@property
def url(self) -> str:
@@ -111,17 +192,6 @@ class AareDaq:
self._cert_path = configured_cert_path()
return self._cert_path
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(
"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)"
)
return info.token
def _request(
self,
method: str,
@@ -131,27 +201,30 @@ class AareDaq:
body: dict[str, Any] | None = None,
timeout_s: float = REQUEST_TIMEOUT_S,
) -> Any:
"""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()
"""Call `endpoint` with the bearer token and return the decoded JSON response. If the
server rejects the token (401), the request is repeated once if there is a new token to
be had (see the class documentation). Any error becomes an AareDaqError."""
for attempt in range(2):
token = self._token_source.get()
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:
break
if attempt == 0 and self._token_source.rejected():
continue
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]}"
f"AareDAQ rejected the token for {method} {endpoint} (401): "
f"{self._token_source.rejected_hint} {resp.text[:500]}"
)
if not resp.ok:
raise AareDaqError(
@@ -159,6 +232,9 @@ class AareDaq:
)
return resp.json()
def _get(self, endpoint: str, timeout_s: float = REQUEST_TIMEOUT_S) -> Any:
return self._request("GET", endpoint, timeout_s=timeout_s)
def _post(
self,
endpoint: str,
@@ -177,3 +253,10 @@ class AareDaq:
self._post(
"/sample/mount", params={"dbid": dbid, "reference": reference}, timeout_s=timeout_s
)
def sample_info(self, sample_id: int) -> LoadedSampleInfo:
"""The aareDB record of the sample with database id `sample_id`, with its puck, dewar
and TELL position. AareDAQ refuses if the sample is not loaded at this beamline (400),
or if the user who forwarded the token is neither in the sample's pgroup nor staff
(403); both are an AareDaqError."""
return LoadedSampleInfo.model_validate(self._get(f"/sample/{sample_id}"))
+125 -2
View File
@@ -6,7 +6,13 @@ import pytest
import requests
from mx_bec.automation_permission import AuthInfo
from mx_bec.external_services.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError, request_user_token
from mx_bec.external_services.aaredaq import (
DEFAULT_URLS,
AareDaq,
AareDaqError,
LoadedSampleInfo,
request_user_token,
)
URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def"
@@ -94,7 +100,9 @@ def test_the_latest_forwarded_token_is_used(daq, client):
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"):
with pytest.raises(
AareDaqError, match="rejected the token.*Grant the automation permission again"
):
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()
@@ -113,6 +121,55 @@ def test_connection_error_becomes_an_aaredaq_error(daq):
daq.mount_sample(1)
SAMPLE_INFO = {
"sample": {"id": 42, "sample_name": "lyso_1", "pgroup": "p16371", "position": 3},
"puck_name": "PUCK7",
"puck_pgroup": "p16371",
"dewar_name": "dewar_a",
"tell_position": "B2",
}
def test_sample_info(daq):
daq._response = _response(json_data=SAMPLE_INFO)
info = daq.sample_info(42)
assert info == LoadedSampleInfo(**SAMPLE_INFO)
assert (info.sample["sample_name"], info.puck_name, info.tell_position) == (
"lyso_1",
"PUCK7",
"B2",
)
[(method, url, kwargs)] = _calls(daq)
assert (method, url) == ("GET", f"{URL}/sample/42")
assert kwargs["headers"] == {"Authorization": f"Bearer {TOKEN}"}
assert kwargs["timeout"] == 30.0
def test_sample_info_without_dewar_and_tell_position(daq):
daq._response = _response(
json_data={"sample": {"id": 1}, "puck_name": "P", "puck_pgroup": "p1"}
)
info = daq.sample_info(1)
assert (info.dewar_name, info.tell_position) == (None, None)
@pytest.mark.parametrize(
"status, text", [(400, "Sample 42 is not loaded at this beamline."), (403, "not in p16371")]
)
def test_sample_info_refused(daq, client, status, text):
daq._response = _response(status, text=text)
with pytest.raises(AareDaqError, match=f"{status}.*{text}"):
daq.sample_info(42)
client.automation_permission.clear.assert_not_called()
def test_sample_info_needs_a_forwarded_token(daq, client):
client.automation_permission.auth_info = None
with pytest.raises(AareDaqError, match="No token for AareDAQ"):
daq.sample_info(42)
daq._session.request.assert_not_called()
# ---- the token request, which clients (not the service) make for the user running them ----
@@ -159,3 +216,69 @@ 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)
# ---- used directly by a user, with their own token instead of one forwarded to the service ----
@pytest.fixture
def user_daq():
"""Client without the AareBec service, with a mocked HTTP session answering "OK"."""
daq = AareDaq(url=URL, cert_path=CERT)
daq._session = MagicMock()
daq._session.request.side_effect = None
daq._session.request.return_value = _response(json_data="OK")
return daq
def test_user_token_is_requested_lazily_and_once(user_daq, curl):
curl.assert_not_called()
user_daq.mount_sample(1)
user_daq.mount_sample(2)
curl.assert_called_once()
headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(user_daq)]
assert headers == [f"Bearer {TOKEN}"] * 2
def test_rejected_user_token_is_renewed_once(user_daq, curl):
new = json.dumps({"access_token": "new", "info": {"sub": "e12345"}})
curl.side_effect = [_curl_result(), _curl_result(new)]
user_daq._session.request.side_effect = [_response(401), _response(json_data="OK")]
user_daq.mount_sample(1)
headers = [kwargs["headers"]["Authorization"] for _, _, kwargs in _calls(user_daq)]
assert headers == [f"Bearer {TOKEN}", "Bearer new"]
def test_persistently_rejected_user_token_is_an_error(user_daq, curl):
user_daq._session.request.return_value = _response(401, text="nope")
with pytest.raises(AareDaqError, match="rejected the token.*nope"):
user_daq.mount_sample(1)
assert len(_calls(user_daq)) == 2
assert curl.call_count == 2
def test_failed_user_token_request_is_an_error_before_any_request(user_daq, curl):
curl.return_value = _curl_result(returncode=6, stderr="could not resolve")
with pytest.raises(AareDaqError, match="curl exit 6"):
user_daq.sample_info(1)
user_daq._session.request.assert_not_called()
def test_a_given_token_is_used_and_not_renewed(curl):
daq = AareDaq(url=URL, cert_path=CERT, token="mine")
daq._session = MagicMock()
daq._session.request.return_value = _response(json_data="OK")
daq.mount_sample(1)
[(_, _, kwargs)] = _calls(daq)
assert kwargs["headers"] == {"Authorization": "Bearer mine"}
daq._session.request.return_value = _response(401, text="nope")
with pytest.raises(AareDaqError, match="rejected the token"):
daq.mount_sample(1)
assert len(_calls(daq)) == 2 # the one above and one rejected: no second attempt
curl.assert_not_called()
def test_service_and_token_cannot_both_be_given(client):
with pytest.raises(ValueError, match="either"):
AareDaq(client, token="mine")