Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions src/murfey/instrument_server/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from functools import partial
from logging import getLogger
from pathlib import Path
from typing import Annotated, Dict, List, Optional, Union
from typing import Annotated, Any, Dict, List, Optional, Union

Check warning on line 10 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L10

Added line #L10 was not covered by tests
from urllib.parse import urlparse

import requests
Expand Down Expand Up @@ -328,19 +328,43 @@
safe_gain_path = sanitise(str(gain_reference.gain_path))
safe_visit_path = sanitise(gain_reference.visit_path)
safe_destination_dir = sanitise(gain_reference.gain_destination_dir)
machine_config = requests.get(

# Load machine config and other needed properties
machine_config: dict[str, Any] = requests.get(

Check warning on line 333 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L333

Added line #L333 was not covered by tests
f"{_get_murfey_url()}/instruments/{sanitise_nonpath(instrument_name)}/machine",
headers={"Authorization": f"Bearer {tokens[session_id]}"},
).json()

Check failure

Code scanning / CodeQL

Partial server-side request forgery Critical

Part of the URL of this request depends on a
user-provided value
.

# Validate that file passed is from the gain reference directory
gain_ref_dir = machine_config.get("gain_reference_directory", "")

Check warning on line 339 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L339

Added line #L339 was not covered by tests
if not safe_gain_path.startswith(gain_ref_dir):
raise ValueError(

Check warning on line 341 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L341

Added line #L341 was not covered by tests
"Gain reference file does not originate from the gain reference directory "
f"{gain_ref_dir!r}"
)

# Return the rsync URL if set, otherwise assume you are syncing via Murfey
rsync_url = urlparse(str(machine_config.get("rsync_url", _get_murfey_url())))
rsync_module = machine_config.get("rsync_module", "data")
rsync_path = f"{rsync_url.hostname}::{rsync_module}/{safe_visit_path}/{safe_destination_dir}/{secure_filename(gain_reference.gain_path.name)}"

Check warning on line 349 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L347-L349

Added lines #L347 - L349 were not covered by tests

# Run rsync subprocess to transfer gain reference
cmd = [
"rsync",
posix_path(Path(safe_gain_path)),
f"{urlparse(_get_murfey_url(), allow_fragments=False).hostname}::{machine_config.get('rsync_module', 'data')}/{safe_visit_path}/{safe_destination_dir}/{secure_filename(gain_reference.gain_path.name)}",
rsync_path,
]
gain_rsync = subprocess.run(cmd)
gain_rsync = subprocess.run(

Check warning on line 357 in src/murfey/instrument_server/api.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/instrument_server/api.py#L357

Added line #L357 was not covered by tests
cmd,
capture_output=True,
text=True,
)
if gain_rsync.returncode:
logger.warning(
f"Gain reference file {safe_gain_path} was not successfully transferred to {safe_visit_path}/processing"
f"Failed to transfer gain reference file {safe_gain_path!r} to {f'{safe_visit_path}/processing'!r} \n"
f"Executed the following command: {' '.join(cmd)!r} \n"
f"Returned the following error: \n"
f"{gain_rsync.stderr}"
)
return {"success": False}
return {"success": True}
Expand Down
8 changes: 7 additions & 1 deletion src/murfey/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2291,6 +2291,10 @@
_transport_object.transport.ack(header)
return None
elif message["register"] == "data_collection":
logger.debug(

Check warning on line 2294 in src/murfey/server/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/server/__init__.py#L2294

Added line #L2294 was not covered by tests
f"Received message named 'data_collection' containing the following items:\n"
f"{', '.join([f'{sanitise(key)}: {sanitise(value)}' for key, value in message.items()])}"
)
murfey_session_id = message["session_id"]
ispyb_session_id = murfey.server.ispyb.get_session_id(
microscope=message["microscope"],
Expand All @@ -2309,7 +2313,9 @@
# flush_data_collections(message["source"], murfey_db)
else:
logger.warning(
f"No data collection group ID was found for image directory {sanitise(message['image_directory'])} and source {sanitise(message['source'])}"
"No data collection group ID was found for image directory "
f"{sanitise(message['image_directory'])} and source "
f"{sanitise(message['source'])}"
)
if _transport_object:
_transport_object.transport.nack(header, requeue=True)
Expand Down
16 changes: 14 additions & 2 deletions src/murfey/server/ispyb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import datetime
import logging
from typing import Callable, List, Literal, Optional
from typing import Callable, Generator, List, Literal, Optional

import ispyb

Expand Down Expand Up @@ -30,6 +30,7 @@
url,
)

from murfey.util import sanitise
from murfey.util.config import get_security_config
from murfey.util.models import FoilHoleParameters, GridSquareParameters, Sample, Visit

Expand Down Expand Up @@ -535,7 +536,7 @@
return reference


def _get_session() -> sqlalchemy.orm.Session:
def _get_session() -> Generator[Optional[sqlalchemy.orm.Session], None, None]:
db = Session()
if db is None:
yield None
Expand All @@ -557,6 +558,17 @@
visit_number: str,
db: sqlalchemy.orm.Session | None,
) -> int | None:

# Log received lookup parameters
log.debug(

Check warning on line 563 in src/murfey/server/ispyb.py

View check run for this annotation

Codecov / codecov/patch

src/murfey/server/ispyb.py#L563

Added line #L563 was not covered by tests
"Looking up ISPyB BLSession ID using the following values:\n"
f"microscope: {sanitise(microscope)}\n"
f"proposal_code: {sanitise(proposal_code)}\n"
f"proposal_number: {sanitise(proposal_number)}\n"
f"visit_number: {sanitise(visit_number)}\n"
)

# Lookup BLSession ID
if db is None:
return None
query = (
Expand Down