diff --git a/README.md b/README.md index 755884b..9730821 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,24 @@ When constructing a manager directly, pass `redis_port` for a non-default listener port or `redis_tls=False` for a local plaintext Redis server. The standalone worker likewise defaults to TLS; use `--redis-tls=false` for plaintext. +## Credentials supplied by an application + +An application can supply credentials directly without a dotenv file: + +```python +manager = SlurmManager.for_cluster(Cluster.RA, username=username, token=token) +# When the application receives a refreshed token: +manager.set_credentials(username=username, token=refreshed_token) +``` + +Import `SlurmManager` and `Cluster` as in the example below. Explicit credentials +are kept in memory and take precedence over dotenv and environment credentials. +Updates apply to subsequent REST requests, including background monitoring and +cancellation, without replacing active jobs or event subscriptions. A request +already in progress retains its original credentials. Pass `username=None` when +no user-name header is needed. The application is responsible for acquiring and +refreshing tokens; keep them out of logs and job payloads. + ## Simple job Run the included ten-second Bash script using the cluster's default resources: diff --git a/slurm_manager/slurm_manager.py b/slurm_manager/slurm_manager.py index 1251961..277b320 100644 --- a/slurm_manager/slurm_manager.py +++ b/slurm_manager/slurm_manager.py @@ -62,6 +62,8 @@ class SlurmManager(Generic[_JobOptionsT]): redis_tls: bool = True, env_file: str | Path = ".env", rest_client: SlurmRestClient | None = None, + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", job_options_type: None = None, ) -> None: ... @@ -75,6 +77,8 @@ class SlurmManager(Generic[_JobOptionsT]): redis_tls: bool = True, env_file: str | Path = ".env", rest_client: SlurmRestClient | None = None, + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", job_options_type: type[_JobOptionsT], ) -> None: ... @@ -87,6 +91,8 @@ class SlurmManager(Generic[_JobOptionsT]): redis_tls: bool = True, env_file: str | Path = ".env", rest_client: SlurmRestClient | None = None, + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", job_options_type: type[_JobOptionsT] | None = None, ) -> None: @@ -101,6 +107,8 @@ class SlurmManager(Generic[_JobOptionsT]): take precedence. rest_client (SlurmRestClient | None): Optional preconfigured REST client; None creates one from env_file. + username (str | None): Explicit Slurm user; None omits the user header. + token (str | None): Explicit JWT; None uses the REST client credentials. worker_path (str): Absolute path to the Go executable on compute nodes. job_options_type: Model used to validate submissions for this manager. @@ -113,7 +121,14 @@ class SlurmManager(Generic[_JobOptionsT]): self._redis_tls = redis_tls self.worker_path = worker_path self._redis_address = f"{redis_host}:{redis_port}" - self.rest_client = rest_client if rest_client is not None else SlurmRestClient(env_file) + if rest_client is None: + self.rest_client = SlurmRestClient(env_file, username=username, token=token) + else: + self.rest_client = rest_client + if token is not None: + self.set_credentials(username=username, token=token) + elif username is not None: + raise ValueError("An explicit username requires an explicit token") redis_options = {} if redis_tls: redis_options = {"ssl": True, "ssl_cert_reqs": "required", "ssl_check_hostname": True} @@ -133,14 +148,20 @@ class SlurmManager(Generic[_JobOptionsT]): def for_cluster( cluster: Literal["ra", Cluster.RA], *, - env_file: str | Path, + env_file: str | Path = ".env", + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", ) -> SlurmManager[ra.RAJobOptions]: ... @overload @staticmethod def for_cluster( - *, env_file: str | Path, worker_path: str = "/usr/bin/bec-slurm-worker" + *, + env_file: str | Path = ".env", + username: str | None = None, + token: str | None = None, + worker_path: str = "/usr/bin/bec-slurm-worker", ) -> SlurmManager[ra.RAJobOptions]: ... @overload @@ -148,7 +169,9 @@ class SlurmManager(Generic[_JobOptionsT]): def for_cluster( cluster: Literal["sfonline", "SFOnline", Cluster.SFONLINE], *, - env_file: str | Path, + env_file: str | Path = ".env", + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", ) -> SlurmManager[sfonline.SFOnlineJobOptions]: ... @@ -157,7 +180,9 @@ class SlurmManager(Generic[_JobOptionsT]): def for_cluster( cluster: Literal["slsonline", "SLSOnline", Cluster.SLSONLINE], *, - env_file: str | Path, + env_file: str | Path = ".env", + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", ) -> SlurmManager[slsonline.SLSOnlineJobOptions]: ... @@ -165,10 +190,23 @@ class SlurmManager(Generic[_JobOptionsT]): def for_cluster( cluster: str = Cluster.RA, *, - env_file: str | Path, + env_file: str | Path = ".env", + username: str | None = None, + token: str | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", ) -> SlurmManager[Any]: - """Create a manager bound to a built-in cluster using a local credential file.""" + """Create a cluster manager using explicit or local dotenv credentials. + + Args: + cluster (str): Built-in cluster name; defaults to RA. + env_file (str | Path): Local credential file when token is not supplied. + username (str | None): Explicit Slurm user; None omits the user header. + token (str | None): Explicit JWT; None uses local dotenv credentials. + worker_path (str): Absolute compute-node worker executable path. + + Returns: + SlurmManager[Any]: Manager configured for the selected cluster. + """ options_type: type[JobOptions] match cluster: case Cluster.RA: @@ -185,7 +223,12 @@ class SlurmManager(Generic[_JobOptionsT]): f"Unknown Slurm cluster {cluster!r}; supported clusters: ra, sfonline, slsonline" ) rest_client = SlurmRestClient( - env_file, rest_url=info.url, api_version=info.api_version, use_environment=False + env_file, + rest_url=info.url, + api_version=info.api_version, + use_environment=False, + username=username, + token=token, ) return SlurmManager( info.redis_host, @@ -196,6 +239,18 @@ class SlurmManager(Generic[_JobOptionsT]): job_options_type=options_type, ) + def set_credentials(self, *, username: str | None, token: str) -> None: + """Update REST credentials without replacing jobs or subscriptions. + + Args: + username (str | None): Slurm user name; None omits the user header. + token (str): Nonempty Slurm JWT overriding dotenv/environment credentials. + + Raises: + ValueError: Credentials are empty or contain invalid header characters. + """ + self.rest_client.set_credentials(username=username, token=token) + ################################################ # Public Job Management # ################################################ diff --git a/slurm_manager/slurm_rest_client.py b/slurm_manager/slurm_rest_client.py index d0dba73..586dc2c 100644 --- a/slurm_manager/slurm_rest_client.py +++ b/slurm_manager/slurm_rest_client.py @@ -5,6 +5,7 @@ from __future__ import annotations import json import os import re +import threading from http import HTTPStatus from http.client import HTTPException from pathlib import Path @@ -62,9 +63,10 @@ class SlurmRestClient: Environment variables override the file. The file is read again for every request so replacing an expired token does not require restarting a manager. + Explicit credentials take precedence over the file and environment. """ - def __init__( + def __init__( # noqa: PLR0913 - REST connection and authentication configuration self, env_file: str | Path = ".env", timeout: float = 30, @@ -72,6 +74,8 @@ class SlurmRestClient: rest_url: str | None = None, api_version: str | None = None, use_environment: bool = True, + username: str | None = None, + token: str | None = None, ) -> None: """Load and validate slurmrestd connection settings. @@ -82,10 +86,18 @@ class SlurmRestClient: rest_url: Explicit endpoint, overriding connection settings from dotenv or environment. api_version: Explicit REST version. use_environment: Allow process-wide environment overrides for dotenv values. + username (str | None): Explicit Slurm user; None omits the user header. + token (str | None): Explicit JWT; None uses dotenv/environment credentials. Raises: ValueError: The URL, API version, token, or timeout is invalid. """ + self._credentials_lock = threading.Lock() + self._credentials: tuple[str | None, str] | None = None + if token is not None: + self.set_credentials(username=username, token=token) + elif username is not None: + raise ValueError("An explicit username requires an explicit token") self.env_file = Path(env_file).resolve() if timeout <= 0: raise ValueError("REST timeout must be positive") @@ -105,9 +117,29 @@ class SlurmRestClient: ) if not re.fullmatch(r"v\d+\.\d+\.\d+", self.api_version): raise ValueError("SLURM_REST_API_VERSION must look like v0.0.44") - self._headers(settings) + self._authentication_headers() self._opener = build_opener(_NoRedirect()) + def set_credentials(self, *, username: str | None, token: str) -> None: + """Atomically replace credentials used by subsequent REST requests. + + Args: + username (str | None): Slurm user name; None omits the user header. + token (str): Nonempty Slurm JWT, overriding dotenv/environment credentials. + + Raises: + ValueError: Credentials are empty or contain invalid header characters. + + Notes: + Requests already in progress retain their original credential snapshot. + Updating credentials does not interrupt jobs or event subscriptions. + """ + if username is not None and not isinstance(username, str): + raise ValueError("Username must be a string or None") + self._headers({"SLURM_JWT": token, "SLURM_USER": username or ""}) + with self._credentials_lock: + self._credentials = (username, token) + ################################################ # Public Job Operations # ################################################ @@ -210,7 +242,7 @@ class SlurmRestClient: Requests are not automatically retried. Authentication headers and response bodies are not included in raised transport errors. """ - headers = self._headers(self._settings()) + headers = self._authentication_headers() data = None if payload is None else json.dumps(payload).encode() if data is not None: headers["Content-Type"] = "application/json" @@ -256,6 +288,15 @@ class SlurmRestClient: # Internal Authentication # ################################################ + def _authentication_headers(self) -> dict[str, str]: + """Build headers from one consistent credential snapshot.""" + with self._credentials_lock: + credentials = self._credentials + if credentials is not None: + username, token = credentials + return self._headers({"SLURM_JWT": token, "SLURM_USER": username or ""}) + return self._headers(self._settings()) + def _settings(self) -> dict[str, str]: """Read local dotenv values and apply environment-variable overrides. @@ -285,8 +326,11 @@ class SlurmRestClient: ValueError: The token is empty. """ token = settings.get("SLURM_JWT", "") - if not token: + if not isinstance(token, str) or not token.strip(): raise ValueError("Set SLURM_JWT in the credential file or enabled environment") + for value in (token, settings.get("SLURM_USER", "")): + if not isinstance(value, str) or not re.fullmatch(r"[\x20-\x7e]*", value): + raise ValueError("Credentials contain invalid HTTP header characters") headers = {"X-SLURM-USER-TOKEN": token, "Accept": "application/json"} if settings.get("SLURM_USER"): headers["X-SLURM-USER-NAME"] = settings["SLURM_USER"] diff --git a/test/test_slurm_manager.py b/test/test_slurm_manager.py index 04581d1..d346c08 100644 --- a/test/test_slurm_manager.py +++ b/test/test_slurm_manager.py @@ -859,3 +859,66 @@ def test_online_job_options_accept_allowed_partitions(options_type, partition): ) def test_online_job_options_send_cluster_default_partition(options_type, default_partition): assert options_type().to_rest()["partition"] == default_partition + + +def test_set_credentials_preserves_active_job_and_subscriptions(manager): + future = submit(manager) + topics = manager.sub_client.registered_topics + manager.set_credentials(username="beamline", token="replacement-token") + manager.rest_client.set_credentials.assert_called_once_with( + username="beamline", token="replacement-token" + ) + assert manager._job_tracker.get_future(future._job_id) is future + assert manager.sub_client.registered_topics == topics + manager.sub_client._redis.publish( + TopicInfo(future._job_id).event, '{"msg_type":"status","status":"finished"}' + ) + future.wait(timeout=1) + assert future.success() + + +def test_explicit_credentials_reach_injected_rest_client(): + rest = mock.Mock(spec=SlurmRestClient) + with mock.patch("slurm_manager.slurm_manager.RedisSubClient"): + manager = SlurmManager(rest_client=rest, username="beamline", token="initial-token") + try: + rest.set_credentials.assert_called_once_with(username="beamline", token="initial-token") + finally: + manager.shutdown(timeout=3) + + +def test_constructor_forwards_explicit_credentials(tmp_path, monkeypatch): + monkeypatch.setenv("SLURM_REST_URL", "https://slurm.example") + monkeypatch.delenv("SLURM_JWT", raising=False) + with mock.patch("slurm_manager.slurm_manager.RedisSubClient"): + manager = SlurmManager( + env_file=tmp_path / "missing.env", username="beamline", token="initial-token" + ) + try: + assert ( + manager.rest_client._authentication_headers()["X-SLURM-USER-TOKEN"] == "initial-token" + ) + assert manager.rest_client._authentication_headers()["X-SLURM-USER-NAME"] == "beamline" + finally: + manager.shutdown(timeout=3) + + +@pytest.mark.parametrize("cluster", ["ra", "sfonline", "slsonline"]) +def test_cluster_factory_accepts_credentials_without_dotenv(monkeypatch, tmp_path, cluster): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("SLURM_JWT", "other-token") + monkeypatch.setenv("SLURM_USER", "other-user") + with mock.patch("slurm_manager.slurm_manager.RedisSubClient"): + manager = SlurmManager.for_cluster(cluster, username="beamline", token="initial-token") + try: + assert ( + manager.rest_client._authentication_headers()["X-SLURM-USER-TOKEN"] == "initial-token" + ) + assert manager.rest_client._authentication_headers()["X-SLURM-USER-NAME"] == "beamline" + manager.set_credentials(username="beamline", token="replacement-token") + assert ( + manager.rest_client._authentication_headers()["X-SLURM-USER-TOKEN"] + == "replacement-token" + ) + finally: + manager.shutdown(timeout=3) diff --git a/test/test_slurm_rest_client.py b/test/test_slurm_rest_client.py index a29ed1b..bd82463 100644 --- a/test/test_slurm_rest_client.py +++ b/test/test_slurm_rest_client.py @@ -234,3 +234,86 @@ def test_truncated_responses_raise_a_transport_error(endpoint, error_response): patch = mock.patch.object(client._opener, "open", return_value=opened) with patch, pytest.raises(SlurmRestError): client.get_job("123") + + +def test_explicit_credentials_initialize_without_a_file(endpoint, tmp_path, monkeypatch): + env_file, calls, replies = endpoint + url = env_file.read_text().splitlines()[0].split("=", 1)[1] + monkeypatch.setenv("SLURM_JWT", "environment-token") + monkeypatch.setenv("SLURM_USER", "environment-user") + client = SlurmRestClient( + tmp_path / "missing.env", rest_url=url, username="beamline", token="initial-token" + ) + replies.extend([(200, {}), (200, {}), (200, {})]) + client.cancel("1") + client.set_credentials(username="replacement-user", token="replacement-token") + client.cancel("2") + client.set_credentials(username=None, token="without-user") + client.cancel("3") + assert [call[2]["X-Slurm-User-Token"] for call in calls] == [ + "initial-token", + "replacement-token", + "without-user", + ] + assert calls[0][2]["X-Slurm-User-Name"] == "beamline" + assert calls[1][2]["X-Slurm-User-Name"] == "replacement-user" + assert "X-Slurm-User-Name" not in calls[2][2] + + +def test_set_credentials_overrides_dotenv_and_environment(endpoint, monkeypatch): + env_file, calls, replies = endpoint + client = SlurmRestClient(env_file) + client.set_credentials(username="beamline", token="explicit-token") + monkeypatch.setenv("SLURM_JWT", "environment-token") + env_file.write_text(env_file.read_text().replace("test-secret", "file-token")) + replies.append((200, {})) + client.cancel("1") + assert calls[0][2]["X-Slurm-User-Token"] == "explicit-token" + assert calls[0][2]["X-Slurm-User-Name"] == "beamline" + + +@pytest.mark.parametrize( + ("username", "token"), + [("beamline", ""), ("beamline", " "), ("beamline", "bad\r\ntoken"), ("bad\nuser", "token")], +) +def test_invalid_rotation_preserves_previous_credentials(endpoint, username, token): + env_file, calls, replies = endpoint + client = SlurmRestClient(env_file, username="valid-user", token="valid-token") + with pytest.raises(ValueError): + client.set_credentials(username=username, token=token) + replies.append((200, {})) + client.cancel("1") + assert calls[0][2]["X-Slurm-User-Name"] == "valid-user" + assert calls[0][2]["X-Slurm-User-Token"] == "valid-token" + + +def test_rotation_during_request_keeps_consistent_snapshot(endpoint, monkeypatch): + from concurrent.futures import ThreadPoolExecutor + + env_file, calls, replies = endpoint + client = SlurmRestClient(env_file, username="old-user", token="old-token") + snapshot_taken = threading.Event() + continue_request = threading.Event() + original_headers = client._headers + + def headers(settings): + if threading.current_thread() is not threading.main_thread(): + snapshot_taken.set() + assert continue_request.wait(timeout=2) + return original_headers(settings) + + monkeypatch.setattr(client, "_headers", headers) + replies.extend([(200, {}), (200, {})]) + with ThreadPoolExecutor(max_workers=1) as pool: + request = pool.submit(client.cancel, "1") + try: + assert snapshot_taken.wait(timeout=2) + client.set_credentials(username="new-user", token="new-token") + finally: + continue_request.set() + request.result(timeout=2) + client.cancel("2") + assert [(call[2]["X-Slurm-User-Name"], call[2]["X-Slurm-User-Token"]) for call in calls] == [ + ("old-user", "old-token"), + ("new-user", "new-token"), + ]