diff --git a/pyproject.toml b/pyproject.toml index a4758776..75e351dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,6 +64,9 @@ markers = ["integration: tests that require external systems or secrets"] requires = ["setuptools>=75.6.0"] build-backend = "setuptools.build_meta" +[tool.setuptools.package-data] +"aare.daq" = ["*.json"] + [tool.black] line-length = 100 skip-magic-trailing-comma = true diff --git a/src/aare/daq/__init__.py b/src/aare/daq/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/daq/aaredb.py b/src/aare/daq/aaredb.py index 06c7d66a..94d85436 100644 --- a/src/aare/daq/aaredb.py +++ b/src/aare/daq/aaredb.py @@ -4,7 +4,7 @@ import aareDB from aarecommon.config.logger import setup_logger from aarecommon.config.logger_events import log_timing from aarecommon.models.beamline import MXBeamline -from aareDB.models import Sample +from aareDB.models.sample import Sample logger = setup_logger("aareDAQ") diff --git a/src/aare/daq/auth.py b/src/aare/daq/auth.py index d85a8dd8..248e50f8 100644 --- a/src/aare/daq/auth.py +++ b/src/aare/daq/auth.py @@ -98,7 +98,7 @@ def generate_session() -> int: return secrets.randbits(31) -def authenticate_user(username: str) -> str: +def authenticate_user(username: str) -> tuple[TokenData, str]: user_info = pwd.getpwnam(username) groups = os.getgrouplist(user_info.pw_name, user_info.pw_gid) @@ -108,8 +108,8 @@ def authenticate_user(username: str) -> str: staff = ( "unx-mxgroup" in supplementary_groups or "unx-sls_mx" in supplementary_groups or super_user ) - token = TokenData(sub=username, pgroups=pgroups, staff=staff, session=generate_session()) - return create_access_token(token) + token_data = TokenData(sub=username, pgroups=pgroups, staff=staff, session=generate_session()) + return token_data, create_access_token(token_data) def parse_token(token: str = Depends(oauth2_scheme)) -> TokenData: diff --git a/src/aare/daq/dummy_samples.json b/src/aare/daq/dummy_samples.json new file mode 100644 index 00000000..2fda7491 --- /dev/null +++ b/src/aare/daq/dummy_samples.json @@ -0,0 +1,10 @@ +[ + {"sample_id": 1, "sample_name": "lyso_01", "pgroup": "p12345"}, + {"sample_id": 2, "sample_name": "lyso_02", "pgroup": "p12345"}, + {"sample_id": 3, "sample_name": "thaumatin_01", "pgroup": "p12345"}, + {"sample_id": 4, "sample_name": "insulin_01", "pgroup": "p67890"}, + {"sample_id": 5, "sample_name": "insulin_02", "pgroup": "p67890"}, + {"sample_id": 6, "sample_name": "proteinaseK_01", "pgroup": "p20001"}, + {"sample_id": 7, "sample_name": "proteinaseK_02", "pgroup": "p20001"}, + {"sample_id": 8, "sample_name": "trypsin_01", "pgroup": "p20002"} +] diff --git a/src/aare/daq/samples.py b/src/aare/daq/samples.py new file mode 100644 index 00000000..5df4220c --- /dev/null +++ b/src/aare/daq/samples.py @@ -0,0 +1,42 @@ +"""Stand-in sample catalogue used while the real sample source lives in BEC/aareDB. + +The data is a static JSON file shipped with the package; each entry maps an aareDB-style +sample id to the p-group that owns it. +""" + +from __future__ import annotations + +from importlib.resources import files +from pathlib import Path + +from pydantic import BaseModel, TypeAdapter + + +class DummySample(BaseModel): + sample_id: int + sample_name: str + pgroup: str + + +class MountResult(BaseModel): + mounted: bool + sample_id: int + sample_name: str + pgroup: str + + +_SAMPLE_LIST = TypeAdapter(list[DummySample]) + + +class DummySampleStore: + def __init__(self, path: Path | None = None) -> None: + if path is None: + path = Path(str(files("aare.daq") / "dummy_samples.json")) + samples = _SAMPLE_LIST.validate_json(path.read_text()) + self._by_id = {s.sample_id: s for s in samples} + + def find_sample(self, sample_id: int) -> DummySample | None: + return self._by_id.get(sample_id) + + def all_samples(self) -> list[DummySample]: + return list(self._by_id.values()) diff --git a/src/aare/daq/server.py b/src/aare/daq/server.py index 351b42b0..95aeecc1 100644 --- a/src/aare/daq/server.py +++ b/src/aare/daq/server.py @@ -7,7 +7,8 @@ from contextlib import asynccontextmanager import uvicorn from aarecommon.config.beamline import mx_beamline from aarecommon.config.logger import get_uvicorn_logging_config, setup_logger -from aarecommon.errors.codes import export_error_codes_grouped +from aarecommon.errors.codes import AuthErrorCode +from aarecommon.errors.exception_handler import SampleException, UserRightsException from fastapi import Depends, FastAPI, Request from fastapi.concurrency import run_in_threadpool from fastapi.security import OAuth2PasswordBearer @@ -15,6 +16,7 @@ from fastapi.security import OAuth2PasswordBearer from aare.daq import auth from aare.daq.aaredb import AareWrapper from aare.daq.auth import SampleAccess +from aare.daq.samples import DummySampleStore, MountResult from aare.daq.server_exception_handler import register_exception_handlers logger = setup_logger("aareDAQ") @@ -24,6 +26,7 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # ── Per-worker state: populated inside the lifespan, after fork ── aaredb: AareWrapper +samples: DummySampleStore @asynccontextmanager @@ -31,11 +34,12 @@ async def lifespan(application: FastAPI): """ Runs once per worker process, AFTER fork() and BEFORE serving requests. """ - global aaredb + global aaredb, samples logger.info(f"Worker {os.getpid()} setting up JWT authentication...") auth.init_jwt_key() aaredb = AareWrapper(mx_beamline()) + samples = DummySampleStore() logger.info(f"Worker {os.getpid()} initialised successfully.") yield # ── application serves requests here ── @@ -63,8 +67,8 @@ async def login(request: Request): A dictionary containing the access token and token type. """ username = auth.authenticate_from_proxy_header(request) - data = await run_in_threadpool(auth.authenticate_user, username) - return {"access_token": data, "token_type": "bearer"} + data, token = await run_in_threadpool(auth.authenticate_user, username) + return {"access_token": token, "token_type": "bearer", "info": data.model_dump()} @app.get("/about/installed_version") @@ -97,6 +101,39 @@ async def sample_access(sample_id: int, token: str = Depends(oauth2_scheme)) -> return auth.check_sample_access(data, sample_id, sample.pgroup if sample else None) +@app.post("/sample/mount/{sample_id}") +async def mount_sample(sample_id: int, token: str = Depends(oauth2_scheme)) -> MountResult: + """ + Mount a sample on behalf of the token's user. + + The sample is looked up in the dummy sample catalogue and the user must be allowed + to work on it (member of its p-group, or staff). Nothing moves yet; this only + exercises the authorization path. + + Args: + sample_id: Database identifier of the sample to mount. + token: OAuth2 access token of the user asking. + + Returns: + MountResult on success. + + Raises: + SampleException: the sample id is not in the catalogue (400). + UserRightsException: the user may not work on this sample (403). + """ + data = auth.parse_token(token) + sample = samples.find_sample(sample_id) + if sample is None: + raise SampleException(f"Unknown sample id {sample_id}.") + access = auth.check_sample_access(data, sample_id, sample.pgroup) + if not access.allowed: + raise UserRightsException(message=access.reason, code=AuthErrorCode.FORBIDDEN) + logger.info(f"{data.sub} mounted sample {sample_id} ({sample.sample_name}, {sample.pgroup})") + return MountResult( + mounted=True, sample_id=sample_id, sample_name=sample.sample_name, pgroup=sample.pgroup + ) + + def main(): uvicorn.run( "aare.daq.server:app", diff --git a/tests/conftest.py b/tests/conftest.py index 23b60f3f..61543b57 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -31,6 +31,13 @@ def mock_aaredb(): return db +@pytest.fixture +def mock_samples(): + store = MagicMock() + store.find_sample.return_value = None + return store + + @pytest.fixture def auth_token_data(): from aare.daq.auth import TokenData @@ -39,10 +46,11 @@ def auth_token_data(): @pytest.fixture -def client(server_module, mock_aaredb, auth_token_data): +def client(server_module, mock_aaredb, mock_samples, auth_token_data): with ( patch("aare.daq.auth.parse_token", return_value=auth_token_data), patch.object(server_module, "AareWrapper", return_value=mock_aaredb), + patch.object(server_module, "DummySampleStore", return_value=mock_samples), TestClient(server_module.app) as c, ): yield c diff --git a/tests/unit/daq/test_auth.py b/tests/unit/daq/test_auth.py index 8225dedc..d3f9d837 100644 --- a/tests/unit/daq/test_auth.py +++ b/tests/unit/daq/test_auth.py @@ -82,7 +82,7 @@ def test_authenticate_user_collects_pgroups(): patch("aare.daq.auth.os.getgrouplist", return_value=gids), patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid), ): - data = parse_token(authenticate_user("u")) + data = authenticate_user("u")[0] assert data.sub == "u" assert data.pgroups == ["p12345", "p67890"] assert data.staff is False @@ -95,7 +95,7 @@ def test_authenticate_user_staff_group(): patch("aare.daq.auth.os.getgrouplist", return_value=gids), patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid), ): - assert parse_token(authenticate_user("u")).staff is True + assert authenticate_user("u")[0].staff is True def test_authenticate_user_super_user(): @@ -105,7 +105,7 @@ def test_authenticate_user_super_user(): patch("aare.daq.auth.os.getgrouplist", return_value=gids), patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid), ): - assert parse_token(authenticate_user(auth.SUPER_USERS[0])).staff is True + assert authenticate_user(auth.SUPER_USERS[0])[0].staff is True def test_sessions_differ_between_tokens(): @@ -115,8 +115,8 @@ def test_sessions_differ_between_tokens(): patch("aare.daq.auth.os.getgrouplist", return_value=gids), patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid), ): - first = parse_token(authenticate_user("u")).session - second = parse_token(authenticate_user("u")).session + first = authenticate_user("u")[0].session + second = authenticate_user("u")[0].session assert first != second diff --git a/tests/unit/daq/test_samples.py b/tests/unit/daq/test_samples.py new file mode 100644 index 00000000..5023c71f --- /dev/null +++ b/tests/unit/daq/test_samples.py @@ -0,0 +1,28 @@ +import pytest + +from aare.daq.samples import DummySample, DummySampleStore + + +def test_shipped_catalogue_loads(): + store = DummySampleStore() + samples = store.all_samples() + assert samples, "shipped dummy_samples.json should not be empty" + assert all(isinstance(s, DummySample) for s in samples) + assert len({s.sample_id for s in samples}) == len(samples), "sample ids must be unique" + + +def test_find_sample(tmp_path): + path = tmp_path / "samples.json" + path.write_text('[{"sample_id": 7, "sample_name": "x", "pgroup": "p1"}]') + store = DummySampleStore(path) + found = store.find_sample(7) + assert found is not None + assert found.pgroup == "p1" + assert store.find_sample(8) is None + + +def test_invalid_catalogue_rejected(tmp_path): + path = tmp_path / "samples.json" + path.write_text('[{"sample_id": "seven", "sample_name": "x"}]') + with pytest.raises(ValueError): + DummySampleStore(path) diff --git a/tests/unit/daq/test_server.py b/tests/unit/daq/test_server.py index c18ba20a..6089eb9e 100644 --- a/tests/unit/daq/test_server.py +++ b/tests/unit/daq/test_server.py @@ -3,13 +3,7 @@ from unittest.mock import MagicMock, patch import pytest from aare.daq.auth import TokenData - - -def test_meta_error_codes(client): - response = client.get("/meta/error-codes") - assert response.status_code == 200 - data = response.json() - assert "AuthErrorCode" in data +from aare.daq.samples import DummySample def test_installed_version(client): @@ -18,10 +12,12 @@ def test_installed_version(client): assert isinstance(response.json(), str) -def test_login_success(client): +def test_login_success(client, auth_token_data): with ( patch("aare.daq.auth.authenticate_from_proxy_header", return_value="user"), - patch("aare.daq.auth.authenticate_user", return_value="fake-access-token"), + patch( + "aare.daq.auth.authenticate_user", return_value=(auth_token_data, "fake-access-token") + ), ): response = client.post( "/token", @@ -29,7 +25,11 @@ def test_login_success(client): headers={"X-Remote-User": "user"}, ) assert response.status_code == 200 - assert response.json() == {"access_token": "fake-access-token", "token_type": "bearer"} + assert response.json() == { + "access_token": "fake-access-token", + "token_type": "bearer", + "info": auth_token_data.model_dump(), + } def test_login_without_proxy_header_is_401(client): @@ -70,3 +70,80 @@ def test_sample_access_unknown_sample(client, mock_aaredb): body = response.json() assert body["allowed"] is False assert body["pgroup"] is None + + +# --------------------------------------------------------------------------- +# /sample/mount +# --------------------------------------------------------------------------- +AUTH = {"Authorization": "Bearer t"} + + +def _as_user(pgroups, staff=False): + return patch( + "aare.daq.auth.parse_token", + return_value=TokenData(sub="u", pgroups=pgroups, session=1, staff=staff), + ) + + +def test_mount_requires_token(client): + assert client.post("/sample/mount/1").status_code == 401 + + +def test_mount_own_pgroup_succeeds(client, mock_samples): + mock_samples.find_sample.return_value = DummySample( + sample_id=1, sample_name="lyso_01", pgroup="p12345" + ) + with _as_user(["p12345"]): + response = client.post("/sample/mount/1", headers=AUTH) + assert response.status_code == 200 + assert response.json() == { + "mounted": True, + "sample_id": 1, + "sample_name": "lyso_01", + "pgroup": "p12345", + } + mock_samples.find_sample.assert_called_once_with(1) + + +def test_mount_other_pgroup_is_403(client, mock_samples): + mock_samples.find_sample.return_value = DummySample( + sample_id=4, sample_name="insulin_01", pgroup="p67890" + ) + with _as_user(["p12345"]): + response = client.post("/sample/mount/4", headers=AUTH) + assert response.status_code == 403 + body = response.json() + assert body["code"] == "FORBIDDEN" + assert "p67890" in body["message"] + + +def test_mount_staff_any_pgroup(client, mock_samples): + mock_samples.find_sample.return_value = DummySample( + sample_id=4, sample_name="insulin_01", pgroup="p67890" + ) + with _as_user(["p11111"], staff=True): + response = client.post("/sample/mount/4", headers=AUTH) + assert response.status_code == 200 + assert response.json()["mounted"] is True + + +def test_mount_unknown_sample_is_400(client, mock_samples): + mock_samples.find_sample.return_value = None + with _as_user(["p12345"]): + response = client.post("/sample/mount/999", headers=AUTH) + assert response.status_code == 400 + assert response.json()["exception_class"] == "SampleException" + + +def test_mount_against_shipped_catalogue(server_module, mock_aaredb): + """End-to-end over the real dummy_samples.json: owner succeeds, outsider is refused.""" + from fastapi.testclient import TestClient + + with ( + patch.object(server_module, "AareWrapper", return_value=mock_aaredb), + TestClient(server_module.app) as c, + _as_user(["p12345"]), + ): + assert c.post("/sample/mount/1", headers=AUTH).status_code == 200 + assert c.post("/sample/mount/4", headers=AUTH).status_code == 403 + assert c.post("/sample/mount/999", headers=AUTH).status_code == 400