diff --git a/docs/user/reference/api.md b/docs/user/reference/api.md index 824c73e..c04f65a 100644 --- a/docs/user/reference/api.md +++ b/docs/user/reference/api.md @@ -19,6 +19,14 @@ Anything else, including every name starting with `_`, is internal. ::: intercede.registry +## Credentials + +::: intercede.auth.models + +::: intercede.auth.protocols + +::: intercede.auth.providers + ## Exceptions ::: intercede.exceptions diff --git a/src/intercede/_backends/_htcondor/__init__.py b/src/intercede/_backends/_htcondor/__init__.py new file mode 100644 index 0000000..743a1fd --- /dev/null +++ b/src/intercede/_backends/_htcondor/__init__.py @@ -0,0 +1,11 @@ +"""What interCEde knows about HTCondor, shared by every backend that drives it. + +Plain functions and data only, with no dependency on any backend class: the +HTCondor-CE backend uses them directly, and the HTCondor scheduler of the +composed backend (issue #21) will use the same ones over its transport. They +share these functions, never a subtype. + +- ``submit``: a submit description built from a ``SubmissionSpec`` +- ``commands``: the argv of each HTCondor tool, and parsers for their output +- ``status``: the state mapping from job ads to ``JobStatus`` +""" diff --git a/src/intercede/_backends/_htcondor/commands.py b/src/intercede/_backends/_htcondor/commands.py new file mode 100644 index 0000000..8c76276 --- /dev/null +++ b/src/intercede/_backends/_htcondor/commands.py @@ -0,0 +1,117 @@ +"""The argv of each HTCondor tool, and parsers for what they print. + +``remote`` is how a tool reaches its schedd: ``schedd_options(pool, name)`` +for a remote schedd, as an HTCondor-CE is reached, or ``()`` for the schedd +of the host the tool runs on, as the composed backend reaches it. +""" + +from __future__ import annotations + +import re +from collections.abc import Sequence + +from intercede.models import JobID + +# Ids per command line, so a status poll of thousands of jobs stays bounded. +CHUNK = 100 + + +def schedd_options(pool: str, name: str) -> list[str]: + """Reach the schedd ``name`` through the collector ``pool`` (host:port).""" + return ["-pool", pool, "-name", name] + + +def submit( + description: str, pool: str | None = None, name: str | None = None +) -> list[str]: + """Submit a description file and spool its inputs to the schedd. + + Spooling copies the inputs at submit time, so nothing on the submitting + host is needed afterwards. With ``pool`` and ``name`` the schedd is a + remote one (``-remote`` implies spooling); without, it is the local one. + """ + if (pool is None) != (name is None): + raise ValueError("a remote schedd needs both pool and name") + + command = ["condor_submit", "-terse"] + + if pool is None or name is None: + command.append("-spool") + else: + command.extend(["-pool", pool, "-remote", name]) + + command.append(description) + return command + + +def query( + ids: Sequence[JobID], attributes: Sequence[str], remote: Sequence[str] +) -> list[str]: + """Read the ads of jobs still in the queue.""" + return ["condor_q", *remote, *ids, "-attributes", ",".join(attributes), "-json"] + + +def history( + ids: Sequence[JobID], attributes: Sequence[str], remote: Sequence[str] +) -> list[str]: + """Read the ads of jobs that have left the queue.""" + return [ + "condor_history", + *remote, + *ids, + "-attributes", + ",".join(attributes), + "-json", + ] + + +def remove(ids: Sequence[JobID], remote: Sequence[str]) -> list[str]: + """Remove jobs: cancels active ones, releases finished ones.""" + return ["condor_rm", *remote, *ids] + + +def transfer_data(ids: Sequence[JobID], remote: Sequence[str]) -> list[str]: + """Fetch the spooled output of jobs into the directory they were submitted from.""" + return ["condor_transfer_data", *remote, *ids] + + +def chunks(ids: Sequence[JobID]) -> list[Sequence[JobID]]: + """Split ids into groups of at most ``CHUNK``.""" + return [ids[start : start + CHUNK] for start in range(0, len(ids), CHUNK)] + + +_TERSE = re.compile( + r"\s*(?P\d+)\.(?P\d+)" + r"\s*-\s*" + r"(?P\d+)\.(?P\d+)\s*" +) + + +def parse_submit(raw: str) -> list[JobID]: + """Parse job IDs from condor_submit -terse output, e.g. '12.0 - 12.3'.""" + lines = [line for line in raw.splitlines() if line.strip()] + + if len(lines) != 1: + raise ValueError(f"unexpected condor_submit output: {raw.strip()!r}") + + match = _TERSE.fullmatch(lines[0]) + if match is None: + raise ValueError(f"unexpected condor_submit output: {raw.strip()!r}") + + cluster = int(match["cluster"]) + first = int(match["first"]) + last_cluster = int(match["last_cluster"]) + last = int(match["last"]) + + if cluster != last_cluster or last < first: + raise ValueError(f"unexpected condor_submit output: {raw.strip()!r}") + + return [JobID(f"{cluster}.{proc}") for proc in range(first, last + 1)] + + +_REMOVED = re.compile(r"^Job (\d+\.\d+) marked for removal", re.MULTILINE) + + +def parse_remove(raw: str) -> set[JobID]: + """Return the ids ``condor_rm`` reports as removed; any other id was not.""" + return {JobID(job) for job in _REMOVED.findall(raw)} diff --git a/src/intercede/_backends/_htcondor/status.py b/src/intercede/_backends/_htcondor/status.py new file mode 100644 index 0000000..40d8aca --- /dev/null +++ b/src/intercede/_backends/_htcondor/status.py @@ -0,0 +1,124 @@ +"""From HTCondor job ads to ``JobStatus``. + +Reading only: the state is taken from what HTCondor records about a job, never +from a policy interCEde sets on it. A finished job reads as FAILED when its +payload exited non-zero or was killed by a signal, from ``ExitCode`` and +``ExitBySignal``. + +Ported from DIRAC's ``BatchSystems/Condor.py`` (``STATES_MAP`` and +``getCondorStatus``), with differences: DIRAC puts a payload that fails on +hold to recognise it, where the exit code is read here instead; the states +DIRAC leaves unmapped (6, 7) are mapped; and a removed job reports what it did +before it was removed, so a purged job keeps its result. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from typing import Any + +from intercede.models import JobID, JobStatus + +# The ad attributes every status query asks for. +STATE_ATTRIBUTES: Sequence[str] = ( + "ClusterId", + "ProcId", + "JobStatus", + "LastJobStatus", + "ExitCode", + "ExitBySignal", + "HoldReasonCode", + "HoldReason", +) + +# HTCondor's JobStatus codes. +_IDLE, _RUNNING, _REMOVED, _COMPLETED, _HELD, _TRANSFERRING, _SUSPENDED = range(1, 8) + +_STATES: Mapping[int, JobStatus] = { + _IDLE: JobStatus.WAITING, + _RUNNING: JobStatus.RUNNING, + _TRANSFERRING: JobStatus.RUNNING, # transferring output after running + _SUSPENDED: JobStatus.WAITING, +} + +_HOLD_SPOOLING = 16 # HoldReasonCode: input files are still being spooled + + +def job_id(ad: Mapping[str, Any]) -> JobID: + """Return the ``cluster.proc`` id of a job ad.""" + return JobID(f"{ad['ClusterId']}.{ad['ProcId']}") + + +def job_status(ad: Mapping[str, Any]) -> JobStatus: + """Map one job ad to the common status.""" + code = ad.get("JobStatus") + if code == _COMPLETED: + return _result(ad) + if code == _REMOVED: + # purge() removes finished jobs to release them, after which the + # history only says "removed": the state it left tells the result. + return ( + _result(ad) if ad.get("LastJobStatus") == _COMPLETED else JobStatus.ABORTED + ) + if code == _HELD: + # Held by the site or by HTCondor, not by interCEde: the job is stuck, + # except while its inputs are still being spooled. + return ( + JobStatus.WAITING + if ad.get("HoldReasonCode") == _HOLD_SPOOLING + else JobStatus.ABORTED + ) + return ( + _STATES.get(code, JobStatus.UNKNOWN) + if isinstance(code, int) + else JobStatus.UNKNOWN + ) + + +def is_removed(ad: Mapping[str, Any]) -> bool: + """Tell whether a job was removed, even while it is still in the queue. + + ``condor_rm`` only marks a job for removal: the schedd drops it from the + queue a moment later. In between it is already released. + + Args: + ad: A job ad with ``JobStatus``. + + Returns: + True when the job has been removed. + + """ + return ad.get("JobStatus") == _REMOVED + + +def _result(ad: Mapping[str, Any]) -> JobStatus: + """Tell DONE from FAILED for a job whose payload has finished.""" + if ad.get("ExitBySignal") is True: + return JobStatus.FAILED + exit_code = ad.get("ExitCode") + return ( + JobStatus.FAILED + if isinstance(exit_code, int) and exit_code != 0 + else JobStatus.DONE + ) + + +def hold_reason(ad: Mapping[str, Any]) -> str | None: + """Return why a held job is held, if it is.""" + reason = ad.get("HoldReason") + return reason if ad.get("JobStatus") == _HELD and isinstance(reason, str) else None + + +def parse_ads(raw: str) -> list[dict[str, Any]]: + """Parse ``condor_q -json`` or ``condor_history -json`` output. + + ``condor_q`` prints nothing at all when no job matches, and + ``condor_history`` prints an empty list. + """ + if not raw.strip(): + return [] + ads = json.loads(raw) + if not isinstance(ads, list) or not all(isinstance(ad, dict) for ad in ads): + raise ValueError("expected a JSON list of job ads") + return ads diff --git a/src/intercede/_backends/_htcondor/submit.py b/src/intercede/_backends/_htcondor/submit.py new file mode 100644 index 0000000..0fa5a0f --- /dev/null +++ b/src/intercede/_backends/_htcondor/submit.py @@ -0,0 +1,219 @@ +"""Submit descriptions: a ``SubmissionSpec`` written in HTCondor's submit language. + +One description submits every copy of a spec as one cluster, one process per +copy. What differs between copies (environment, secrets, working directory) is +expanded per process through macros indexed by ``$(ProcId)``, so the copies +stay one bulk submission. + +A description only says what to run and where its files go. It sets no +policy on the job's lifetime: no holds, no automatic removal, no retries. +Those are the consumer's decisions. The one exception is that a finished job +stays in the queue until it is purged, so its output can be collected again. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field + + +def quote_arguments(arguments: Sequence[str]) -> str: + """Quote command arguments using HTCondor's new syntax.""" + quoted_arguments = [_quote_item(argument) for argument in arguments] + + joined_arguments = " ".join(quoted_arguments) + return f'"{joined_arguments}"' + + +def quote_environment(environment: Mapping[str, str]) -> str: + """Quote environment variables using HTCondor's new syntax.""" + for name in environment: + _validate_environment_name(name) + + quoted_variables = [ + f"{name}={_quote_item(value)}" for name, value in sorted(environment.items()) + ] + + joined_variables = " ".join(quoted_variables) + return f'"{joined_variables}"' + + +def _validate_environment_name(name: str) -> None: + """Raise ValueError if the environment variable name is invalid.""" + is_valid = bool(name) and "=" not in name and name.replace("_", "").isalnum() + + if not is_valid: + raise ValueError(f"{name!r} is not a valid environment variable name") + + +def _quote_item(value: str) -> str: + """Escape and quote a single argument or environment variable value.""" + _refuse_newlines(value) + + escaped_value = value.replace('"', '""') + escaped_value = escaped_value.replace("'", "''") + escaped_value = _escape_macros(escaped_value) + + return f"'{escaped_value}'" + + +def _escape_macros(value: str) -> str: + # "$(...)" is macro syntax in a submit description; $(DOLLAR) is a literal "$". + return value.replace("$", "$(DOLLAR)") + + +def _refuse_newlines(value: str) -> None: + if "\n" in value or "\r" in value: + raise ValueError("a submit description value cannot contain a line break") + + +@dataclass(frozen=True) +class CopyPlan: + """What one process of the cluster gets on its own.""" + + initialdir: str # absolute; outputs come back here (SUBMIT_Iwd) + environment: Mapping[str, str] = field(default_factory=dict) + # Inputs of this copy only, relative to ``initialdir`` (e.g. "secrets/"). + inputs: Sequence[str] = () + + +@dataclass(frozen=True) +class SubmitPlan: + """Everything a submit description says, resolved to HTCondor's terms.""" + + executable: str + transfer_executable: bool + arguments: Sequence[str] + copies: Sequence[CopyPlan] + inputs: Sequence[str] = () # shared by every copy: absolute paths or URLs + stdout: str = "$(ClusterId).$(ProcId).out" + stderr: str = "$(ClusterId).$(ProcId).err" + log: str = "$(ClusterId).$(ProcId).log" + # None: every file the payload creates comes back; empty: none at all. + outputs: Sequence[str] | None = () + output_remaps: Mapping[str, str] = field(default_factory=dict) # name -> URL + cpus: int = 1 + memory_mb: int | None = None + wall_time_s: int | None = None + queue: str | None = None + + +def render(plan: SubmitPlan) -> str: + """Write ``plan`` as a submit description that queues one process per copy.""" + _validate_plan(plan) + + lines = _render_basics(plan) + lines.extend(_render_copies(plan)) + lines.extend(_render_file_transfer(plan)) + lines.extend(_render_resources(plan)) + lines.extend(_render_queue(plan)) + + return "\n".join(lines) + "\n" + + +def _join(items: Sequence[str]) -> str: + for item in items: + _refuse_newlines(item) + if "," in item: + raise ValueError(f"{item!r}: HTCondor file lists cannot hold a comma") + return ", ".join(_escape_macros(item) for item in items) + + +def _bool(value: bool) -> str: + return "true" if value else "false" + + +def _classad_string(value: str) -> str: + _refuse_newlines(value) + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + return '"' + _escape_macros(escaped) + '"' + + +def _validate_plan(plan: SubmitPlan) -> None: + if not plan.copies: + raise ValueError("A submit description needs at least one copy") + + +def _render_basics(plan: SubmitPlan) -> list[str]: + lines = [ + "universe = vanilla", + f"executable = {_escape_macros(plan.executable)}", + f"transfer_executable = {_bool(plan.transfer_executable)}", + ] + + if plan.arguments: + lines.append(f"arguments = {quote_arguments(plan.arguments)}") + + return lines + + +def _render_copies(plan: SubmitPlan) -> list[str]: + lines = [] + + for index, copy in enumerate(plan.copies): + _refuse_newlines(copy.initialdir) + lines.extend( + [ + f"ic_dir_{index} = {_escape_macros(copy.initialdir)}", + f"ic_env_{index} = {quote_environment(copy.environment)}", + f"ic_in_{index} = {_join(copy.inputs)}", + ] + ) + + lines.extend( + ["initialdir = $(ic_dir_$(ProcId))", "environment = $(ic_env_$(ProcId))"] + ) + + return lines + + +def _render_file_transfer(plan: SubmitPlan) -> list[str]: + shared_inputs = _join(plan.inputs) + copy_inputs = "$(ic_in_$(ProcId))" + inputs = f"{shared_inputs}, {copy_inputs}" if shared_inputs else copy_inputs + + lines = [ + "should_transfer_files = YES", + "when_to_transfer_output = ON_EXIT_OR_EVICT", + f"transfer_input_files = {inputs}", + f"output = {plan.stdout}", + f"error = {plan.stderr}", + f"log = {plan.log}", + ] + + if plan.outputs is not None: + output_files = _join(plan.outputs) or '""' + lines.append(f"transfer_output_files = {output_files}") + + if plan.output_remaps: + remaps = "; ".join( + f"{name} = {url}" for name, url in sorted(plan.output_remaps.items()) + ) + lines.append(f'transfer_output_remaps = "{_escape_macros(remaps)}"') + + return lines + + +def _render_resources(plan: SubmitPlan) -> list[str]: + lines = [f"request_cpus = {plan.cpus}", f"+xcount = {plan.cpus}"] + + if plan.memory_mb is not None: + lines.extend( + [f"request_memory = {plan.memory_mb}", f"+maxMemory = {plan.memory_mb}"] + ) + + if plan.wall_time_s is not None: + lines.append(f"+BatchRuntime = {plan.wall_time_s}") + + if plan.queue is not None: + lines.append(f"+queue = {_classad_string(plan.queue)}") + + return lines + + +def _render_queue(plan: SubmitPlan) -> list[str]: + return [ + # Keep completed jobs until purge() releases them + "leave_in_queue = (JobStatus == 4)", + f"queue {len(plan.copies)}", + ] diff --git a/src/intercede/_backends/credentials.py b/src/intercede/_backends/credentials.py new file mode 100644 index 0000000..02e804a --- /dev/null +++ b/src/intercede/_backends/credentials.py @@ -0,0 +1,157 @@ +"""What a backend asks its credential provider for, when, and what it accepts back. + +``credential_requirements`` turns a configuration into what to ask for. This is +also the one place freshness is decided. A backend keeps the credential it was +last given, privately, and before each operation calls ``refresh_if_stale``: +the provider is asked only when there is none yet or it is about to expire. +Where credentials come from, and how they are renewed, stays the consumer's +business, inside its provider. +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from intercede.auth.models import ( + BearerToken, + Credential, + CredentialRequirements, + SSHPassword, + SSHPrivateKey, +) +from intercede.auth.protocols import CredentialProvider +from intercede.config import ( + ARCConfig, + BackendConfig, + BatchSSHConfig, + HTCondorCEConfig, +) +from intercede.exceptions import AuthenticationError, InterCEdeError + +# What each configured auth mode asks the credential provider for. +# "agent" is absent on purpose: an SSH agent holds the key, so nothing is asked. +AUTH_KINDS: dict[str, type[Credential]] = { + "token": BearerToken, + "key": SSHPrivateKey, + "password": SSHPassword, +} + +# Ask again this long before a credential expires, so it cannot run out in the +# middle of an operation. A library default; whether a provider should be able +# to change it is still open. +DEFAULT_MARGIN = timedelta(minutes=5) + + +def credential_requirements( + config: BackendConfig, scopes: frozenset[str] = frozenset() +) -> CredentialRequirements | None: + """Say what a backend must ask its provider for. + + Args: + config: The backend's validated configuration. + scopes: The scopes of the operation about to run, for token-based + backends; ignored by the others. + + Returns: + What to ask for, or None when the backend needs no credential: it runs + on this host, or an SSH agent holds the key. + """ + if isinstance(config, ARCConfig | HTCondorCEConfig): + # The endpoint is the resource, so a token is minted for this CE's audience. + return CredentialRequirements( + resource=config.endpoint, + kind=AUTH_KINDS[config.auth], + scopes=scopes, + ) + if isinstance(config, BatchSSHConfig) and config.auth != "agent": + # The resource is the login, ``user@host:port``: a provider finds the key + # or password by it, and the same host can take different users. + return CredentialRequirements( + resource=f"{config.user}@{config.host}:{config.port}", + kind=AUTH_KINDS[config.auth], + ) + return None + + +def is_stale( + credential: Credential | None, + requirements: CredentialRequirements, + *, + margin: timedelta = DEFAULT_MARGIN, + now: datetime | None = None, +) -> bool: + """Tell whether ``credential`` cannot serve ``requirements`` for ``margin`` more. + + A credential that never expires is never stale. + + Args: + credential: The one the backend holds, or None before its first request. + requirements: What the backend needs for the operation about to run. + margin: How long the credential must stay valid from now. + now: The current time; tests pass a fixed one. + + Returns: + True when there is no credential yet, when it is of another kind than + required, or when it expires within ``margin``. + """ + if not isinstance(credential, requirements.kind): + return True + if credential.expires_at is None: + return False + return credential.expires_at - margin <= (now or datetime.now(UTC)) + + +async def refresh_if_stale( + current: Credential | None, + requirements: CredentialRequirements, + provider: CredentialProvider, + *, + margin: timedelta = DEFAULT_MARGIN, + now: datetime | None = None, +) -> Credential: + """Return ``current`` while it is fresh, otherwise a new one from ``provider``. + + Args: + current: The credential the backend holds, or None before its first request. + requirements: What the backend needs for the operation about to run. + provider: The consumer's provider, asked only when ``current`` is stale. + margin: How long the credential must stay valid from now. + now: The current time; tests pass a fixed one. + + Returns: + The credential to authenticate with: ``current``, or the provider's new one. + + Raises: + AuthenticationError: The provider failed, returned something other than + the required kind, or returned a credential that has already expired. + Always a failure of the whole operation, never a per-job outcome. + """ + if not is_stale(current, requirements, margin=margin, now=now): + assert current is not None # is_stale() is True for None + return current + + try: + fresh = await provider.get(requirements) + except InterCEdeError: + raise # already typed, e.g. an AuthenticationError from the provider + except Exception as exc: + # Only the type: the provider's message may hold a token or a secret URL. + # The exception itself stays available as __cause__. + raise AuthenticationError( + f"the credential provider failed for {requirements.resource} " + f"with {type(exc).__name__}" + ) from exc + + if not isinstance(fresh, requirements.kind): + raise AuthenticationError( + f"the credential provider returned a {type(fresh).__name__} " + f"for {requirements.resource}, not a {requirements.kind.__name__}" + ) + # Expiring within the margin is accepted (it is asked again next time); + # already expired is not, since it cannot authenticate anything. + if is_stale(fresh, requirements, margin=timedelta(0), now=now): + raise AuthenticationError( + f"the credential provider returned an expired credential " + f"for {requirements.resource}" + ) + return fresh diff --git a/src/intercede/_backends/fake.py b/src/intercede/_backends/fake.py index 53c4d59..3171866 100644 --- a/src/intercede/_backends/fake.py +++ b/src/intercede/_backends/fake.py @@ -13,6 +13,7 @@ from typing import Self from intercede._backends.config import FakeConfig +from intercede.auth.protocols import CredentialProvider from intercede.exceptions import ( InterCEdeError, ResourceUnavailableError, @@ -94,11 +95,15 @@ def __init__( self._closed = False @classmethod - def from_settings(cls, settings: FakeConfig) -> Self: + def from_settings( + cls, settings: FakeConfig, credentials: CredentialProvider + ) -> Self: """Build the fake from its settings; how the registry constructs it. Args: settings: The fake's settings: only the resource it reports. + credentials: Never asked: nothing leaves the process, so the fake + needs no credentials. Returns: A new fake, not yet opened. @@ -307,7 +312,12 @@ def _read_local_inputs(inputs: Sequence[FileRef]) -> dict[str, bytes]: contents: dict[str, bytes] = {} for ref in inputs: if not _is_url(ref.source): - contents[ref.name] = Path(ref.source).read_bytes() + try: + contents[ref.name] = Path(ref.source).read_bytes() + except OSError as exc: + raise SpecificationRejectedError( + f"input {ref.name!r}: cannot read {ref.source}: {exc.strerror}" + ) from exc return contents @staticmethod @@ -379,4 +389,6 @@ def _write_job_files( _kill: type[Killable] = FakeBackend _purge: type[Purgeable] = FakeBackend _diag: type[Diagnosable] = FakeBackend -_built_by_registry: Callable[[FakeConfig], JobBackend] = FakeBackend.from_settings +_built_by_registry: Callable[[FakeConfig, CredentialProvider], JobBackend] = ( + FakeBackend.from_settings +) diff --git a/src/intercede/_backends/monolith/__init__.py b/src/intercede/_backends/monolith/__init__.py new file mode 100644 index 0000000..1a90eaa --- /dev/null +++ b/src/intercede/_backends/monolith/__init__.py @@ -0,0 +1 @@ +"""Monolithic backends: services that submit and schedule by themselves.""" diff --git a/src/intercede/_backends/monolith/htcondorce/__init__.py b/src/intercede/_backends/monolith/htcondorce/__init__.py new file mode 100644 index 0000000..3974421 --- /dev/null +++ b/src/intercede/_backends/monolith/htcondorce/__init__.py @@ -0,0 +1,22 @@ +"""An HTCondor-CE, reached as a remote schedd (issue #23). + +The backend drives the HTCondor command-line tools, as DIRAC's +``HTCondorCEComputingElement`` does with ``UseLocalSchedd = False``: jobs are +submitted with ``condor_submit -remote`` and their inputs spooled to the CE at +submit time, so no HTCondor daemon runs on the submitting host. + +- ``backend``: the contract operations (submit, status) +- ``session``: one operation's credentials, and the tools run with them +- ``staging``: the private working area, and what a submission puts in it +- ``process``: running one tool as a subprocess + +What HTCondor itself knows (submit descriptions, commands, the state mapping) +lives in ``_backends._htcondor`` and is shared with the HTCondor scheduler of +the composed backend. This package holds only what is specific to a remote CE. +""" + +from __future__ import annotations + +from intercede._backends.monolith.htcondorce.backend import HTCondorCEBackend + +__all__ = ["HTCondorCEBackend"] diff --git a/src/intercede/_backends/monolith/htcondorce/backend.py b/src/intercede/_backends/monolith/htcondorce/backend.py new file mode 100644 index 0000000..6059258 --- /dev/null +++ b/src/intercede/_backends/monolith/htcondorce/backend.py @@ -0,0 +1,250 @@ +"""The contract operations of the HTCondor-CE backend.""" + +from __future__ import annotations + +import re +import shutil +import uuid +from collections.abc import AsyncGenerator, Callable, Iterable, Mapping, Sequence +from contextlib import asynccontextmanager +from pathlib import Path +from types import TracebackType +from typing import Any, Self + +from intercede._backends._htcondor import status +from intercede._backends._htcondor.submit import SubmitPlan, render +from intercede._backends.credentials import credential_requirements, refresh_if_stale +from intercede._backends.monolith.htcondorce import staging +from intercede._backends.monolith.htcondorce.process import Runner, run_process +from intercede._backends.monolith.htcondorce.session import ( + CondorSession, + credential_files, +) +from intercede.auth.models import BearerToken +from intercede.auth.protocols import CredentialProvider +from intercede.config import HTCondorCEConfig +from intercede.exceptions import InterCEdeError, SpecificationRejectedError +from intercede.models import ( + CopyVars, + JobHandle, + JobID, + JobStatus, + StatusMap, + Submission, + SubmissionSpec, +) +from intercede.protocols import JobBackend + +BACKEND = "htcondor-ce" +DEFAULT_PORT = 9619 + +# Token scopes per operation (WLCG token profile), so a status poller carries +# a read scope and nothing that would let it submit. +SUBMIT_SCOPES = frozenset({"compute.create"}) +READ_SCOPES = frozenset({"compute.read"}) + +_JOB_ID = re.compile(r"^\d+\.\d+$") + + +class HTCondorCEBackend: + """An HTCondor-CE: submit and status. + + It has no live diagnostics (issue #23); ``Diagnosable`` is absent on purpose. + """ + + def __init__( + self, + settings: HTCondorCEConfig, + credentials: CredentialProvider, + *, + runner: Runner = run_process, + workdir: Path | None = None, + ) -> None: + # Construction is cheap and does no I/O. + self._settings = settings + self._provider = credentials + self._run = runner + self._workdir = workdir or staging.default_workdir() + self._host, port = split_endpoint(settings.endpoint) + self._pool = f"{self._host}:{port}" + # The CE's schedd is named after its host unless the site says otherwise. + self._name = settings.schedd or self._host + self._tokens: dict[frozenset[str], BearerToken] = {} # per scope set + self._closed = False + + @classmethod + def from_settings( + cls, settings: HTCondorCEConfig, credentials: CredentialProvider + ) -> Self: + """Build the backend from its settings; how the registry constructs it. + + Args: + settings: The CE's validated configuration. + credentials: The consumer's provider, asked for a token when an + operation first needs one. + + Returns: + A new backend, not yet opened. + """ + return cls(settings, credentials) + + @property + def resource(self) -> str: + """The CE this backend talks to; the ``resource`` of its job handles.""" + return self._settings.endpoint + + # -- lifecycle --------------------------------------------------------- + + async def __aenter__(self) -> Self: + self._closed = False + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + # Idempotent. Cached tokens are dropped; they were never written anywhere. + self._closed = True + self._tokens.clear() + + # -- Submitter --------------------------------------------------------- + + async def submit( + self, spec: SubmissionSpec, copies: int | Sequence[CopyVars] = 1 + ) -> Submission: + self._check_usable() + copy_vars = [CopyVars()] * copies if isinstance(copies, int) else list(copies) + if not copy_vars: + return Submission(handles={}) + for index, copy in enumerate(copy_vars): + # A secret and an input would be staged to the same file. + if clashes := spec.clashes_with(copy): + raise SpecificationRejectedError( + f"copy {index}: secrets {sorted(clashes)} are named like inputs" + ) + outputs, remaps = staging.outputs(spec) + executable, ship, arguments = staging.command( + spec, self._settings.container_launcher, self.resource + ) + + handles: dict[int, JobHandle] = {} + failures: dict[int, str] = {} + async with self._session(SUBMIT_SCOPES) as session: + submission = self._workdir / uuid.uuid4().hex + submission.mkdir(mode=0o700) + try: + inputs = staging.stage_inputs(spec, submission) + for group in staging.group_by_environment(spec, copy_vars): + plan = SubmitPlan( + executable=executable, + transfer_executable=ship, + arguments=arguments, + copies=[ + staging.stage_copy(spec, copy_vars[i], submission / str(i)) + for i in group + ], + inputs=inputs, + stdout=spec.stdout or SubmitPlan.stdout, + stderr=spec.stderr or SubmitPlan.stderr, + outputs=outputs, + output_remaps=remaps, + cpus=spec.resources.cpus, + memory_mb=spec.resources.memory_mb, + wall_time_s=spec.resources.wall_time_s, + queue=spec.resources.queue or self._settings.queue, + ) + description = submission / f"group-{group[0]}.sub" + description.write_text(render(plan)) + try: + ids = await session.submit(description, len(group)) + except InterCEdeError as exc: + if not handles: + raise # nothing submitted: the whole operation failed + failures.update({i: str(exc) for i in group}) + continue + for index, job_id in zip(group, ids): + handles[index] = JobHandle( + backend=BACKEND, resource=self.resource, id=job_id + ) + finally: + # Inputs are spooled to the CE by now; secrets must not linger here. + shutil.rmtree(submission, ignore_errors=True) + return Submission(handles=handles, failures=failures) + + # -- StatusReporter ---------------------------------------------------- + + async def get_status(self, handles: Sequence[JobHandle]) -> StatusMap: + self._check_usable() + ads = await self._ads(self._ids(handles), status.STATE_ATTRIBUTES, history=True) + return { + handle: status.job_status(ads[handle.id]) + if self._owns(handle) and handle.id in ads + else JobStatus.UNKNOWN + for handle in handles + } + + # -- talking to the CE ---------------------------------------------------- + + @asynccontextmanager + async def _session(self, scopes: frozenset[str]) -> AsyncGenerator[CondorSession]: + """Open the tools for one operation, with a token scoped to it.""" + token = await self._fresh(scopes) + workdir = staging.ensure_workdir(self._workdir) + async with credential_files(token, workdir) as files: + yield CondorSession(self._run, files, self._pool, self._name) + + async def _fresh(self, scopes: frozenset[str]) -> BearerToken: + requirements = credential_requirements(self._settings, scopes) + assert requirements is not None # an HTCondor-CE always asks for a token + fresh = await refresh_if_stale( + self._tokens.get(scopes), requirements, self._provider + ) + assert isinstance(fresh, BearerToken) # refresh_if_stale checked the kind + self._tokens[scopes] = fresh + return fresh + + async def _ads( + self, ids: Sequence[JobID], attributes: Sequence[str], *, history: bool + ) -> dict[JobID, Mapping[str, Any]]: + if not ids: + return {} + async with self._session(READ_SCOPES) as session: + return await session.ads(ids, attributes, history=history) + + # -- helpers ------------------------------------------------------------- + + def _check_usable(self) -> None: + if self._closed: + raise InterCEdeError("backend is closed") + + def _owns(self, handle: JobHandle) -> bool: + return ( + handle.backend == BACKEND + and handle.resource == self.resource + and bool(_JOB_ID.match(handle.id)) + ) + + def _ids(self, handles: Iterable[JobHandle]) -> list[JobID]: + """Return the ids to ask the CE about: ours, well-formed, each once. + + Ids come from stored handles, so they are checked before they reach a + command line: a malformed one could otherwise pass as an option. + """ + return list( + dict.fromkeys(handle.id for handle in handles if self._owns(handle)) + ) + + +def split_endpoint(endpoint: str) -> tuple[str, int]: + """Split ``host[:port]``; an HTCondor-CE listens on 9619 by default.""" + host, separator, port = endpoint.partition(":") + return host, int(port) if separator else DEFAULT_PORT + + +# The type checker proves conformance. +_backend: type[JobBackend] = HTCondorCEBackend +_built_by_registry: Callable[[HTCondorCEConfig, CredentialProvider], JobBackend] = ( + HTCondorCEBackend.from_settings +) diff --git a/src/intercede/_backends/monolith/htcondorce/process.py b/src/intercede/_backends/monolith/htcondorce/process.py new file mode 100644 index 0000000..b2db0ea --- /dev/null +++ b/src/intercede/_backends/monolith/htcondorce/process.py @@ -0,0 +1,44 @@ +"""Running one HTCondor tool as a subprocess.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable, Callable, Mapping, Sequence + +from intercede._backends.batch.protocols import CommandResult +from intercede.exceptions import ConfigurationError, ResourceUnavailableError + +# How the backend runs a tool: argv, environment, timeout in seconds. +# Tests pass their own, to play the tools without HTCondor installed. +Runner = Callable[[Sequence[str], Mapping[str, str], float], Awaitable[CommandResult]] + + +async def run_process( + argv: Sequence[str], env: Mapping[str, str], timeout: float +) -> CommandResult: + """Run one HTCondor tool and wait for it, killing it after ``timeout`` seconds.""" + try: + process = await asyncio.create_subprocess_exec( + *argv, + stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env=dict(env), + ) + except FileNotFoundError as exc: + raise ConfigurationError( + f"{argv[0]} was not found: the HTCondor client tools must be installed" + ) from exc + try: + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout) + except TimeoutError as exc: + process.kill() + await process.wait() + raise ResourceUnavailableError( + f"{argv[0]} did not finish within {timeout:.0f} s" + ) from exc + return CommandResult( + returncode=process.returncode if process.returncode is not None else -1, + stdout=stdout.decode(errors="replace"), + stderr=stderr.decode(errors="replace"), + ) diff --git a/src/intercede/_backends/monolith/htcondorce/session.py b/src/intercede/_backends/monolith/htcondorce/session.py new file mode 100644 index 0000000..d220673 --- /dev/null +++ b/src/intercede/_backends/monolith/htcondorce/session.py @@ -0,0 +1,217 @@ +"""One operation's connection to the CE: its credentials, and the tools run with them. + +Every tool runs in its own subprocess, configured only through its +environment. The token for an operation is written to private files that exist +only while the operation runs, so backends with different credentials never +share HTCondor configuration. +""" + +from __future__ import annotations + +import os +import re +import shutil +import tempfile +from collections.abc import AsyncGenerator, Mapping, Sequence +from contextlib import asynccontextmanager +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from intercede._backends._htcondor import commands, status +from intercede._backends.batch.protocols import CommandResult +from intercede._backends.monolith.htcondorce.process import Runner +from intercede._backends.monolith.htcondorce.staging import write_private +from intercede.auth.models import BearerToken +from intercede.exceptions import AuthenticationError, ResourceUnavailableError +from intercede.models import JobID + +COMMAND_TIMEOUT_S = 120 # every command but output transfer, which uses the limits + + +@dataclass(frozen=True) +class CredentialFiles: + """Where one operation's token is, while it runs.""" + + token: Path + token_dir: Path + scratch: Path # HTCondor's LOG directory (SciTokens keeps a cache there) + + +@asynccontextmanager +async def credential_files( + token: BearerToken, workdir: Path +) -> AsyncGenerator[CredentialFiles, None]: + """Write the token to private files for the duration of one operation.""" + directory = Path(tempfile.mkdtemp(prefix="cred-", dir=workdir)) # mode 0700 + try: + token_dir = directory / "tokens.d" + token_dir.mkdir(mode=0o700) + secret = token.value.get_secret_value().encode() + for path in (directory / "token", token_dir / "token"): + write_private(path, secret) + scratch = directory / "log" + scratch.mkdir(mode=0o700) + yield CredentialFiles( + token=directory / "token", + token_dir=token_dir, + scratch=scratch, + ) + finally: + shutil.rmtree(directory, ignore_errors=True) + + +def environment(files: CredentialFiles) -> dict[str, str]: + """Return the environment a tool runs with, for the credentials in ``files``.""" + env = dict(os.environ) + if "CONDOR_CONFIG" not in env: + # No config file: this environment is all the configuration there is. + env["CONDOR_CONFIG"] = "ONLY_ENV" + env.update( + { + # Never fall back to an unauthenticated connection: by default + # HTCondor would quietly continue anonymously after a rejected token. + "_CONDOR_SEC_CLIENT_AUTHENTICATION": "REQUIRED", + # SCITOKENS for a CE; IDTOKENS for a schedd that issues its own + # tokens. The same token is offered to both, in that order. + "_CONDOR_SEC_CLIENT_AUTHENTICATION_METHODS": "SCITOKENS,IDTOKENS", + "_CONDOR_SCITOKENS_FILE": str(files.token), + "_CONDOR_SEC_TOKEN_DIRECTORY": str(files.token_dir), + "_CONDOR_LOG": str(files.scratch), + "_CONDOR_TOOL_DEBUG": "D_SECURITY", + } + ) + if "X509_CERT_DIR" in env: # the CAs the CE's host certificate is checked against + env["_CONDOR_AUTH_SSL_CLIENT_CADIR"] = env["X509_CERT_DIR"] + return env + + +class CondorSession: + """The HTCondor tools, run against one CE with one operation's credentials.""" + + def __init__( + self, runner: Runner, files: CredentialFiles, pool: str, name: str + ) -> None: + self.files = files + self._run = runner + self._pool = pool + self._name = name + self._remote = commands.schedd_options(pool, name) + self._env = environment(files) + + async def run( + self, argv: Sequence[str], timeout: float = COMMAND_TIMEOUT_S + ) -> CommandResult: + """Run a tool; raise when the CE rejected us or could not be reached.""" + # -debug with D_SECURITY makes the tool say why a connection failed: + # the only way to tell a rejected token from an unreachable CE. + result = await self._run([argv[0], "-debug", *argv[1:]], self._env, timeout) + if result.returncode == 0: + return result + text = f"{result.stdout}\n{result.stderr}" + if rejected := _AUTH_FAILURE.search(text): + raise AuthenticationError( + f"{self._name} rejected the credentials: {_line_of(text, rejected)}" + ) + if _UNREACHABLE.search(text): + raise ResourceUnavailableError( + f"{self._pool} could not be reached: {last_line(result)}" + ) + return result + + async def submit(self, description: Path, expected: int) -> list[JobID]: + """Submit a description file and return the ids of the jobs it created.""" + result = await self.run( + commands.submit(str(description), self._pool, self._name) + ) + require_success(result, "condor_submit") + try: + ids = commands.parse_submit(result.stdout) + except ValueError as exc: + raise ResourceUnavailableError(str(exc)) from exc + if len(ids) != expected: + raise ResourceUnavailableError( + f"condor_submit created {len(ids)} jobs, expected {expected}" + ) + return ids + + async def ads( + self, ids: Sequence[JobID], attributes: Sequence[str], *, history: bool + ) -> dict[JobID, Mapping[str, Any]]: + """Read job ads: from the queue, then (with ``history``) the rest from the history.""" + found: dict[JobID, Mapping[str, Any]] = {} + for chunk in commands.chunks(ids): + result = await self._read(commands.query(chunk, attributes, self._remote)) + found.update(result) + if history: + missing = [i for i in ids if i not in found] + for chunk in commands.chunks(missing): + result = await self._read( + commands.history(chunk, attributes, self._remote) + ) + found.update(result) + return found + + async def _read(self, argv: Sequence[str]) -> dict[JobID, Mapping[str, Any]]: + result = await self.run(argv) + require_success(result, argv[0]) + try: + ads = status.parse_ads(result.stdout) + except ValueError as exc: # also covers json.JSONDecodeError + raise ResourceUnavailableError( + f"{argv[0]} printed unreadable output: {exc}" + ) from exc + return { + status.job_id(ad): ad for ad in ads if "ClusterId" in ad and "ProcId" in ad + } + + +# -- reading what a tool said --------------------------------------------------- + +# Markers in the -debug output. An authentication failure also reports that +# the collector "could not be contacted", so it is checked first. +_AUTH_FAILURE = re.compile( + # condor_submit prints only the SECMAN line; condor_q also the AUTHENTICATE + # summary. Not "method ... failed": that is logged even when the next + # method then succeeds. + r"required authentication with .* failed|AUTHENTICATE:\d+|PERMISSION DENIED|not authorized", + re.IGNORECASE, +) +_UNREACHABLE = re.compile( + r"Connection refused|connect errno|Failed to connect|Couldn't contact|Can't find address|" + r"couldn't locate|Unable to locate|Name or service not known|timed out", + re.IGNORECASE, +) +_DEBUG_LINE = re.compile(r"^\d\d/\d\d/\d\d \d\d:\d\d:\d\d ") + + +def _line_of(text: str, match: re.Match[str]) -> str: + """Return the line holding ``match``, without its -debug timestamp.""" + start = text.rfind("\n", 0, match.start()) + 1 + end = text.find("\n", match.end()) + line = text[start : end if end != -1 else len(text)].strip() + return _DEBUG_LINE.sub("", line) + + +def last_line(result: CommandResult) -> str: + """Return the tool's own last message, without the -debug lines.""" + lines = [ + line.strip() + for line in f"{result.stdout}\n{result.stderr}".splitlines() + if line.strip() and not _DEBUG_LINE.match(line) + ] + if lines: + return lines[-1] + else: + return f"exit code {result.returncode}" + + +def failure(result: CommandResult, tool: str) -> str: + """Describe why a tool failed, in one line.""" + return f"{tool} failed: {last_line(result)}" + + +def require_success(result: CommandResult, tool: str) -> None: + """Raise when a tool whose failure fails the whole operation did not succeed.""" + if result.returncode != 0: + raise ResourceUnavailableError(failure(result, tool)) diff --git a/src/intercede/_backends/monolith/htcondorce/staging.py b/src/intercede/_backends/monolith/htcondorce/staging.py new file mode 100644 index 0000000..79cccde --- /dev/null +++ b/src/intercede/_backends/monolith/htcondorce/staging.py @@ -0,0 +1,187 @@ +"""The private working area, and what a submission puts in it. + +Everything here turns a ``SubmissionSpec`` into what HTCondor is given: files +staged under their names, one directory per copy holding only that copy's +secrets, and the executable, arguments and outputs in HTCondor's terms. +""" + +from __future__ import annotations + +import os +import re +import stat +import tempfile +from collections.abc import Sequence +from pathlib import Path, PurePosixPath + +from intercede._backends._htcondor.submit import CopyPlan +from intercede.exceptions import ConfigurationError, SpecificationRejectedError +from intercede.models import CopyVars, SubmissionSpec + +_GLOB = re.compile(r"[*?\[]") + + +# -- the working area --------------------------------------------------------- + + +def default_workdir() -> Path: + """Return where this user's staging and collection areas live on this host.""" + return Path(tempfile.gettempdir()) / f"intercede-htcondor-ce-{os.getuid()}" + + +def ensure_workdir(workdir: Path) -> Path: + """Create the private working area, refusing one somebody else controls.""" + workdir.mkdir(mode=0o700, parents=True, exist_ok=True) + info = workdir.lstat() + if ( + stat.S_ISLNK(info.st_mode) + or not stat.S_ISDIR(info.st_mode) + or info.st_uid != os.getuid() + ): + raise ConfigurationError(f"{workdir} is not a directory owned by this user") + workdir.chmod(0o700) + return workdir + + +def write_private(path: Path, content: bytes) -> None: + """Create a file only this user can read (0600); never overwrite one.""" + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "wb") as handle: + handle.write(content) + + +# -- files -------------------------------------------------------------------- + + +def stage_inputs(spec: SubmissionSpec, submission: Path) -> list[str]: + """Copy local inputs under their names, so they spool with the right layout. + + Returns the entries for ``transfer_input_files``: the staged directory and + the URLs the resource fetches itself. + """ + staged: list[str] = [] + common = submission / "inputs" + for ref in spec.inputs: + if "://" in ref.source: + if PurePosixPath(ref.source.split("?")[0]).name != ref.name: + raise SpecificationRejectedError( + f"input {ref.name!r}: HTCondor names a URL input after the URL, " + f"so {ref.source!r} would arrive under another name" + ) + staged.append(ref.source) # fetched by the resource + continue + target = common / ref.name + target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + # Read now: the caller may delete its file once submit() returns. + try: + content = Path(ref.source).read_bytes() + except OSError as exc: + raise SpecificationRejectedError( + f"input {ref.name!r}: cannot read {ref.source}: {exc.strerror}" + ) from exc + target.write_bytes(content) + if common.exists(): + # Trailing slash: the directory's contents, keeping sub-directories. + staged.append(f"{common}/") + return staged + + +def stage_copy(spec: SubmissionSpec, copy: CopyVars, directory: Path) -> CopyPlan: + """Give one copy its own directory, holding only its secrets (0600).""" + directory.mkdir(mode=0o700) + inputs: list[str] = [] + if copy.secrets: + secrets = directory / "secrets" + secrets.mkdir(mode=0o700) + for name, secret in copy.secrets.items(): + target = secrets / name + target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + write_private(target, secret.get_secret_value()) # HTCondor keeps the mode + inputs.append("secrets/") + return CopyPlan( + initialdir=str(directory), + environment={**spec.environment, **copy.environment}, + inputs=inputs, + ) + + +def group_by_environment( + spec: SubmissionSpec, copies: Sequence[CopyVars] +) -> list[list[int]]: + """Group copy indexes by the names of their environment variables. + + HTCondor merges each process's environment onto the previous one, so a + variable of one copy would leak into the next in the same cluster: copies + with different names must go to different clusters. + """ + groups: dict[frozenset[str], list[int]] = {} + for index, copy in enumerate(copies): + names = frozenset({*spec.environment, *copy.environment}) + groups.setdefault(names, []).append(index) + return list(groups.values()) + + +# -- what HTCondor runs and returns --------------------------------------------- + + +def command( + spec: SubmissionSpec, launcher: Sequence[str] | None, resource: str +) -> tuple[str, bool, list[str]]: + """Return what HTCondor runs: the executable, whether to ship it, and its arguments. + + A file on this host is shipped; anything else is a command on the worker. + A container image is run through the configured launcher. + """ + executable = spec.executable + arguments = list(spec.arguments) + is_local_file = Path(spec.executable).is_file() + + if spec.container is None: + return executable, is_local_file, arguments + + if launcher is None: + raise SpecificationRejectedError( + f"{resource} has no container_launcher configured, so it cannot run " + f"{spec.container.image!r}" + ) + + if is_local_file: + raise SpecificationRejectedError( + "a container job runs a command inside the image, not a local file" + ) + + launcher_args = [arg.replace("{image}", spec.container.image) for arg in launcher] + + return (launcher_args[0], False, [*launcher_args[1:], executable, *arguments]) + + +def outputs(spec: SubmissionSpec) -> tuple[list[str] | None, dict[str, str]]: + """Return output files to retrieve and files to remap. + + None means retrieve all outputs. Remaps map output names to destinations. + """ + if spec.outputs is None: + return [], {} + + include_unlisted = spec.outputs.include_unlisted + kept: list[str] = [] + remaps: dict[str, str] = {} + + for member in spec.outputs.members: + pattern = member.pattern + destination = member.destination + + if _GLOB.search(pattern): + if not include_unlisted or destination is not None: + raise SpecificationRejectedError( + f"output {pattern!r}: " + "HTCondor selects outputs by name, not by pattern" + ) + continue # include_unlisted brings it back anyway + + kept.append(pattern) + + if destination is not None: + remaps[pattern] = destination # uploaded by the resource + + return (None if include_unlisted else kept), remaps diff --git a/src/intercede/auth/__init__.py b/src/intercede/auth/__init__.py new file mode 100644 index 0000000..0b886c3 --- /dev/null +++ b/src/intercede/auth/__init__.py @@ -0,0 +1,28 @@ +"""Backend credentials: typed, declared, supplied by a provider. + +A consumer implements a ``CredentialProvider``, which returns the one credential +a backend asks for. Configuration never holds a secret: it only says how a backend +logs in, and the provider supplies the credential at run time. +""" + +from __future__ import annotations + +from intercede.auth.models import ( + BearerToken, + Credential, + CredentialRequirements, + SSHPassword, + SSHPrivateKey, +) +from intercede.auth.protocols import CredentialProvider +from intercede.auth.providers import StaticCredentials + +__all__ = [ + "BearerToken", + "Credential", + "CredentialProvider", + "CredentialRequirements", + "SSHPassword", + "SSHPrivateKey", + "StaticCredentials", +] diff --git a/src/intercede/auth/models.py b/src/intercede/auth/models.py new file mode 100644 index 0000000..868c5b9 --- /dev/null +++ b/src/intercede/auth/models.py @@ -0,0 +1,106 @@ +"""The public credential models a consumer of interCEde can use. + +Credentials are immutable values. Secret material is held in pydantic's secret +types, so a credential cannot be printed or logged by accident: ``repr``, +``str`` and JSON all show ``**********``, and the content is only readable on +purpose, with ``get_secret_value()``. +""" + +from __future__ import annotations + +from typing import Self + +from pydantic import ( + AwareDatetime, + ConfigDict, + SecretBytes, + SecretStr, + model_validator, +) + +from intercede.models import _Model + +__all__ = [ + "BearerToken", + "Credential", + "CredentialRequirements", + "SSHPassword", + "SSHPrivateKey", +] + + +# -------------------------------------------------------------------------- +# Credential values +# -------------------------------------------------------------------------- + + +class Credential(_Model): + """Base of every credential: the one field the freshness check needs. + + Not used on its own: a provider returns one of the concrete kinds below. + """ + + # Added to _Model's settings: a value given by mistake may be the secret + # itself, so no error message repeats one. + model_config = ConfigDict(hide_input_in_errors=True, use_attribute_docstrings=True) + + expires_at: AwareDatetime | None = None + """When the credential stops working, with a timezone, so it can be compared + with the current time. None means it never expires, as for SSH secrets.""" + + +class BearerToken(Credential): + """A token for the channel to a CE. Opaque to interCEde.""" + + value: SecretStr + """The token itself.""" + + +class SSHPrivateKey(Credential): + """An SSH private key: the key itself, never a path on some host.""" + + pem: SecretBytes + """The private key, PEM-encoded.""" + + passphrase: SecretStr | None = None + """The passphrase the key is encrypted with, or None if it is not.""" + + +class SSHPassword(Credential): + """A password for an SSH login.""" + + value: SecretStr + """The password itself.""" + + +# -------------------------------------------------------------------------- +# What a backend asks for +# -------------------------------------------------------------------------- + + +class CredentialRequirements(_Model): + """What a backend asks its provider for. + + The backend computes it from its own configuration and keeps it to itself: + a consumer only meets it as the argument to its provider's ``get``. + """ + + model_config = ConfigDict(use_attribute_docstrings=True) + + resource: str + """Which backend instance is asking: the endpoint it talks to, the same + string as ``JobHandle.resource``. For a token this is also the audience, + in the form that CE expects.""" + + kind: type[Credential] + """The kind of credential needed: a backend authenticates with exactly one.""" + + scopes: frozenset[str] = frozenset() + """For a token, the scopes of the operation about to run; empty for the + other kinds.""" + + @model_validator(mode="after") + def _concrete_kind(self) -> Self: + if self.kind is Credential: + raise ValueError("kind must be a concrete kind, not the Credential base") + return self diff --git a/src/intercede/auth/protocols.py b/src/intercede/auth/protocols.py new file mode 100644 index 0000000..f3b9951 --- /dev/null +++ b/src/intercede/auth/protocols.py @@ -0,0 +1,48 @@ +"""The public protocol for a ``CredentialProvider``.""" + +from __future__ import annotations + +from types import TracebackType +from typing import Protocol, Self, runtime_checkable + +from intercede.auth.models import Credential, CredentialRequirements + +__all__ = ["CredentialProvider"] + + +@runtime_checkable +class CredentialProvider(Protocol): + """The protocol any consumer's own credential provider must satisfy. + + The consumer creates the provider, shares it between backends and closes + it: interCEde never closes a provider, because it did not create it. A + backend calls ``get`` only when its current credential is missing or + close to expiry, so the consumer decides where credentials come from and + interCEde decides when to ask. + """ + + async def get(self, requirements: CredentialRequirements) -> Credential: + """Return the credential a backend needs. + + Args: + requirements: The resource, the kind of credential it takes, and + the scopes of the operation about to run. + + Returns: + One credential of ``requirements.kind``. + + Raises: + Exception: Anything raised here fails the whole operation: the + backend reports it as an ``AuthenticationError``, never as a + per-job outcome. + """ + ... + + async def __aenter__(self) -> Self: ... + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: ... diff --git a/src/intercede/auth/providers.py b/src/intercede/auth/providers.py new file mode 100644 index 0000000..f6c2fe1 --- /dev/null +++ b/src/intercede/auth/providers.py @@ -0,0 +1,77 @@ +"""Ready-made credential providers.""" + +from __future__ import annotations + +from collections.abc import Iterable +from types import TracebackType +from typing import Self + +from intercede.auth.models import Credential, CredentialRequirements +from intercede.auth.protocols import CredentialProvider +from intercede.exceptions import AuthenticationError + +__all__ = ["StaticCredentials"] + + +class StaticCredentials: + """A provider holding fixed credentials: files read once, or fixed values. + + For standalone use, tests and the integration stacks, where nothing issues + or renews credentials. It holds at most one credential of each kind, since + one provider can serve several backends, and each backend receives only the + one it asks for. It holds nothing to release, so closing does nothing, but + it is still a context manager, like every provider:: + + async with StaticCredentials([SSHPrivateKey(pem=key)]) as credentials: + backend = registry.get_backend(config, credentials) + """ + + def __init__(self, credentials: Iterable[Credential] = ()) -> None: + # Validated now, so a duplicate kind or plain data fails at construction. + self._credentials: dict[type[Credential], Credential] = {} + for credential in credentials: + # A plain dict is ambiguous: {"value": ...} fits both a BearerToken + # and an SSHPassword. Guessing the kind of a secret is never right. + # Never repeat the item in the message: it may be the secret itself. + if not isinstance(credential, Credential) or type(credential) is Credential: + raise ValueError( + "StaticCredentials holds concrete credential objects, " + "e.g. BearerToken(value=...), not plain data" + ) + kind = type(credential) + if kind in self._credentials: + raise ValueError(f"more than one credential of kind {kind.__name__}") + self._credentials[kind] = credential + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + return None + + async def get(self, requirements: CredentialRequirements) -> Credential: + """Return the held credential of the requested kind. + + Args: + requirements: What the backend asks for. + + Returns: + The held credential of ``requirements.kind``. + + Raises: + AuthenticationError: It holds no credential of that kind. + """ + credential = self._credentials.get(requirements.kind) + if credential is None: + raise AuthenticationError( + f"no {requirements.kind.__name__} for {requirements.resource}" + ) + return credential + + +_provider: type[CredentialProvider] = StaticCredentials diff --git a/src/intercede/config.py b/src/intercede/config.py index e9be28a..f2a9c7b 100644 --- a/src/intercede/config.py +++ b/src/intercede/config.py @@ -16,13 +16,14 @@ known_hosts = "batch.example.org ssh-ed25519 AAAA..." Configuration describes the resource and is never secret: keys, passwords, -tokens and proxies come from the credential provider at run time. Error +and tokens come from the credential provider at run time. Error messages therefore never repeat the values they were given. The kinds are a closed set: they list what interCEde ships. """ from __future__ import annotations +import re from collections.abc import Mapping, Sequence from typing import Annotated, Any, Literal, Self @@ -91,6 +92,10 @@ def _launcher_names_the_image(self) -> Self: # -- grid CEs that schedule by themselves ------------------------------------- +_HOST_PORT = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::\d{1,5})?") +# "host" or "name@host": no leading "-" and no spaces, so never read as an option. +_SCHEDD = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*(?:@[A-Za-z0-9][A-Za-z0-9.-]*)?") + class ARCConfig(_QueueConfig): """An ARC CE.""" @@ -101,15 +106,8 @@ class ARCConfig(_QueueConfig): endpoint: str """The CE's REST endpoint, e.g. ``"https://arc.example.org:443/arex"``.""" - auth: frozenset[Literal["token", "proxy"]] = frozenset({"token"}) - """Which credentials the provider must supply, all of them together: a token - for the channel, a proxy for delegation, or both.""" - - @model_validator(mode="after") - def _auth_not_empty(self) -> Self: - if not self.auth: - raise ValueError("auth must name at least one of 'token', 'proxy'") - return self + auth: Literal["token"] = "token" + """Which credential the provider must supply: a token for the channel.""" class HTCondorCEConfig(_QueueConfig): @@ -121,15 +119,23 @@ class HTCondorCEConfig(_QueueConfig): endpoint: str """The CE's collector, as ``"host"`` or ``"host:port"``, e.g. ``"ce.example.org:9619"``.""" - auth: frozenset[Literal["token", "proxy"]] = frozenset({"token"}) - """Which credentials the provider must supply. The token authenticates the - channel; ``"proxy"`` adds an X.509 proxy for sites that account on VOMS attributes.""" + schedd: str | None = None + """The CE's schedd, when it is not named after the endpoint's host: ``"name@host"`` + for one of several CEs on one host, or a CE behind a forwarded address.""" + + auth: Literal["token"] = "token" + """Which credential the provider must supply: a token for the channel.""" @model_validator(mode="after") - def _token_required(self) -> Self: - if "token" not in self.auth: + def _names_fit_a_command_line(self) -> Self: + # Both end up on the tools' command lines, as "-pool host:port -name schedd". + if not _HOST_PORT.fullmatch(self.endpoint): + raise ValueError( + "endpoint must be 'host' or 'host:port', e.g. 'ce.example.org:9619'" + ) + if self.schedd is not None and not _SCHEDD.fullmatch(self.schedd): raise ValueError( - "an HTCondor-CE authenticates with a token; auth must include 'token'" + "schedd must be 'host' or 'name@host', e.g. 'ce01@ce.example.org'" ) return self diff --git a/src/intercede/registry.py b/src/intercede/registry.py index 063afe1..9c57db7 100644 --- a/src/intercede/registry.py +++ b/src/intercede/registry.py @@ -7,6 +7,8 @@ Every registered class provides a ``from_settings`` classmethod, which is how the registry builds it from a validated configuration model. +The parts that authenticate (single-class backends and transports) also +receive the consumer's credential provider; a scheduler only builds commands. What it builds is checked against the relevant protocol before it is returned, so a broken entry fails here, with a clear error, and not at the first call. """ @@ -20,6 +22,7 @@ from intercede._backends.batch.protocols import Scheduler, Transport from intercede._backends.config import FakeConfig +from intercede.auth.protocols import CredentialProvider from intercede.config import ( _MODELS as _CONFIG_MODELS, ) @@ -29,7 +32,7 @@ BatchSSHConfig, validate_config, ) -from intercede.exceptions import RegistryError +from intercede.exceptions import ConfigurationError, RegistryError from intercede.protocols import JobBackend __all__ = ["available", "get_backend"] @@ -42,6 +45,7 @@ # never need classes of their own. _BACKENDS: dict[str, str] = { "fake": "intercede._backends.fake:FakeBackend", # internal, for the test suites + "htcondor-ce": "intercede._backends.monolith.htcondorce:HTCondorCEBackend", } _TRANSPORTS: dict[str, str] = {} _SCHEDULERS: dict[str, str] = {} @@ -53,25 +57,39 @@ } -def get_backend(config: BackendConfig | Mapping[str, Any]) -> JobBackend: +def get_backend( + config: BackendConfig | Mapping[str, Any], credentials: CredentialProvider +) -> JobBackend: """Build the backend a configuration describes. - The backend is returned unopened: use it as ``async with registry.get_backend(config) as ce``. - Construction does no I/O, so building a backend for an unreachable resource succeeds. + The backend is returned unopened: use it as + ``async with registry.get_backend(config, credentials) as ce``. Construction + does no I/O and asks the provider for nothing, so building a backend for an + unreachable resource succeeds. The backend asks for credentials when it + first needs them, and again when they are about to expire. Args: config: A ``BackendConfig``, or the same data as a mapping, for example a parsed TOML table. + credentials: The consumer's provider. The consumer opens and closes it; + interCEde never does. One provider is normally shared by every + backend a task drives. Returns: The backend, not yet opened. Raises: - ConfigurationError: The configuration is invalid. + ConfigurationError: The configuration is invalid, or ``credentials`` + is not a ``CredentialProvider``. RegistryError: The configuration is valid, but this version of interCEde does not provide what it asks for. """ - return _build(validate_config(config)) + validated = validate_config(config) + if not isinstance(credentials, CredentialProvider): + raise ConfigurationError( + f"credentials must be a CredentialProvider, not a {type(credentials).__name__}" + ) + return _build(validated, credentials) def available() -> dict[str, tuple[str, ...]]: @@ -123,11 +141,14 @@ def _choices(annotation: Any) -> set[str]: return values -def _build(config: BackendConfig | FakeConfig) -> JobBackend: +def _build( + config: BackendConfig | FakeConfig, credentials: CredentialProvider +) -> JobBackend: """Build a backend from a validated configuration. Internal: the test suites call it directly. Args: config: The validated configuration of one backend, or the fake's settings. + credentials: The consumer's provider, for the parts that authenticate. Returns: The backend, not yet opened. A ``batch`` backend is composed of the @@ -139,14 +160,14 @@ def _build(config: BackendConfig | FakeConfig) -> JobBackend: what was built does not satisfy its protocol. """ if not isinstance(config, BatchLocalConfig | BatchSSHConfig): - built = _load("backend", config.kind).from_settings(config) + built = _load("backend", config.kind).from_settings(config, credentials) result: JobBackend = _checked("backend", config.kind, built, JobBackend) return result transport: Transport = _checked( "transport", config.transport, - _load("transport", config.transport).from_settings(config), + _load("transport", config.transport).from_settings(config, credentials), Transport, ) scheduler: Scheduler = _checked( diff --git a/tests/integration/stacks/_template/config/basic/intercede-client.toml b/tests/integration/stacks/_template/config/basic/intercede-client.toml index 785b352..54f2be0 100644 --- a/tests/integration/stacks/_template/config/basic/intercede-client.toml +++ b/tests/integration/stacks/_template/config/basic/intercede-client.toml @@ -9,5 +9,5 @@ endpoint = "CHANGEME" # e.g. "https://localhost:443/arex" or "localhost:2222" queue = "CHANGEME" [credentials] -type = "CHANGEME" # token | proxy | ssh-key +type = "CHANGEME" # token | ssh-key path = "credentials/CHANGEME/" # under the ./credentials bind mount diff --git a/tests/unit/_registry_dummies.py b/tests/unit/_registry_dummies.py index 5dc02fe..345b4eb 100644 --- a/tests/unit/_registry_dummies.py +++ b/tests/unit/_registry_dummies.py @@ -19,10 +19,13 @@ async def __aexit__(self, *exc_info: object) -> None: ... class DummyTransport(_Lifecycle): def __init__(self, settings: Any) -> None: self.settings = settings + self.credentials: Any = None @classmethod - def from_settings(cls, settings: Any) -> DummyTransport: - return cls(settings) + def from_settings(cls, settings: Any, credentials: Any) -> DummyTransport: + built = cls(settings) + built.credentials = credentials + return built async def run(self, argv: Any) -> Any: ... @@ -74,10 +77,13 @@ class DummyBackend(_Lifecycle): def __init__(self, settings: Any) -> None: self.settings = settings + self.credentials: Any = None @classmethod - def from_settings(cls, settings: Any) -> DummyBackend: - return cls(settings) + def from_settings(cls, settings: Any, credentials: Any) -> DummyBackend: + built = cls(settings) + built.credentials = credentials + return built async def submit(self, spec: Any, copies: Any = 1) -> Any: ... diff --git a/tests/unit/backends/__init__.py b/tests/unit/backends/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/backends/_htcondor/__init__.py b/tests/unit/backends/_htcondor/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/backends/_htcondor/test_core.py b/tests/unit/backends/_htcondor/test_core.py new file mode 100644 index 0000000..185d2e6 --- /dev/null +++ b/tests/unit/backends/_htcondor/test_core.py @@ -0,0 +1,360 @@ +"""The shared HTCondor knowledge: submit descriptions, commands and the state mapping. + +Expected values were checked against HTCondor 25 (condor_submit -dry-run and a +live schedd): what is asserted here is what HTCondor actually does with them. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from intercede import JobStatus +from intercede._backends._htcondor import commands, status, submit +from intercede._backends._htcondor.submit import CopyPlan, SubmitPlan, render + +# -------------------------------------------------------------------------- +# Quoting +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("arguments", "quoted"), + [ + (["plain"], "\"'plain'\""), + (["two words"], "\"'two words'\""), + (["it's"], "\"'it''s'\""), + (['say "hi"'], '"\'say ""hi""\'"'), + (["cost $(HOME) $5"], "\"'cost $(DOLLAR)(HOME) $(DOLLAR)5'\""), + ([""], "\"''\""), + (["a", "b"], "\"'a' 'b'\""), + ], + ids=[ + "plain", + "space", + "single-quote", + "double-quote", + "dollar", + "empty", + "several", + ], +) +def test_quote_arguments(arguments: list[str], quoted: str): + assert submit.quote_arguments(arguments) == quoted + + +def test_quote_environment_sorts_and_quotes(): + quoted = submit.quote_environment({"STAMP": "a b", "X": "$(Y)", "A": "it's"}) + assert quoted == "\"A='it''s' STAMP='a b' X='$(DOLLAR)(Y)'\"" + + +@pytest.mark.parametrize("name", ["", "A=B", "WITH SPACE", "DASH-ED", "$X"]) +def test_environment_names_must_be_identifiers(name: str): + with pytest.raises(ValueError, match="not a valid environment variable name"): + submit.quote_environment({name: "x"}) + + +@pytest.mark.parametrize("value", ["line\nbreak", "carriage\rreturn"]) +def test_line_breaks_are_refused(value: str): + with pytest.raises(ValueError, match="line break"): + submit.quote_arguments([value]) + with pytest.raises(ValueError, match="line break"): + submit.quote_environment({"X": value}) + + +# -------------------------------------------------------------------------- +# Submit descriptions +# -------------------------------------------------------------------------- + + +def plan(**changes: Any) -> SubmitPlan: + values: dict[str, Any] = { + "executable": "/work/payload.sh", + "transfer_executable": True, + "arguments": ["a"], + "copies": [ + CopyPlan("/work/0", {"STAMP": "s0"}, ["secrets/"]), + CopyPlan("/work/1", {"STAMP": "s1"}), + ], + } + return SubmitPlan(**{**values, **changes}) + + +def lines(text: str) -> list[str]: + return text.splitlines() + + +class TestRender: + def test_one_process_per_copy(self): + assert lines(render(plan()))[-1] == "queue 2" + + def test_per_copy_values_are_indexed_by_proc_id(self): + text = render(plan()) + assert "ic_dir_0 = /work/0" in lines(text) + assert "ic_dir_1 = /work/1" in lines(text) + assert "ic_env_0 = \"STAMP='s0'\"" in lines(text) + assert "ic_in_0 = secrets/" in lines(text) + assert "ic_in_1 = " in lines(text) + assert "initialdir = $(ic_dir_$(ProcId))" in lines(text) + assert "environment = $(ic_env_$(ProcId))" in lines(text) + + def test_inputs_shared_and_per_copy(self): + text = render(plan(inputs=["/work/inputs/", "https://example.org/in.dat"])) + assert ( + "transfer_input_files = /work/inputs/, https://example.org/in.dat, $(ic_in_$(ProcId))" + in lines(text) + ) + + @pytest.mark.parametrize( + ("outputs", "expected"), + [ + ( + [], + 'transfer_output_files = ""', + ), # nothing but stdout, stderr and the log + (["result.txt", "dir/x"], "transfer_output_files = result.txt, dir/x"), + (None, None), # every file the payload creates + ], + ids=["none", "listed", "all"], + ) + def test_outputs(self, outputs: list[str] | None, expected: str | None): + text = render(plan(outputs=outputs)) + found = [ + line for line in lines(text) if line.startswith("transfer_output_files") + ] + assert found == ([expected] if expected else []) + + def test_output_remaps_upload_to_urls(self): + text = render( + plan( + outputs=["a", "b"], + output_remaps={"b": "https://s/b", "a": "https://s/a"}, + ) + ) + assert 'transfer_output_remaps = "a = https://s/a; b = https://s/b"' in lines( + text + ) + + def test_resources_for_a_schedd_and_for_a_ce_router(self): + text = render(plan(cpus=8, memory_mb=4000, wall_time_s=7200, queue="long")) + for line in [ + "request_cpus = 8", + "+xcount = 8", + "request_memory = 4000", + "+maxMemory = 4000", + "+BatchRuntime = 7200", + '+queue = "long"', + ]: + assert line in lines(text) + + def test_finished_jobs_stay_until_purged(self): + # The one lifetime rule interCEde sets: output can be collected + # again until the consumer releases the job. + assert "leave_in_queue = (JobStatus == 4)" in lines(render(plan())) + + @pytest.mark.parametrize( + "command", + [ + "on_exit_hold", + "on_exit_remove", + "periodic_hold", + "periodic_release", + "periodic_remove", + "max_retries", + "requirements", + ], + ) + def test_sets_no_policy_on_the_job(self, command: str): + # Holding, releasing, removing or retrying jobs is the consumer's + # policy, never interCEde's. + assert not any(line.startswith(command) for line in lines(render(plan()))) + + def test_macros_in_paths_are_escaped(self): + assert "ic_dir_0 = /work/$(DOLLAR)0" in lines( + render(plan(copies=[CopyPlan("/work/$0")])) + ) + + @pytest.mark.parametrize("field", ["inputs", "outputs"]) + def test_file_lists_cannot_hold_a_comma(self, field: str): + with pytest.raises(ValueError, match="comma"): + render(plan(**{field: ["a,b"]})) + + def test_paths_cannot_hold_a_line_break(self): + with pytest.raises(ValueError, match="line break"): + render(plan(copies=[CopyPlan("/work/a\nqueue 100")])) + + +# -------------------------------------------------------------------------- +# Commands +# -------------------------------------------------------------------------- + + +class TestCommands: + def test_submit_to_the_local_schedd_spools(self): + assert commands.submit("/w/job.sub") == [ + "condor_submit", + "-terse", + "-spool", + "/w/job.sub", + ] + + @pytest.mark.parametrize( + ("count", "sizes"), + [(100, [100]), (101, [100, 1]), (250, [100, 100, 50])], + ) + def test_chunks(self, count: int, sizes: list[int]): + ids = [status.JobID(f"1.{i}") for i in range(count)] + chunked = commands.chunks(ids) + assert [len(chunk) for chunk in chunked] == sizes + assert [i for chunk in chunked for i in chunk] == ids + + +class TestParseSubmit: + @pytest.mark.parametrize( + ("raw", "ids"), + [ + ("1.0 - 1.1\n", ["1.0", "1.1"]), + (" 42.0 - 42.0 ", ["42.0"]), + ("\n7.3 - 7.5\n\n", ["7.3", "7.4", "7.5"]), + ], + ) + def test_terse_output(self, raw: str, ids: list[str]): + assert commands.parse_submit(raw) == ids + + @pytest.mark.parametrize( + "raw", + [ + "", + "Submitting job(s).\n1 job(s) submitted to cluster 1.", + "1.0 - 2.0", + "1.3 - 1.1", + "1.0 - 1.1\n2.0 - 2.1", + "x", + ], + ids=["empty", "verbose", "two-clusters", "backwards", "two-lines", "garbage"], + ) + def test_anything_else_is_refused(self, raw: str): + with pytest.raises(ValueError, match="unexpected condor_submit output"): + commands.parse_submit(raw) + + +def test_parse_remove(): + raw = "Job 1.0 marked for removal\nJob 1.2 marked for removal\nCouldn't find/remove all jobs matching 1.1\n" + assert commands.parse_remove(raw) == {"1.0", "1.2"} + assert commands.parse_remove("") == set() + + +# -------------------------------------------------------------------------- +# State mapping +# -------------------------------------------------------------------------- + + +def ad(**fields: Any) -> dict[str, Any]: + return {"ClusterId": 3, "ProcId": 1, **fields} + + +class TestJobStatus: + @pytest.mark.parametrize( + ("code", "expected"), + [ + (1, JobStatus.WAITING), + (2, JobStatus.RUNNING), + (4, JobStatus.DONE), + (6, JobStatus.RUNNING), + (7, JobStatus.WAITING), + ], + ids=["idle", "running", "completed", "transferring-output", "suspended"], + ) + def test_plain_states(self, code: int, expected: JobStatus): + assert status.job_status(ad(JobStatus=code)) == expected + + @pytest.mark.parametrize( + "code", + [8, None], + ids=["unexpected", "missing"], + ) + def test_unknown_codes(self, code: Any): + assert status.job_status(ad(JobStatus=code)) == JobStatus.UNKNOWN + + @pytest.mark.parametrize( + ("fields", "expected"), + [ + ({"ExitCode": 0, "ExitBySignal": False}, JobStatus.DONE), + ({"ExitCode": 3, "ExitBySignal": False}, JobStatus.FAILED), + ({"ExitBySignal": True, "ExitSignal": 9}, JobStatus.FAILED), + ({}, JobStatus.DONE), + ], + ids=["exit-0", "exit-3", "signal", "no-exit-info"], + ) + def test_finished_payload_result_comes_from_its_exit( + self, fields: dict[str, Any], expected: JobStatus + ): + # Read from what HTCondor records; no hold is put on the job to tell. + assert status.job_status(ad(JobStatus=4, **fields)) == expected + + def test_spooling_is_waiting(self): + assert ( + status.job_status(ad(JobStatus=5, HoldReasonCode=16)) == JobStatus.WAITING + ) + + @pytest.mark.parametrize( + "fields", + [{"HoldReasonCode": 1}, {"HoldReasonCode": 3, "HoldReasonSubCode": 55}, {}], + ids=["by-user", "by-site-policy", "no-reason"], + ) + def test_any_other_hold_is_aborted(self, fields: dict[str, Any]): + assert status.job_status(ad(JobStatus=5, **fields)) == JobStatus.ABORTED + + @pytest.mark.parametrize( + ("fields", "expected"), + [ + ({"LastJobStatus": 4, "ExitCode": 0}, JobStatus.DONE), + ({"LastJobStatus": 4}, JobStatus.DONE), + ({"LastJobStatus": 4, "ExitCode": 2}, JobStatus.FAILED), + ({"LastJobStatus": 4, "ExitBySignal": True}, JobStatus.FAILED), + ({"LastJobStatus": 5, "ExitCode": 3}, JobStatus.ABORTED), + ({"LastJobStatus": 2}, JobStatus.ABORTED), + ({"LastJobStatus": 1}, JobStatus.ABORTED), + ({}, JobStatus.ABORTED), + ], + ids=[ + "purged-done", + "purged-done-no-code", + "purged-failed", + "purged-signal", + "removed-while-held", + "killed-running", + "killed-idle", + "bare", + ], + ) + def test_removed_jobs_keep_their_result( + self, fields: dict[str, Any], expected: JobStatus + ): + assert status.job_status(ad(JobStatus=3, **fields)) == expected + + +class TestParseAds: + def test_condor_q_prints_nothing_for_no_match(self): + assert status.parse_ads("") == [] + assert status.parse_ads("\n \n") == [] + + def test_condor_history_prints_an_empty_list(self): + assert status.parse_ads("[\n]\n") == [] + + @pytest.mark.parametrize("raw", ["{}", "[1, 2]", '"text"', "not json"]) + def test_anything_else_is_refused(self, raw: str): + with pytest.raises(ValueError): + status.parse_ads(raw) + + def test_every_status_query_asks_for_what_the_mapping_reads(self): + assert { + "ClusterId", + "ProcId", + "JobStatus", + "LastJobStatus", + "ExitCode", + "ExitBySignal", + "HoldReasonCode", + } <= set(status.STATE_ATTRIBUTES) diff --git a/tests/unit/backends/fake/__init__.py b/tests/unit/backends/fake/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_fake_backend.py b/tests/unit/backends/fake/test_fake_backend.py similarity index 100% rename from tests/unit/test_fake_backend.py rename to tests/unit/backends/fake/test_fake_backend.py diff --git a/tests/unit/backends/htcondorce/__init__.py b/tests/unit/backends/htcondorce/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/backends/htcondorce/_fake_condor.py b/tests/unit/backends/htcondorce/_fake_condor.py new file mode 100644 index 0000000..bab99d7 --- /dev/null +++ b/tests/unit/backends/htcondorce/_fake_condor.py @@ -0,0 +1,204 @@ +"""A simulated set of HTCondor tools, and helpers for driving the backend with it. + +``FakeCondor`` answers the way HTCondor 25 does (checked against a live schedd): +``condor_q`` prints nothing for unknown jobs, ``condor_history`` an empty list, +``condor_rm`` exits 1 for jobs it cannot find, and ``condor_transfer_data`` +writes into each job's ``SUBMIT_Iwd``. +""" + +from __future__ import annotations + +import json +import re +import stat +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from intercede import HTCondorCEConfig, JobHandle, JobID, SubmissionSpec +from intercede._backends.batch.protocols import CommandResult +from intercede._backends.monolith.htcondorce import HTCondorCEBackend +from intercede.auth import BearerToken, StaticCredentials + +ENDPOINT = "ce.example.org:9619" +SPEC = SubmissionSpec(executable="/bin/true") +TOKEN = "TOKEN-VALUE" # noqa: S105 (a fake token the tests look for) + + +@dataclass +class Call: + argv: list[str] + env: dict[str, str] + files: dict[str, tuple[int, bytes]] = field( + default_factory=dict + ) # path -> (mode, content) + + +class FakeCondor: + """Plays condor_submit, condor_q, condor_history, condor_rm and condor_transfer_data.""" + + def __init__(self) -> None: + self.calls: list[Call] = [] + self.queue: dict[str, dict[str, Any]] = {} + self.history: dict[str, dict[str, Any]] = {} + self.outputs: dict[str, dict[str, bytes]] = {} # files a job "created" + self.descriptions: list[str] = [] + self.next_cluster = 1 + self.fail: dict[str, CommandResult] = {} # tool -> forced result + + async def __call__( + self, argv: Sequence[str], env: Mapping[str, str], timeout: float + ) -> CommandResult: + call = Call(list(argv), dict(env)) + self.calls.append(call) + self._snapshot(call) + tool, args = argv[0], [a for a in argv[1:] if a != "-debug"] + if tool in self.fail: + return self.fail[tool] + ids = [a for a in args if re.fullmatch(r"\d+\.\d+", a)] + if tool == "condor_submit": + return self._submit(Path(args[-1])) + if tool == "condor_q": + return self._ads(self.queue, ids, args, empty="") + if tool == "condor_history": + return self._ads(self.history, ids, args, empty="[\n]\n") + if tool == "condor_rm": + return self._remove(ids) + if tool == "condor_transfer_data": + return self._transfer(ids) + raise AssertionError(f"unexpected tool {tool}") + + # -- the tools ----------------------------------------------------------- + + def _submit(self, description: Path) -> CommandResult: + text = description.read_text() + self.descriptions.append(text) + count = int(re.search(r"^queue (\d+)$", text, re.M).group(1)) # type: ignore[union-attr] + cluster = self.next_cluster + self.next_cluster += 1 + for proc in range(count): + iwd = re.search(rf"^ic_dir_{proc} = (.*)$", text, re.M).group(1) # type: ignore[union-attr] + out = re.search(r"^output = (.*)$", text, re.M).group(1) # type: ignore[union-attr] + err = re.search(r"^error = (.*)$", text, re.M).group(1) # type: ignore[union-attr] + self.queue[f"{cluster}.{proc}"] = { + "ClusterId": cluster, + "ProcId": proc, + "JobStatus": 1, + "SUBMIT_Iwd": iwd, + "Out": _expand(out, cluster, proc), + "Err": _expand(err, cluster, proc), + "UserLog": f"{iwd}/{cluster}.{proc}.log", + } + return ok(f"{cluster}.0 - {cluster}.{count - 1}\n") + + @staticmethod + def _ads( + store: Mapping[str, dict[str, Any]], ids: list[str], args: list[str], empty: str + ) -> CommandResult: + wanted = args[args.index("-attributes") + 1].split(",") + found = [ + {k: v for k, v in store[i].items() if k in wanted} + for i in ids + if i in store + ] + return ok(json.dumps(found) if found else empty) + + def _remove(self, ids: list[str]) -> CommandResult: + lines, missing = [], False + for i in ids: + if i in self.queue: + ad = self.queue.pop(i) + self.history[i] = { + **ad, + "LastJobStatus": ad["JobStatus"], + "JobStatus": 3, + } + lines.append(f"Job {i} marked for removal") + else: + missing = True + if missing: + return CommandResult( + returncode=1, + stdout="\n".join(lines), + stderr="Couldn't find/remove all jobs\n", + ) + return ok("\n".join(lines)) + + def _transfer(self, ids: list[str]) -> CommandResult: + for i in ids: + ad = self.queue[i] + iwd = Path(ad["SUBMIT_Iwd"]) + iwd.mkdir(parents=True, exist_ok=True) + files = { + name: content + for name, content in [ + (ad.get("Out"), b"stdout of " + i.encode()), + (ad.get("Err"), b""), + (Path(ad["UserLog"]).name if "UserLog" in ad else None, b"log"), + ] + if name + } + for name, content in {**files, **self.outputs.get(i, {})}.items(): + (iwd / name).parent.mkdir(parents=True, exist_ok=True) + (iwd / name).write_bytes(content) + return ok("Fetching data files...\n") + + # -- helpers for the tests -------------------------------------------------- + + def _snapshot(self, call: Call) -> None: + """Record staged and credential files as they exist during the call.""" + for key in ("_CONDOR_SCITOKENS_FILE",): + if key in call.env: + self._record(call, Path(call.env[key])) + if call.argv[0] == "condor_submit": + submission = Path(call.argv[-1]).parent + for path in submission.rglob("*"): + if path.is_file(): + self._record(call, path) + + @staticmethod + def _record(call: Call, path: Path) -> None: + if path.is_file(): + call.files[str(path)] = ( + stat.S_IMODE(path.stat().st_mode), + path.read_bytes(), + ) + + def tools(self) -> list[str]: + return [call.argv[0] for call in self.calls] + + def finish(self, job: JobID | str, code: int = 4, **fields: Any) -> None: + self.queue[job] = {**self.queue[job], "JobStatus": code, **fields} + + +def _expand(name: str, cluster: int, proc: int) -> str: + return name.replace("$(ClusterId)", str(cluster)).replace("$(ProcId)", str(proc)) + + +def ok(stdout: str) -> CommandResult: + return CommandResult(returncode=0, stdout=stdout, stderr="") + + +def settings(**fields: Any) -> HTCondorCEConfig: + return HTCondorCEConfig(**{"kind": "htcondor-ce", "endpoint": ENDPOINT, **fields}) + + +def make( + condor: FakeCondor, + workdir: Path, + credentials: list[Any] | None = None, + **fields: Any, +) -> HTCondorCEBackend: + provider = StaticCredentials( + credentials if credentials is not None else [BearerToken(value=TOKEN)] + ) + return HTCondorCEBackend( + settings(**fields), provider, runner=condor, workdir=workdir + ) + + +def handle(job: str, **changes: str) -> JobHandle: + return JobHandle( + backend="htcondor-ce", resource=ENDPOINT, id=JobID(job) + ).model_copy(update=changes) diff --git a/tests/unit/backends/htcondorce/conftest.py b/tests/unit/backends/htcondorce/conftest.py new file mode 100644 index 0000000..688a77e --- /dev/null +++ b/tests/unit/backends/htcondorce/conftest.py @@ -0,0 +1,25 @@ +"""Fixtures for the HTCondor-CE backend tests.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from ._fake_condor import FakeCondor, make + + +@pytest.fixture +def condor() -> FakeCondor: + return FakeCondor() + + +@pytest.fixture +def workdir(tmp_path: Path) -> Path: + return tmp_path / "work" + + +@pytest.fixture +async def ce(condor: FakeCondor, workdir: Path): + async with make(condor, workdir) as backend: + yield backend diff --git a/tests/unit/backends/htcondorce/test_construction.py b/tests/unit/backends/htcondorce/test_construction.py new file mode 100644 index 0000000..b9dce9f --- /dev/null +++ b/tests/unit/backends/htcondorce/test_construction.py @@ -0,0 +1,75 @@ +"""The HTCondor-CE backend: shape and construction.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from intercede import InterCEdeError, JobHandle, JobID, registry +from intercede._backends.monolith.htcondorce import HTCondorCEBackend +from intercede.auth import BearerToken, StaticCredentials +from intercede.protocols import Diagnosable + +from ._fake_condor import ENDPOINT, SPEC, TOKEN, FakeCondor, make, settings + + +class TestShape: + def test_no_live_diagnostics(self, condor: FakeCondor, workdir: Path): + assert not isinstance(make(condor, workdir), Diagnosable) + + def test_construction_does_no_io(self, condor: FakeCondor, workdir: Path): + make(condor, workdir) + assert not workdir.exists() + assert condor.calls == [] + + def test_built_by_the_registry(self): + built = registry.get_backend( + {"kind": "htcondor-ce", "endpoint": ENDPOINT}, StaticCredentials() + ) + assert isinstance(built, HTCondorCEBackend) + assert built.resource == ENDPOINT + + @pytest.mark.parametrize( + ("endpoint", "pool"), + [ + ("ce.example.org:9619", "ce.example.org:9619"), + ("ce.example.org", "ce.example.org:9619"), + ("ce:1234", "ce:1234"), + ], + ) + async def test_endpoint_becomes_pool_and_schedd_name( + self, condor: FakeCondor, workdir: Path, endpoint: str, pool: str + ): + backend = HTCondorCEBackend( + settings(endpoint=endpoint), + StaticCredentials([BearerToken(value=TOKEN)]), + runner=condor, + workdir=workdir, + ) + async with backend: + await backend.get_status( + [JobHandle(backend="htcondor-ce", resource=endpoint, id=JobID("1.0"))] + ) + argv = condor.calls[0].argv + assert argv[argv.index("-pool") + 1] == pool + assert argv[argv.index("-name") + 1] == pool.split(":")[0] + + async def test_schedd_overrides_the_name_not_the_pool( + self, condor: FakeCondor, workdir: Path + ): + async with make(condor, workdir, schedd="ce01@ce.example.org") as backend: + await backend.get_status( + [JobHandle(backend="htcondor-ce", resource=ENDPOINT, id=JobID("1.0"))] + ) + argv = condor.calls[0].argv + assert argv[argv.index("-pool") + 1] == ENDPOINT + assert argv[argv.index("-name") + 1] == "ce01@ce.example.org" + + async def test_closed_backend_refuses(self, condor: FakeCondor, workdir: Path): + backend = make(condor, workdir) + async with backend: + pass + await backend.__aexit__(None, None, None) # closing twice is harmless + with pytest.raises(InterCEdeError, match="closed"): + await backend.submit(SPEC) diff --git a/tests/unit/backends/htcondorce/test_process.py b/tests/unit/backends/htcondorce/test_process.py new file mode 100644 index 0000000..383428c --- /dev/null +++ b/tests/unit/backends/htcondorce/test_process.py @@ -0,0 +1,184 @@ +"""The HTCondor-CE backend: how every tool runs, how failures map to errors, and the process runner.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from intercede import ( + AuthenticationError, + ConfigurationError, + JobHandle, + JobID, + ResourceUnavailableError, +) +from intercede._backends.batch.protocols import CommandResult +from intercede._backends.monolith.htcondorce import HTCondorCEBackend +from intercede._backends.monolith.htcondorce.process import run_process + +from ._fake_condor import ENDPOINT, SPEC, TOKEN, FakeCondor, make, ok + + +class TestEnvironment: + async def test_every_tool_runs_with_debug_for_error_classification( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + await ce.submit(SPEC) + assert all(call.argv[1] == "-debug" for call in condor.calls) + + async def test_authentication_is_required_and_token_based( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + await ce.submit(SPEC) + env = condor.calls[0].env + assert env["_CONDOR_SEC_CLIENT_AUTHENTICATION"] == "REQUIRED" + assert env["_CONDOR_SEC_CLIENT_AUTHENTICATION_METHODS"] == "SCITOKENS,IDTOKENS" + assert env["_CONDOR_TOOL_DEBUG"] == "D_SECURITY" + + async def test_token_is_a_private_file_only_during_the_call( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + await ce.submit(SPEC) + call = condor.calls[0] + token = call.env["_CONDOR_SCITOKENS_FILE"] + assert call.files[token] == (0o600, TOKEN.encode()) + assert not Path(token).exists() + assert not Path(call.env["_CONDOR_SEC_TOKEN_DIRECTORY"]).exists() + assert not Path(call.env["_CONDOR_LOG"]).exists() + + async def test_no_config_file_unless_the_operator_set_one( + self, ce: HTCondorCEBackend, condor: FakeCondor, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.delenv("CONDOR_CONFIG", raising=False) + await ce.get_status( + [JobHandle(backend="htcondor-ce", resource=ENDPOINT, id=JobID("1.0"))] + ) + assert condor.calls[-1].env["CONDOR_CONFIG"] == "ONLY_ENV" + monkeypatch.setenv("CONDOR_CONFIG", "/etc/condor/site.conf") + await ce.get_status( + [JobHandle(backend="htcondor-ce", resource=ENDPOINT, id=JobID("1.0"))] + ) + assert condor.calls[-1].env["CONDOR_CONFIG"] == "/etc/condor/site.conf" + + async def test_ca_directory_from_x509_cert_dir( + self, ce: HTCondorCEBackend, condor: FakeCondor, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setenv("X509_CERT_DIR", "/etc/grid-security/certificates") + await ce.submit(SPEC) + assert ( + condor.calls[0].env["_CONDOR_AUTH_SSL_CLIENT_CADIR"] + == "/etc/grid-security/certificates" + ) + + +class TestErrors: + @pytest.mark.parametrize( + "stderr", + [ + "10/21/26 13:52:19 AUTHENTICATE:1003:Failed to authenticate with any method\n" + "Error: Couldn't contact the condor_collector", + "PERMISSION DENIED to submituser", + # condor_submit with a rejected token (HTCondor 25): no AUTHENTICATE + # summary, and an error that looks like an unreachable schedd. + "10/26/26 11:37:15 AUTHENTICATE: method 2048 (IDTOKENS) failed.\n" + "10/26/26 11:37:15 SECMAN: required authentication with collector " + "127.0.0.1:9619 failed, so aborting command QUERY_SCHEDD_ADS.\n" + "ERROR: Can't find address of schedd htcondor-ce@backend", + ], + ids=["token-rejected", "permission-denied", "submit-token-rejected"], + ) + async def test_authentication_failure( + self, ce: HTCondorCEBackend, condor: FakeCondor, stderr: str + ): + condor.fail["condor_submit"] = CommandResult( + returncode=1, stdout="", stderr=stderr + ) + with pytest.raises(AuthenticationError): + await ce.submit(SPEC) + + @pytest.mark.parametrize( + "stderr", + [ + "10/21/26 13:52:19 connect errno = 111\nError: Couldn't contact the condor_collector on ce:9619.", + "Can't find address for schedd ce.example.org", + ], + ids=["refused", "no-address"], + ) + async def test_unreachable( + self, ce: HTCondorCEBackend, condor: FakeCondor, stderr: str + ): + condor.fail["condor_q"] = CommandResult(returncode=1, stdout="", stderr=stderr) + with pytest.raises(ResourceUnavailableError, match="could not be reached"): + await ce.get_status( + [JobHandle(backend="htcondor-ce", resource=ENDPOINT, id=JobID("1.0"))] + ) + + async def test_other_failures_name_the_tool_without_debug_lines( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + condor.fail["condor_submit"] = CommandResult( + returncode=1, + stdout="", + stderr="10/21/26 13:52:19 SECMAN: noise\nERROR: on Line 3 of submit file\n", + ) + with pytest.raises( + ResourceUnavailableError, + match="condor_submit failed: ERROR: on Line 3 of submit file$", + ): + await ce.submit(SPEC) + + @pytest.mark.parametrize("raw", ["Submitting job(s).", "1.0 - 1.0\n2.0 - 2.0"]) + async def test_unreadable_submit_output( + self, ce: HTCondorCEBackend, condor: FakeCondor, raw: str + ): + condor.fail["condor_submit"] = ok(raw) + with pytest.raises( + ResourceUnavailableError, match="unexpected condor_submit output" + ): + await ce.submit(SPEC) + + async def test_job_count_mismatch(self, ce: HTCondorCEBackend, condor: FakeCondor): + condor.fail["condor_submit"] = ok("5.0 - 5.0") + with pytest.raises( + ResourceUnavailableError, match="created 1 jobs, expected 2" + ): + await ce.submit(SPEC, 2) + + async def test_unreadable_query_output( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + condor.fail["condor_q"] = ok("not json") + with pytest.raises(ResourceUnavailableError, match="unreadable output"): + await ce.get_status( + [JobHandle(backend="htcondor-ce", resource=ENDPOINT, id=JobID("1.0"))] + ) + + async def test_no_token_from_the_provider(self, condor: FakeCondor, workdir: Path): + async with make(condor, workdir, credentials=[]) as backend: + with pytest.raises(AuthenticationError, match="BearerToken"): + await backend.submit(SPEC) + assert condor.calls == [] + + +class TestRunProcess: + async def test_runs_a_command_with_only_the_given_environment(self): + result = await run_process( + ["/bin/sh", "-c", "echo $ONLY; echo err >&2; exit 3"], + {"ONLY": "this", "PATH": os.environ["PATH"]}, + 10, + ) + assert (result.returncode, result.stdout, result.stderr) == ( + 3, + "this\n", + "err\n", + ) + + async def test_missing_tool_is_a_configuration_error(self): + with pytest.raises(ConfigurationError, match="HTCondor client tools"): + await run_process(["condor_definitely_not_installed"], dict(os.environ), 10) + + async def test_timeout_kills_the_tool(self): + with pytest.raises(ResourceUnavailableError, match="did not finish"): + await run_process(["/bin/sleep", "10"], dict(os.environ), 0.2) diff --git a/tests/unit/backends/htcondorce/test_status.py b/tests/unit/backends/htcondorce/test_status.py new file mode 100644 index 0000000..ae08562 --- /dev/null +++ b/tests/unit/backends/htcondorce/test_status.py @@ -0,0 +1,36 @@ +"""The HTCondor-CE backend: status.""" + +from __future__ import annotations + +import pytest + +from intercede import JobStatus +from intercede._backends.monolith.htcondorce import HTCondorCEBackend + +from ._fake_condor import FakeCondor, handle + + +class TestStatus: + @pytest.mark.parametrize( + "foreign", + [ + {"resource": "other.example.org:9619"}, + {"backend": "arc"}, + {"id": "-constraint true"}, + {"id": "1"}, + {"id": "1.0 1.1"}, + ], + ids=["other-ce", "other-backend", "option-injection", "no-proc", "two-ids"], + ) + async def test_foreign_and_malformed_handles_never_reach_a_command( + self, ce: HTCondorCEBackend, condor: FakeCondor, foreign: dict[str, str] + ): + bad = handle("1.0", **foreign) + assert await ce.get_status([bad]) == {bad: JobStatus.UNKNOWN} + assert condor.calls == [] + + async def test_large_polls_are_chunked( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + await ce.get_status([handle(f"1.{i}") for i in range(250)]) + assert condor.tools() == ["condor_q"] * 3 + ["condor_history"] * 3 diff --git a/tests/unit/backends/htcondorce/test_submit.py b/tests/unit/backends/htcondorce/test_submit.py new file mode 100644 index 0000000..4ce5c37 --- /dev/null +++ b/tests/unit/backends/htcondorce/test_submit.py @@ -0,0 +1,311 @@ +"""The HTCondor-CE backend: submit descriptions, outputs and containers.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from pathlib import Path + +import pytest + +from intercede import ( + ContainerSpec, + CopyVars, + FileRef, + OutputMember, + OutputSpec, + ResourceUnavailableError, + SpecificationRejectedError, + SubmissionSpec, +) +from intercede._backends.batch.protocols import CommandResult +from intercede._backends.monolith.htcondorce import HTCondorCEBackend +from intercede.auth import BearerToken, StaticCredentials + +from ._fake_condor import SPEC, TOKEN, FakeCondor, make, settings + + +class TestSubmit: + async def test_a_secret_named_like_an_input_is_refused_before_any_call( + self, ce: HTCondorCEBackend, condor: FakeCondor, tmp_path: Path + ): + source = tmp_path / "pilot.cfg" + source.write_text("data") + spec = SPEC.model_copy( + update={"inputs": [FileRef(name="pilot.cfg", source=str(source))]} + ) + with pytest.raises(SpecificationRejectedError, match="pilot.cfg"): + await ce.submit(spec, [CopyVars(secrets={"pilot.cfg": b"s"})]) + assert condor.calls == [] + + async def test_zero_copies_submit_nothing( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + assert (await ce.submit(SPEC, 0)).handles == {} + assert condor.calls == [] + + async def test_local_inputs_keep_their_directories( + self, ce: HTCondorCEBackend, condor: FakeCondor, tmp_path: Path + ): + source = tmp_path / "anything.dat" + source.write_text("data") + spec = SPEC.model_copy( + update={"inputs": [FileRef(name="sub/dir/in.txt", source=str(source))]} + ) + await ce.submit(spec) + staged = [ + p for p in condor.calls[0].files if p.endswith("inputs/sub/dir/in.txt") + ] + assert len(staged) == 1 and condor.calls[0].files[staged[0]][1] == b"data" + + async def test_secrets_are_private_and_gone_afterwards( + self, ce: HTCondorCEBackend, condor: FakeCondor, workdir: Path + ): + copies = [ + CopyVars(secrets={"pilot.secret": b"s0"}), + CopyVars(secrets={"pilot.secret": b"s1"}), + ] + await ce.submit(SPEC, copies) + secrets = { + path: entry + for path, entry in condor.calls[0].files.items() + if path.endswith("pilot.secret") + } + assert sorted(entry for entry in secrets.values()) == [ + (0o600, b"s0"), + (0o600, b"s1"), + ] + assert not [p for p in workdir.rglob("*") if p.is_file()] + + async def test_secret_never_in_the_description( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + await ce.submit(SPEC, [CopyVars(secrets={"pilot.secret": b"TOPSECRET"})]) + assert "TOPSECRET" not in condor.descriptions[0] + + async def test_different_variable_names_get_separate_clusters( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + # HTCondor merges each process's environment onto the previous one, so + # a variable of one copy would leak into the next in the same cluster. + copies = [ + CopyVars(environment={"STAMP": "a"}), + CopyVars(environment={"STAMP": "b", "EXTRA": "x"}), + CopyVars(environment={"STAMP": "c"}), + ] + sub = await ce.submit(SPEC, copies) + assert condor.tools().count("condor_submit") == 2 + clusters = {i: h.id.split(".")[0] for i, h in sub.handles.items()} + assert clusters[0] == clusters[2] != clusters[1] + assert "EXTRA" not in condor.descriptions[0] + + async def test_a_later_cluster_failing_keeps_the_submitted_copies( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + copies = [CopyVars(environment={"A": "1"}), CopyVars(environment={"B": "2"})] + submitted = 0 + real = condor.__call__ + + async def second_submit_fails( + argv: Sequence[str], env: Mapping[str, str], timeout: float + ) -> CommandResult: + nonlocal submitted + if argv[0] == "condor_submit": + submitted += 1 + if submitted == 2: + return CommandResult( + returncode=1, stdout="", stderr="ERROR: schedd full" + ) + return await real(argv, env, timeout) + + backend = HTCondorCEBackend( + settings(), + StaticCredentials([BearerToken(value=TOKEN)]), + runner=second_submit_fails, + workdir=ce._workdir, + ) + async with backend: + sub = await backend.submit(SPEC, copies) + assert sorted(sub.handles) == [0] + assert sub.failures == {1: "condor_submit failed: ERROR: schedd full"} + + async def test_nothing_submitted_raises( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + condor.fail["condor_submit"] = CommandResult( + returncode=1, stdout="", stderr="ERROR: schedd full" + ) + with pytest.raises(ResourceUnavailableError, match="schedd full"): + await ce.submit(SPEC, 2) + + async def test_url_inputs_are_left_to_the_resource( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + spec = SPEC.model_copy( + update={ + "inputs": [ + FileRef(name="in.dat", source="https://example.org/data/in.dat?x=1") + ] + } + ) + await ce.submit(spec) + assert "https://example.org/data/in.dat?x=1" in condor.descriptions[0] + + async def test_url_input_under_another_name_is_refused( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + spec = SPEC.model_copy( + update={ + "inputs": [ + FileRef(name="renamed.dat", source="https://example.org/in.dat") + ] + } + ) + with pytest.raises(SpecificationRejectedError, match="another name"): + await ce.submit(spec) + assert "condor_submit" not in condor.tools() + + async def test_missing_local_input_is_refused( + self, ce: HTCondorCEBackend, condor: FakeCondor, tmp_path: Path + ): + spec = SPEC.model_copy( + update={"inputs": [FileRef(name="in", source=str(tmp_path / "missing"))]} + ) + with pytest.raises(SpecificationRejectedError, match="cannot read"): + await ce.submit(spec) + assert "condor_submit" not in condor.tools() + + async def test_command_on_the_worker_is_not_shipped( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + # Not a file on this host, so it is a command on the worker node. + await ce.submit( + SPEC.model_copy(update={"executable": "/opt/site/bin/run-payload"}) + ) + assert "transfer_executable = false" in condor.descriptions[0] + + async def test_resources_and_queue(self, condor: FakeCondor, workdir: Path): + spec = SPEC.model_copy( + update={ + "resources": SPEC.resources.model_copy( + update={"cpus": 4, "memory_mb": 8000, "wall_time_s": 3600} + ) + } + ) + async with make(condor, workdir, queue="default") as backend: + await backend.submit(spec) + text = condor.descriptions[0] + assert all( + line in text + for line in [ + "+xcount = 4", + "+maxMemory = 8000", + "+BatchRuntime = 3600", + '+queue = "default"', + ] + ) + + async def test_spec_queue_wins_over_configured_queue( + self, condor: FakeCondor, workdir: Path + ): + spec = SPEC.model_copy( + update={"resources": SPEC.resources.model_copy(update={"queue": "short"})} + ) + async with make(condor, workdir, queue="default") as backend: + await backend.submit(spec) + assert '+queue = "short"' in condor.descriptions[0] + + +class TestSubmitOutputs: + async def test_kept_and_uploaded_members( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + outputs = OutputSpec( + members=[ + OutputMember(pattern="kept.txt"), + OutputMember(pattern="sent.root", destination="https://se/sent.root"), + ] + ) + await ce.submit(SPEC.model_copy(update={"outputs": outputs})) + text = condor.descriptions[0] + assert "transfer_output_files = kept.txt, sent.root" in text + assert 'transfer_output_remaps = "sent.root = https://se/sent.root"' in text + + async def test_include_unlisted_brings_back_everything( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + outputs = OutputSpec( + members=[OutputMember(pattern="*.root")], include_unlisted=True + ) + await ce.submit(SPEC.model_copy(update={"outputs": outputs})) + assert "transfer_output_files" not in condor.descriptions[0] + + @pytest.mark.parametrize( + "member", + [ + OutputMember(pattern="*.root"), + OutputMember(pattern="out?.txt"), + OutputMember(pattern="[ab].txt"), + ], + ) + async def test_patterns_are_refused_without_include_unlisted( + self, ce: HTCondorCEBackend, member: OutputMember + ): + with pytest.raises(SpecificationRejectedError, match="by name, not by pattern"): + await ce.submit( + SPEC.model_copy(update={"outputs": OutputSpec(members=[member])}) + ) + + async def test_a_pattern_cannot_be_uploaded(self, ce: HTCondorCEBackend): + member = OutputMember(pattern="*.root", destination="https://se/") + with pytest.raises(SpecificationRejectedError, match="by name"): + await ce.submit( + SPEC.model_copy( + update={ + "outputs": OutputSpec(members=[member], include_unlisted=True) + } + ) + ) + + +class TestContainers: + async def test_refused_without_a_launcher( + self, ce: HTCondorCEBackend, condor: FakeCondor + ): + with pytest.raises(SpecificationRejectedError, match="no container_launcher"): + await ce.submit( + SPEC.model_copy( + update={"container": ContainerSpec(image="docker://alpine")} + ) + ) + assert condor.calls == [] + + async def test_wrapped_by_the_configured_launcher( + self, condor: FakeCondor, workdir: Path + ): + spec = SubmissionSpec( + executable="/usr/bin/run", + arguments=["x"], + container=ContainerSpec(image="/cvmfs/img.sif"), + ) + async with make( + condor, workdir, container_launcher=["apptainer", "exec", "{image}"] + ) as backend: + await backend.submit(spec) + text = condor.descriptions[0] + assert "executable = apptainer" in text + assert "transfer_executable = false" in text + assert "arguments = \"'exec' '/cvmfs/img.sif' '/usr/bin/run' 'x'\"" in text + + async def test_a_local_file_cannot_run_inside_an_image( + self, condor: FakeCondor, workdir: Path, tmp_path: Path + ): + script = tmp_path / "s.sh" + script.write_text("") + spec = SubmissionSpec( + executable=str(script), container=ContainerSpec(image="docker://a") + ) + async with make( + condor, workdir, container_launcher=["apptainer", "exec", "{image}"] + ) as backend: + with pytest.raises(SpecificationRejectedError, match="inside the image"): + await backend.submit(spec) diff --git a/tests/unit/backends/htcondorce/test_working_area.py b/tests/unit/backends/htcondorce/test_working_area.py new file mode 100644 index 0000000..824b0fa --- /dev/null +++ b/tests/unit/backends/htcondorce/test_working_area.py @@ -0,0 +1,32 @@ +"""The HTCondor-CE backend: the working area, and keeping nothing between calls.""" + +from __future__ import annotations + +import stat +from pathlib import Path + +import pytest + +from intercede import ConfigurationError +from intercede._backends.monolith.htcondorce import HTCondorCEBackend + +from ._fake_condor import SPEC, FakeCondor, make + + +class TestWorkingArea: + async def test_is_private(self, ce: HTCondorCEBackend, workdir: Path): + await ce.submit(SPEC) + assert stat.S_IMODE(workdir.stat().st_mode) == 0o700 + + async def test_a_link_in_its_place_is_refused( + self, condor: FakeCondor, tmp_path: Path + ): + target = tmp_path / "elsewhere" + target.mkdir() + link = tmp_path / "work" + link.symlink_to(target) + async with make(condor, link) as backend: + with pytest.raises( + ConfigurationError, match="not a directory owned by this user" + ): + await backend.submit(SPEC) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index b243067..e3b6575 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -13,11 +13,12 @@ from intercede import JobBackend from intercede._backends.config import FakeConfig +from intercede.auth import StaticCredentials from intercede.registry import _build # Built through the registry, so the suite also covers the registry path. BACKENDS: dict[str, Callable[[], JobBackend]] = { - "fake": lambda: _build(FakeConfig()), + "fake": lambda: _build(FakeConfig(), StaticCredentials()), } diff --git a/tests/unit/test_auth.py b/tests/unit/test_auth.py new file mode 100644 index 0000000..3977caa --- /dev/null +++ b/tests/unit/test_auth.py @@ -0,0 +1,112 @@ +"""Credential values, requirements and the static provider.""" + +from __future__ import annotations + +from collections.abc import Callable +from datetime import datetime +from typing import Any + +import pytest +from pydantic import ValidationError + +from intercede.auth import ( + BearerToken, + Credential, + CredentialProvider, + CredentialRequirements, + SSHPassword, + SSHPrivateKey, + StaticCredentials, +) +from intercede.exceptions import AuthenticationError + +SECRET = "TOPSECRET" # noqa: S105 (a fake secret the tests look for) + +# One instance of every kind, each holding SECRET in all of its secret fields. +EVERY_KIND: dict[type[Credential], Credential] = { + BearerToken: BearerToken(value=SECRET), + SSHPrivateKey: SSHPrivateKey(pem=SECRET.encode(), passphrase=SECRET), + SSHPassword: SSHPassword(value=SECRET), +} + + +@pytest.mark.parametrize("kind", list(EVERY_KIND), ids=lambda kind: kind.__name__) +def test_a_secret_never_shows(kind: type[Credential]): + credential = EVERY_KIND[kind] + for shown in ( + repr(credential), + str(credential), + credential.model_dump_json(), + repr(StaticCredentials([credential])), + ): + assert SECRET not in shown + + +@pytest.mark.parametrize( + "build", + [ + lambda: BearerToken(value="t", token=SECRET), + lambda: SSHPrivateKey(pem=b"k", passphrase=[SECRET]), + lambda: StaticCredentials([{"value": SECRET}]), + ], + ids=["unknown-field", "wrong-type", "plain-data-in-provider"], +) +def test_a_mistake_never_repeats_the_secret(build: Callable[[], Any]): + with pytest.raises(ValueError) as exc_info: # also pydantic's ValidationError + build() + assert SECRET not in str(exc_info.value) + + +def test_expiry_must_have_a_timezone(): + # A naive time could not be compared with the current time in UTC. + with pytest.raises(ValidationError, match="timezone"): + BearerToken(value="t", expires_at=datetime(2030, 1, 1)) # noqa: DTZ001 + + +class TestCredentialRequirements: + def test_names_one_kind(self): + requirements = CredentialRequirements(resource="r", kind=BearerToken) + assert requirements.kind is BearerToken + + def test_needs_a_kind(self): + with pytest.raises(ValidationError, match="kind"): + CredentialRequirements(resource="r") # type: ignore[call-arg] + + @pytest.mark.parametrize("kind", [Credential, str, "BearerToken"]) + def test_the_kind_is_a_concrete_credential_class(self, kind: Any): + with pytest.raises(ValidationError): + CredentialRequirements(resource="r", kind=kind) + + +class TestStaticCredentials: + def test_is_a_provider(self): + assert isinstance(StaticCredentials(), CredentialProvider) + + async def test_hands_out_only_the_requested_kind(self): + token, password = BearerToken(value="t"), SSHPassword(value="pw") + provider = StaticCredentials([token, password]) + requirements = CredentialRequirements(resource="ce:9619", kind=BearerToken) + async with provider: + assert await provider.get(requirements) is token + + async def test_a_kind_it_does_not_hold_is_named(self): + # A token and a password both have a single "value" field: it goes by + # kind, not by shape. + provider = StaticCredentials([SSHPassword(value="pw")]) + requirements = CredentialRequirements(resource="ce:9619", kind=BearerToken) + with pytest.raises(AuthenticationError, match="no BearerToken for ce:9619"): + await provider.get(requirements) + + @pytest.mark.parametrize( + "credentials", + [ + [BearerToken(value="a"), BearerToken(value="b")], + [{"value": "x"}], + ["token"], + [Credential()], + ], + ids=["two-of-a-kind", "plain-data", "a-string", "the-base-class"], + ) + def test_refuses_bad_input_at_construction(self, credentials: Any): + with pytest.raises(ValueError): + StaticCredentials(credentials) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 2856b53..a89b203 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -64,7 +64,14 @@ def test_defaults_are_filled_in(): assert (ssh.port, ssh.auth, ssh.connect_timeout_s) == (22, "key", 30) assert ssh.transfer_timeout_s == 3600 ce = validate_config(CE) - assert isinstance(ce, HTCondorCEConfig) and ce.auth == {"token"} + assert isinstance(ce, HTCondorCEConfig) and ce.auth == "token" + arc = validate_config(ARC) + assert isinstance(arc, ARCConfig) and arc.auth == "token" + + +def test_an_htcondor_ce_can_name_its_schedd(): + ce = validate_config({**CE, "schedd": "ce01@ce.example.org"}) + assert isinstance(ce, HTCondorCEConfig) and ce.schedd == "ce01@ce.example.org" def test_a_model_passes_through_unchanged(): @@ -127,9 +134,10 @@ def test_every_missing_field_is_named_at_once(self): @pytest.mark.parametrize( ("data", "message"), [ - ({**ARC, "auth": []}, "auth must name at least one"), - ({**CE, "auth": ["proxy"]}, "must include 'token'"), - ({**ARC, "auth": ["key"]}, "auth"), + ({**ARC, "auth": "proxy"}, "auth: Input should be 'token'"), + ({**CE, "auth": "proxy"}, "auth: Input should be 'token'"), + ({**CE, "auth": ["token", "proxy"]}, "auth: Input should be 'token'"), + ({**ARC, "auth": "key"}, "auth: Input should be 'token'"), ({**SSH, "auth": "token"}, "auth"), ( {**SSH, "known_hosts": "\n\t "}, @@ -139,14 +147,19 @@ def test_every_missing_field_is_named_at_once(self): {**LOCAL, "container_launcher": ["apptainer", "exec"]}, "'{image}' placeholder", ), + ({**CE, "endpoint": "https://ce.example.org"}, "endpoint must be 'host'"), + ({**CE, "schedd": "-name evil"}, "schedd must be 'host' or 'name@host'"), ({**CLOUD, "driver_options": {"OS_PASSWORD": "x"}}, "credential provider"), ({**LOCAL, "max_output_files": 0}, "max_output_files"), ], ids=[ - "arc-no-auth", - "htcondor-ce-no-token", + "arc-no-proxy", + "htcondor-ce-no-proxy", + "htcondor-ce-one-credential", "ce-ssh-auth", "ssh-ce-auth", + "ce-endpoint-url", + "ce-schedd-option", "no-host-keys", "launcher-no-image", "secret-driver-option", @@ -168,6 +181,9 @@ def test_an_unknown_field(self): def test_a_wrong_value(self): assert "toto4" not in rejected(**SSH, port="toto4") + def test_a_value_that_breaks_a_rule(self): + assert "toto4" not in rejected(**{**CE, "endpoint": "https://toto4"}) + def test_building_a_model_directly(self): with pytest.raises(ValueError) as exc_info: BatchSSHConfig(**SSH, password="toto4") # type: ignore[call-arg] # noqa: S106 diff --git a/tests/unit/test_conformance.py b/tests/unit/test_conformance.py index 5d6f51e..8a8a2f7 100644 --- a/tests/unit/test_conformance.py +++ b/tests/unit/test_conformance.py @@ -138,3 +138,12 @@ async def test_a_secret_named_like_an_input_is_refused( clashing = [CopyVars(), CopyVars(secrets={"pilot.cfg": b"s"})] with pytest.raises(SpecificationRejectedError, match="pilot.cfg"): await backend.submit(spec, clashing) + + +async def test_a_missing_local_input_is_refused(backend: JobBackend, tmp_path: Path): + spec = SubmissionSpec( + executable="/bin/true", + inputs=[FileRef(name="in", source=str(tmp_path / "missing"))], + ) + with pytest.raises(SpecificationRejectedError, match="cannot read"): + await backend.submit(spec) diff --git a/tests/unit/test_credentials.py b/tests/unit/test_credentials.py new file mode 100644 index 0000000..ab45d13 --- /dev/null +++ b/tests/unit/test_credentials.py @@ -0,0 +1,196 @@ +"""When a backend asks its provider again, and what it accepts back.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from types import TracebackType +from typing import Any, Self + +import pytest + +from intercede import AuthenticationError, InterCEdeError, validate_config +from intercede._backends.credentials import ( + DEFAULT_MARGIN, + credential_requirements, + is_stale, + refresh_if_stale, +) +from intercede.auth import ( + BearerToken, + Credential, + CredentialRequirements, + SSHPassword, + SSHPrivateKey, +) + +NOW = datetime(2030, 1, 1, 12, 0, tzinfo=UTC) +TOKEN_ONLY = CredentialRequirements(resource="ce:9619", kind=BearerToken) + + +def token(expires_in: timedelta | None = None) -> BearerToken: + return BearerToken( + value="t", expires_at=None if expires_in is None else NOW + expires_in + ) + + +class Recording: + """A provider that returns whatever the test gives it, and counts calls.""" + + def __init__(self, result: Any = None, error: BaseException | None = None) -> None: + self.result = result + self.error = error + self.asked: list[CredentialRequirements] = [] + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: ... + + async def get(self, requirements: CredentialRequirements) -> Any: + self.asked.append(requirements) + if self.error is not None: + raise self.error + return self.result + + +class TestIsStale: + @pytest.mark.parametrize( + ("credential", "stale"), + [ + (None, True), # nothing asked for yet + (token(), False), # never expires + (token(DEFAULT_MARGIN + timedelta(seconds=1)), False), + (token(DEFAULT_MARGIN), True), # inside the margin + (token(-timedelta(hours=1)), True), # expired + (SSHPassword(value="p"), True), # not what is required + ], + ids=[ + "none", + "never-expires", + "outside-margin", + "at-margin", + "expired", + "another-kind", + ], + ) + def test_one_credential(self, credential: Credential | None, stale: bool): + assert is_stale(credential, TOKEN_ONLY, now=NOW) is stale + + +class TestRefreshIfStale: + async def test_fresh_credential_is_kept_without_asking(self): + current = token(timedelta(hours=1)) + provider = Recording() + assert await refresh_if_stale(current, TOKEN_ONLY, provider, now=NOW) is current + assert provider.asked == [] + + async def test_stale_credential_is_replaced(self): + fresh = token(timedelta(hours=1)) + provider = Recording(fresh) + current = token(timedelta(minutes=1)) + assert await refresh_if_stale(current, TOKEN_ONLY, provider, now=NOW) is fresh + assert provider.asked == [TOKEN_ONLY] + + async def test_short_lived_credentials_are_accepted(self): + # Inside the margin but not expired: usable now, asked again next time. + fresh = token(timedelta(minutes=1)) + assert ( + await refresh_if_stale(None, TOKEN_ONLY, Recording(fresh), now=NOW) is fresh + ) + + +class TestProviderFailures: + """Every failure is a whole-operation AuthenticationError.""" + + async def test_provider_raising_is_an_authentication_error(self): + provider = Recording(error=RuntimeError("no token for s3cret-url")) + with pytest.raises(AuthenticationError) as exc_info: + await refresh_if_stale(None, TOKEN_ONLY, provider, now=NOW) + assert isinstance(exc_info.value.__cause__, RuntimeError) + message = str(exc_info.value) + assert "ce:9619" in message and "RuntimeError" in message + assert "s3cret" not in message # the provider's text may hold a secret + + async def test_our_own_errors_pass_through_unchanged(self): + error = InterCEdeError("x") + with pytest.raises(InterCEdeError) as exc_info: + await refresh_if_stale(None, TOKEN_ONLY, Recording(error=error), now=NOW) + assert exc_info.value is error + + @pytest.mark.parametrize( + ("result", "returned"), + [ + (None, "NoneType"), + ([token()], "list"), + (SSHPassword(value="p"), "SSHPassword"), + ], + ids=["nothing", "several", "another-kind"], + ) + async def test_anything_but_the_required_kind(self, result: Any, returned: str): + with pytest.raises( + AuthenticationError, match=f"returned a {returned} .*not a BearerToken" + ): + await refresh_if_stale(None, TOKEN_ONLY, Recording(result), now=NOW) + + async def test_an_expired_credential(self): + provider = Recording(token(-timedelta(minutes=1))) + with pytest.raises(AuthenticationError, match="expired"): + await refresh_if_stale(None, TOKEN_ONLY, provider, now=NOW) + + +# -------------------------------------------------------------------------- +# From a configuration to what to ask the provider for +# -------------------------------------------------------------------------- + +ARC: dict[str, Any] = {"kind": "arc", "endpoint": "https://arc.example.org:443"} +CE: dict[str, Any] = {"kind": "htcondor-ce", "endpoint": "ce.example.org:9619"} +SSH: dict[str, Any] = { + "kind": "batch", + "transport": "ssh", + "scheduler": "slurm", + "host": "batch.example.org", + "user": "dirac", + "known_hosts": "batch.example.org ssh-ed25519 AAAAC3Nz...", +} + + +class TestCredentialRequirements: + @pytest.mark.parametrize("base", [ARC, CE], ids=["arc", "htcondor-ce"]) + @pytest.mark.parametrize("auth", [{}, {"auth": "token"}], ids=["default", "named"]) + def test_a_ce_asks_for_a_token_for_its_endpoint( + self, base: dict[str, Any], auth: dict[str, Any] + ): + scopes = frozenset({"compute.create"}) + requirements = credential_requirements( + validate_config({**base, **auth}), scopes + ) + assert requirements is not None + assert requirements.kind is BearerToken + assert requirements.resource == base["endpoint"] + assert requirements.scopes == scopes + + @pytest.mark.parametrize( + ("auth", "kind"), [("key", SSHPrivateKey), ("password", SSHPassword)] + ) + def test_ssh_asks_for_the_login(self, auth: str, kind: type): + config = validate_config({**SSH, "auth": auth, "port": 2222}) + requirements = credential_requirements(config) + assert requirements is not None + assert requirements.kind is kind + assert requirements.resource == "dirac@batch.example.org:2222" + + @pytest.mark.parametrize( + "data", + [ + {**SSH, "auth": "agent"}, + {"kind": "batch", "transport": "local", "scheduler": "slurm"}, + ], + ids=["ssh-agent", "local"], + ) + def test_nothing_to_ask_for(self, data: dict[str, Any]): + assert credential_requirements(validate_config(data)) is None diff --git a/tests/unit/test_registry.py b/tests/unit/test_registry.py index eebab72..458d674 100644 --- a/tests/unit/test_registry.py +++ b/tests/unit/test_registry.py @@ -18,9 +18,11 @@ registry, ) from intercede._backends.config import FakeConfig +from intercede.auth import BearerToken, Credential, StaticCredentials from intercede.registry import _build, _load DUMMIES = "tests.unit._registry_dummies" +CREDENTIALS = StaticCredentials() CLOUD: dict[str, Any] = { "kind": "cloud", @@ -63,7 +65,7 @@ def composed(monkeypatch: pytest.MonkeyPatch) -> None: class TestBuilds: async def test_the_fake_for_the_test_suites(self): - async with _build(FakeConfig(resource="fake://test")) as backend: + async with _build(FakeConfig(resource="fake://test"), CREDENTIALS) as backend: assert isinstance(backend, JobBackend) assert backend.resource == "fake://test" @@ -72,29 +74,59 @@ async def test_the_fake_for_the_test_suites(self): [CLOUD, CloudConfig(**CLOUD)], ids=["mapping", "object"], ) - def test_a_single_class_backend_gets_its_settings( + def test_a_single_class_backend_gets_its_settings_and_provider( self, monkeypatch: pytest.MonkeyPatch, config: Any ): monkeypatch.setitem(registry._BACKENDS, "cloud", f"{DUMMIES}:DummyBackend") - built: Any = registry.get_backend(config) + provider = StaticCredentials() + built: Any = registry.get_backend(config, provider) assert type(built).__name__ == "DummyBackend" assert isinstance(built.settings, CloudConfig) + assert built.credentials is provider def test_a_batch_backend_is_composed_of_its_parts(self, composed: None): - built: Any = registry.get_backend({**SSH_SLURM, "queue": "short"}) + provider = StaticCredentials() + built: Any = registry.get_backend({**SSH_SLURM, "queue": "short"}, provider) assert type(built).__name__ == "DummyBatchBackend" - # Transport and scheduler each get the whole batch configuration. + # Transport and scheduler each get the whole batch configuration; the + # transport, which authenticates, also gets the provider. assert isinstance(built.transport.settings, BatchSSHConfig) assert built.transport.settings.host == "batch.example.org" + assert built.transport.credentials is provider assert built.scheduler.settings.queue == "short" + async def test_building_asks_the_provider_nothing( + self, composed: None, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setitem(registry._BACKENDS, "cloud", f"{DUMMIES}:DummyBackend") + + class Watching(StaticCredentials): + asked = 0 + + async def get(self, requirements: Any) -> Credential: + Watching.asked += 1 + return await super().get(requirements) + + registry.get_backend(SSH_SLURM, Watching()) + registry.get_backend(CLOUD, Watching()) + assert Watching.asked == 0 # construction does no I/O + class TestRefused: def test_invalid_configuration_keeps_the_details(self): with pytest.raises(ConfigurationError) as exc_info: - registry.get_backend({"kind": "arc"}) + registry.get_backend({"kind": "arc"}, CREDENTIALS) assert "endpoint: required for kind='arc'" in str(exc_info.value) + @pytest.mark.parametrize( + "credentials", + [None, BearerToken(value="t")], + ids=["none", "credential-not-provider"], + ) + def test_credentials_must_be_a_provider(self, composed: None, credentials: Any): + with pytest.raises(ConfigurationError, match="must be a CredentialProvider"): + registry.get_backend(LOCAL_SLURM, credentials) + @pytest.mark.parametrize( "config", [{"kind": "arc", "endpoint": "https://arc.example.org:443"}, CLOUD], @@ -104,18 +136,18 @@ def test_valid_but_not_shipped_yet(self, config: dict[str, Any]): with pytest.raises( RegistryError, match=f"backend '{config['kind']}' is not available" ): - registry.get_backend(config) + registry.get_backend(config, CREDENTIALS) def test_composed_part_not_shipped_yet(self): with pytest.raises(RegistryError, match="transport 'ssh' is not available"): - registry.get_backend(SSH_SLURM) + registry.get_backend(SSH_SLURM, CREDENTIALS) def test_an_entry_that_cannot_be_imported( self, composed: None, monkeypatch: pytest.MonkeyPatch ): monkeypatch.setitem(registry._TRANSPORTS, "ssh", "tests.unit.does_not_exist:X") with pytest.raises(RegistryError, match="cannot be imported") as exc_info: - registry.get_backend(SSH_SLURM) + registry.get_backend(SSH_SLURM, CREDENTIALS) assert isinstance(exc_info.value.__cause__, ImportError) @pytest.mark.parametrize( @@ -138,12 +170,16 @@ def test_what_breaks_its_protocol_is_refused( getattr(registry, table), name, f"{DUMMIES}:BuildsTheWrongThing" ) with pytest.raises(RegistryError, match=f"which is not a {protocol}"): - registry.get_backend(LOCAL_SLURM) + registry.get_backend(LOCAL_SLURM, CREDENTIALS) class TestAvailable: def test_shipped_today(self): - assert registry.available() == {"backend": (), "transport": (), "scheduler": ()} + assert registry.available() == { + "backend": ("htcondor-ce",), + "transport": (), + "scheduler": (), + } def test_lists_only_what_a_configuration_can_ask_for( self, composed: None, monkeypatch: pytest.MonkeyPatch @@ -170,5 +206,5 @@ def test_only_the_requested_entry_is_imported( monkeypatch.delitem(sys.modules, DUMMIES, raising=False) registry.available() assert DUMMIES not in sys.modules # listing imports nothing - registry.get_backend(LOCAL_SLURM) + registry.get_backend(LOCAL_SLURM, CREDENTIALS) assert DUMMIES in sys.modules