From 6a47c745207d5d9d61e7411e0aa3fb56b11e5117 Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:09:15 +0800 Subject: [PATCH 1/7] fix(server): pin scipy in ESM image, resolve system binaries via shutil.which - ESM image: pin scipy==1.12.0 (esm_if1 inverse-folding import chain) and extend the build-time smoke import to cover it - Resolve sacct/scancel/docker executables via shutil.which() so cancellation/reconnect fail cleanly when the binaries are absent - Rename email wrapper parameter html -> html_body; lint suppressions - Regenerate UI typing contract (drop unused QtCore import) Co-Authored-By: Claude --- .gitignore | 3 + CHANGELOG.md | 59 ++++++++++--------- dev/tools/generate_ui_typing.py | 2 +- server/docker/runners/esm/Dockerfile | 7 ++- server/docker/runners/esm/esm1v_score.py | 6 +- server/docker/runners/esm/esm_if1_design.py | 1 - server/docker/runners/esm/msa1b_score.py | 4 +- server/revocompute/auth.py | 20 +++---- .../revocompute/job/runners/slurm_runner.py | 8 ++- server/revocompute/manage_db.py | 14 +++-- server/revocompute/resource_audit.py | 4 +- server/revocompute/routes.py | 33 +++++++---- server/revocompute/task_runtime.py | 11 ++-- server/revocompute/task_types/__init__.py | 5 +- server/tests/test_runner_script_static.py | 3 +- server/tools/audit_runtime_sizes.py | 6 +- src/REvoDesign/UI/types.py | 2 +- 17 files changed, 113 insertions(+), 75 deletions(-) diff --git a/.gitignore b/.gitignore index ccd0594f5..9f33c09ae 100644 --- a/.gitignore +++ b/.gitignore @@ -136,6 +136,7 @@ cluster_test.zip /site docs_old/**/* docs_old/ +docs/dev-guide/server-plugin-research.md test_sc/ src/REvoDesign/UI/Ui_REvoDesign.py # loopkit — keep installable scaffolding, ignore runtime artifacts @@ -153,3 +154,5 @@ playground/config 4MB8_GREMLIN_mtx_zscore.png /mutagenese /temperal_pdb +# security audit working doc (internal, not a deliverable) +/server/security-audit-tracking.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 75af90b40..ab6fb98aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Runner build-failure tolerance**: a failed Docker/SIF runner build warns, drops the runner from `ENABLED_TASKRUNNERS`, and lets the restart continue instead of aborting. +- **Multi-task server architecture**: task-type-agnostic compute server with a + YAML-based registry. Portable task schemas select one of nine shared runtime + families, while one machine-local runner YAML per family supplies mounts, + environment, timeout, and deployment defaults. Missing registry files fail + closed; `gremlin` is always enabled and additional tasks are gated by + `ENABLED_TASKRUNNERS`. +- **Server-driven dynamic form workflow**: the create-task page fetches form + schema from `GET /compute/api/types/` and dynamically builds the file + input (accept extension, label), sequence editor visibility, and params form + (number/text inputs from `TaskParam` definitions). Adding a task type with + new params requires zero frontend changes. +- **`TaskSubmissionRequest` pydantic model**: flat form data + (`params[key]=value`) is parsed into a nested dict, validated against the + task type registry, and forwarded to Celery. Unknown params or task types + are rejected at the API boundary. +- **`GET /compute/api/types` and `GET /compute/api/types/`**: public + endpoints listing all enabled task types with full param schemas. +- **Runner config directory deployment**: `CONFIG_DIR` env var points to the + active `task_types.yaml` and `runners/` directory. Production can mount an + external machine-owned configuration read-only instead of baking host paths + into the server image. +- **Structured issue reporting**: added GitHub Issue Forms for bugs, + installation and environment problems, feature requests, and documentation + problems, with private routing for security vulnerabilities. ### Changed - **ESMFold v1 removed**: the `esmfold_3B_v1` checkpoint is built against @@ -47,8 +71,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Accepted tasks snapshot their effective policy; Docker and SLURM consume the same values, invalid settings fail closed, allowed partitions are enforced, and CPU tasks cannot accidentally inherit GPU GRES. - -### Changed - **Create-task scientific workflow**: replaced page-specific form assembly with capability composition, explicit primary/auxiliary file roles, nested folder selection, local structure summaries and residue selection, grouped @@ -58,33 +80,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 SLURM CPU/memory controls with canonical per-task overrides and visible effective values. Legacy database fields remain migration fallbacks, empty overrides restore inheritance, and multi-field updates are transactional. -### Added -- **Multi-task server architecture**: task-type-agnostic compute server with a - YAML-based registry. Portable task schemas select one of nine shared runtime - families, while one machine-local runner YAML per family supplies mounts, - environment, timeout, and deployment defaults. Missing registry files fail - closed; `gremlin` is always enabled and additional tasks are gated by - `ENABLED_TASKRUNNERS`. -- **Server-driven dynamic form workflow**: the create-task page fetches form - schema from `GET /compute/api/types/` and dynamically builds the file - input (accept extension, label), sequence editor visibility, and params form - (number/text inputs from `TaskParam` definitions). Adding a task type with - new params requires zero frontend changes. -- **`TaskSubmissionRequest` pydantic model**: flat form data - (`params[key]=value`) is parsed into a nested dict, validated against the - task type registry, and forwarded to Celery. Unknown params or task types - are rejected at the API boundary. -- **`GET /compute/api/types` and `GET /compute/api/types/`**: public - endpoints listing all enabled task types with full param schemas. -- **Runner config directory deployment**: `CONFIG_DIR` env var points to the - active `task_types.yaml` and `runners/` directory. Production can mount an - external machine-owned configuration read-only instead of baking host paths - into the server image. -- **Structured issue reporting**: added GitHub Issue Forms for bugs, - installation and environment problems, feature requests, and documentation - problems, with private routing for security vulnerabilities. - -### Changed - **Server deployment and adapter documentation**: reconciled the server README and developer guides with the global executor/runtime model, runtime-family sharing, immutable multi-file workspaces, manifest-first @@ -189,6 +184,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 be downloaded individually. ### Fixed +- **ESM runner missing `scipy`**: the ESM image did not pin scipy, so + `esm_if1_design.py` crashed at import + (`esm2.inverse_folding.gvp_transformer` → `scipy.spatial.transform`, + `ModuleNotFoundError`) on the SLURM path. Pinned `scipy==1.12.0` + (matching the `prime` image) and extended the build-time smoke import to + cover the inverse-folding chain. - **SLURM execution diagnostics**: scheduler stdout/stderr are now stored under explicit `execution/slurm---.stdout.log` and `.stderr.log` paths. They are diff --git a/dev/tools/generate_ui_typing.py b/dev/tools/generate_ui_typing.py index ffb424e11..ac5939ac8 100644 --- a/dev/tools/generate_ui_typing.py +++ b/dev/tools/generate_ui_typing.py @@ -151,7 +151,7 @@ def render_types(bindings: list[UiBinding], ui_path: Path = UI_PATH) -> str: "", "from typing import Protocol", "", - "from REvoDesign.Qt import QtCore, QtGui, QtWidgets", + "from REvoDesign.Qt import QtGui, QtWidgets", "", "", "class REvoDesignUiProtocol(Protocol):", diff --git a/server/docker/runners/esm/Dockerfile b/server/docker/runners/esm/Dockerfile index 63c27a68a..37e4b18ec 100644 --- a/server/docker/runners/esm/Dockerfile +++ b/server/docker/runners/esm/Dockerfile @@ -24,15 +24,20 @@ RUN pip install --no-cache-dir torch==2.2.0+cu121 \ "numpy<2" \ "pandas==2.2.3" \ "pytorch-lightning==1.9.5" \ + "scipy==1.12.0" \ "torchmetrics==0.11.4" +# ESM-IF1 (esm2.inverse_folding) imports scipy.spatial.transform; the fork's +# setup.py declares scipy, but the image pins dependencies explicitly rather +# than trusting transitive resolution. The smoke import covers the full +# inverse-folding import chain so a dependency gap fails at image build. ARG ESM_REPO=https://github.com/YaoYinYing/esm2.git ARG ESM_REF=efcdb2265b180238a30b99ba19cced447eba6b76 RUN git init /opt/esm2 && git -C /opt/esm2 remote add origin ${ESM_REPO} && \ git -C /opt/esm2 fetch --depth 1 origin ${ESM_REF} && \ git -C /opt/esm2 checkout --detach FETCH_HEAD && \ pip install --no-cache-dir -e /opt/esm2 && \ - python -c "import esm2, pandas" && \ + python -c "import esm2, esm2.inverse_folding, pandas" && \ rm -rf /opt/esm2/.git FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04 diff --git a/server/docker/runners/esm/esm1v_score.py b/server/docker/runners/esm/esm1v_score.py index f5d92c219..611322952 100644 --- a/server/docker/runners/esm/esm1v_score.py +++ b/server/docker/runners/esm/esm1v_score.py @@ -2,7 +2,6 @@ # Distributed under the terms of the GNU General Public License v3.0. # SPDX-License-Identifier: GPL-3.0-only -#!/usr/bin/env python3 # REvoDesign ESM-1v runner — zero-shot variant effect prediction via esm2. # # Adapted from RosettaWorkshop/2._Working/1._MutationEffects/ESM-1v @@ -22,7 +21,7 @@ import pandas as pd import torch -from esm2 import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained +from esm2 import Alphabet, pretrained from esm2.data import read_fasta logger = logging.getLogger() @@ -48,7 +47,8 @@ def label_mutation(mutation: str, sequence: str, token_probs: torch.Tensor, alph """ wt, mt = mutation[0], mutation[-1] pos = int(mutation[1:-1]) - 1 # label positions are 1-based - assert sequence[pos] == wt, f"Wild-type mismatch at position {pos + 1}: {mutation}" + if sequence[pos] != wt: + raise ValueError(f"Wild-type mismatch at position {pos + 1}: {mutation}") wt_encoded, mt_encoded = alphabet.get_idx(wt), alphabet.get_idx(mt) # +1 skips the BOS token return (token_probs[0, 1 + pos, mt_encoded] - token_probs[0, 1 + pos, wt_encoded]).item() diff --git a/server/docker/runners/esm/esm_if1_design.py b/server/docker/runners/esm/esm_if1_design.py index 7631041dd..cc16a54b2 100644 --- a/server/docker/runners/esm/esm_if1_design.py +++ b/server/docker/runners/esm/esm_if1_design.py @@ -2,7 +2,6 @@ # Distributed under the terms of the GNU General Public License v3.0. # SPDX-License-Identifier: GPL-3.0-only -#!/usr/bin/env python3 # REvoDesign ESM-IF1 runner — inverse folding (sequence design from backbone). # # Adapted from esm2/examples/inverse_folding/sample_sequences.py. Samples diff --git a/server/docker/runners/esm/msa1b_score.py b/server/docker/runners/esm/msa1b_score.py index 35919dd8a..d173a0b11 100644 --- a/server/docker/runners/esm/msa1b_score.py +++ b/server/docker/runners/esm/msa1b_score.py @@ -11,7 +11,6 @@ import argparse import csv import itertools -import math import string import torch @@ -38,7 +37,8 @@ def parse_args() -> argparse.Namespace: def read_a3m(path: str, nseq: int) -> list[str]: rows = [] - with open(path, encoding="utf-8") as handle: + # PTC-W6004: sandboxed runner; path is the mounted read-only input snapshot + with open(path, encoding="utf-8") as handle: # skipcq: PTC-W6004 for record in itertools.islice(_fasta_blocks(handle), nseq): rows.append(remove_insertions(record[1])) return rows diff --git a/server/revocompute/auth.py b/server/revocompute/auth.py index f82c63643..41dcff0dc 100644 --- a/server/revocompute/auth.py +++ b/server/revocompute/auth.py @@ -546,7 +546,7 @@ def _resend_from() -> str: return f"{name} <{addr}>" -def _send_email(*, to: str, subject: str, text: str, html: str | None = None) -> bool: +def _send_email(*, to: str, subject: str, text: str, html_body: str | None = None) -> bool: """Send an email. Uses Resend if available+configured, else SMTP. Returns ``True`` on success, ``False`` on failure (logged). @@ -560,8 +560,8 @@ def _send_email(*, to: str, subject: str, text: str, html: str | None = None) -> "subject": subject, "text": text, } - if html: - params["html"] = html + if html_body: + params["html"] = html_body _resend_module.Emails.send(params) # type: ignore[union-attr] return True except Exception: @@ -574,8 +574,8 @@ def _send_email(*, to: str, subject: str, text: str, html: str | None = None) -> msg["To"] = to msg["Subject"] = subject msg.attach(MIMEText(text, "plain")) - if html: - msg.attach(MIMEText(html, "html")) + if html_body: + msg.attach(MIMEText(html_body, "html")) try: if cfg["use_tls"]: @@ -717,7 +717,7 @@ def send_verification_email(user: dict[str, Any]) -> bool: to=user["email"], subject="Verify your email — REvoCompute", text=text, - html=_email_html(html_body), + html_body=_email_html(html_body), ) @@ -789,7 +789,7 @@ def send_password_reset_email(email: str, db: UserDatabase) -> bool: to=email, subject="Reset your password — REvoCompute", text=text, - html=_email_html(html_body), + html_body=_email_html(html_body), ) @@ -819,7 +819,7 @@ def send_approval_email(user: dict[str, Any]) -> bool: to=user["email"], subject="Registration approved — REvoCompute", text=text, - html=_email_html(html_body), + html_body=_email_html(html_body), ) @@ -844,7 +844,7 @@ def send_rejection_email(user: dict[str, Any]) -> bool: to=user["email"], subject="Registration update — REvoCompute", text=text, - html=_email_html(html_body), + html_body=_email_html(html_body), ) @@ -924,7 +924,7 @@ def send_admin_digest() -> bool: html_content = _email_html(html_body) for email in recipients: try: - if _send_email(to=email, subject=subject, text=text, html=html_content): + if _send_email(to=email, subject=subject, text=text, html_body=html_content): any_sent = True except Exception: logging.exception("Failed to send admin digest to %s", email) diff --git a/server/revocompute/job/runners/slurm_runner.py b/server/revocompute/job/runners/slurm_runner.py index 411c02e36..7005c62c8 100644 --- a/server/revocompute/job/runners/slurm_runner.py +++ b/server/revocompute/job/runners/slurm_runner.py @@ -16,6 +16,7 @@ import logging import os import re +import shutil import subprocess import threading from typing import Any @@ -67,11 +68,16 @@ def reconnect(self, slurm_job_id: str) -> bool: We cannot re-attach the srun subprocess, but we can query sacct.""" self._slurm_job_id = slurm_job_id self._job_id_event.set() + sacct = shutil.which("sacct") + if not sacct: + return False try: result = subprocess.run( - ["sacct", "-j", slurm_job_id, "--noheader", "-o", "State", "-P"], + [sacct, "-j", slurm_job_id, "--noheader", "-o", "State", "-P"], capture_output=True, text=True, timeout=10, ) + if result.returncode != 0: + return False state = (result.stdout or "").strip().split("\n")[0].strip() return state in ("RUNNING", "PENDING", "CONFIGURING") except Exception: diff --git a/server/revocompute/manage_db.py b/server/revocompute/manage_db.py index 70481b395..f49211fcb 100644 --- a/server/revocompute/manage_db.py +++ b/server/revocompute/manage_db.py @@ -127,7 +127,9 @@ def task_type_all(self) -> list[dict]: """Return all task type config rows.""" cols = ("tool",) + _ALL_TASK_TYPE_FIELDS with self._lock: - rows = self._conn.execute(f"SELECT {', '.join(cols)} FROM task_type_config ORDER BY tool").fetchall() + rows = self._conn.execute( # skipcq: BAN-B608 — cols are module-level field constants, values bound below + f"SELECT {', '.join(cols)} FROM task_type_config ORDER BY tool" + ).fetchall() result: list[dict] = [] for r in rows: row = {"tool": r[0]} @@ -144,8 +146,9 @@ def task_type_get(self, tool: str) -> dict | None: """Return one task type config row, or None.""" cols = ("tool",) + _ALL_TASK_TYPE_FIELDS with self._lock: + # BAN-B608: cols are module-level field constants; the value is bound via ? row = self._conn.execute( - f"SELECT {', '.join(cols)} FROM task_type_config WHERE tool = ?", + f"SELECT {', '.join(cols)} FROM task_type_config WHERE tool = ?", # skipcq: BAN-B608 (tool,), ).fetchone() if row is None: @@ -179,8 +182,9 @@ def task_type_upsert(self, tool: str, **fields) -> None: values = list(updates.values()) with self._lock: + # BAN-B608: keys are allowlisted against _ALL_TASK_TYPE_FIELDS; values bound via ? self._conn.execute( - f"INSERT INTO task_type_config (tool, {columns}) " + f"INSERT INTO task_type_config (tool, {columns}) " # skipcq: BAN-B608 f"VALUES (?, {placeholders}) " f"ON CONFLICT(tool) DO UPDATE SET " + ", ".join(f"{c}=excluded.{c}" for c in updates), [tool] + values, @@ -262,8 +266,10 @@ def apply_resource_updates( continue columns = ", ".join(updates) placeholders = ", ".join("?" for _ in updates) + # BAN-B608: keys are allowlisted against _ALL_TASK_TYPE_FIELDS; values bound via ? self._conn.execute( - f"INSERT INTO task_type_config (tool, {columns}) VALUES (?, {placeholders}) " + f"INSERT INTO task_type_config (tool, {columns}) " # skipcq: BAN-B608 + f"VALUES (?, {placeholders}) " f"ON CONFLICT(tool) DO UPDATE SET " + ", ".join(f"{column}=excluded.{column}" for column in updates), [tool, *updates.values()], diff --git a/server/revocompute/resource_audit.py b/server/revocompute/resource_audit.py index 77b4fe536..658e1edd9 100644 --- a/server/revocompute/resource_audit.py +++ b/server/revocompute/resource_audit.py @@ -35,7 +35,9 @@ def _read_database(path: str) -> tuple[dict[str, str], dict[str, dict[str, objec globals_ = dict(connection.execute("SELECT key, value FROM resource_config")) if "task_type_config" in tables: columns = [row[1] for row in connection.execute("PRAGMA table_info(task_type_config)")] - rows = connection.execute(f"SELECT {', '.join(columns)} FROM task_type_config") + rows = connection.execute( # skipcq: BAN-B608 — column names come from PRAGMA table_info, not user input + f"SELECT {', '.join(columns)} FROM task_type_config" + ) for row in rows: record = dict(zip(columns, row, strict=True)) tasks[str(record.pop("tool"))] = record diff --git a/server/revocompute/routes.py b/server/revocompute/routes.py index 306166a75..0c1c943f4 100644 --- a/server/revocompute/routes.py +++ b/server/revocompute/routes.py @@ -436,7 +436,7 @@ def _save_uploaded_inputs( uploaded.save(temp_path) hasher = hashlib.sha256() with open(temp_path, "rb") as handle: - for chunk in iter(lambda: handle.read(65536), b""): + while chunk := handle.read(65536): hasher.update(chunk) blob_hash = hasher.hexdigest() blob_path = _safe_join(app.config["UPLOAD_FOLDER"], f"{blob_hash}.upload") @@ -800,7 +800,8 @@ def _result_artifact(task: dict[str, Any], relative_path: str) -> tuple[str, dic if not normalized or any(part in {"", ".", ".."} for part in normalized.split("/")): return None try: - with open(_safe_join(task["result_dir"], "manifest.json"), encoding="utf-8") as handle: + # PTC-W6004: task["result_dir"] is server-owned; the requested path is validated above + with open(_safe_join(task["result_dir"], "manifest.json"), encoding="utf-8") as handle: # skipcq: PTC-W6004 manifest = json.load(handle) except (OSError, json.JSONDecodeError): return None @@ -946,19 +947,27 @@ def cancel_task(md5sum): slurm_job_id = task.get("slurm_job_id") if slurm_job_id: - try: - subprocess.run(["scancel", str(slurm_job_id)], timeout=10, check=True) - logging.info("Cancelled SLURM job %s for task %s", slurm_job_id, md5sum) - except Exception as exc: # pylint: disable=broad-except - logging.warning("Failed to scancel SLURM job %s: %s", slurm_job_id, exc) + scancel = shutil.which("scancel") + if not scancel: + logging.warning("scancel not found; cannot cancel SLURM job %s", slurm_job_id) + else: + try: + subprocess.run([scancel, str(slurm_job_id)], timeout=10, check=True) + logging.info("Cancelled SLURM job %s for task %s", slurm_job_id, md5sum) + except Exception as exc: # pylint: disable=broad-except + logging.warning("Failed to scancel SLURM job %s: %s", slurm_job_id, exc) container_id = task.get("container_id") if container_id: - try: - subprocess.run(["docker", "stop", str(container_id)], timeout=15, check=True) - logging.info("Stopped Docker container %s for task %s", container_id, md5sum) - except Exception as exc: # pylint: disable=broad-except - logging.warning("Failed to stop container %s: %s", container_id, exc) + docker = shutil.which("docker") + if not docker: + logging.warning("docker not found; cannot stop container %s", container_id) + else: + try: + subprocess.run([docker, "stop", str(container_id)], timeout=15, check=True) + logging.info("Stopped Docker container %s for task %s", container_id, md5sum) + except Exception as exc: # pylint: disable=broad-except + logging.warning("Failed to stop container %s: %s", container_id, exc) celery_id = task.get("celery_task_id") if celery_id: diff --git a/server/revocompute/task_runtime.py b/server/revocompute/task_runtime.py index 65f6fb7a9..8d4c2d2d6 100644 --- a/server/revocompute/task_runtime.py +++ b/server/revocompute/task_runtime.py @@ -291,7 +291,8 @@ def _run_compute_job( _IMAGE_PREVIEW_EXTENSIONS = {".gif", ".jpeg", ".jpg", ".png", ".svg", ".webp"} -def _sha256_file(path: str) -> str: +# PTC-W6004: internal utility — callers pass server-built snapshot paths only +def _sha256_file(path: str) -> str: # skipcq: PTC-W6004 digest = hashlib.sha256() with open(path, "rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): @@ -640,10 +641,11 @@ def _recover_orphaned_tasks() -> int: task_type = task.get("task_type", "gremlin") logging.info("Recovery: checking orphaned task %s", md5sum) + from revocompute.task_types import get as _gt + if container_id: try: - from revocompute.job.runners.docker_runner import DockerJob # noqa: F811 - from revocompute.task_types import get as _gt # noqa: F811 + from revocompute.job.runners.docker_runner import DockerJob tt, runner = _gt(task_type) job = DockerJob(md5sum, tt, runner, [], task["result_dir"]) @@ -662,8 +664,7 @@ def _recover_orphaned_tasks() -> int: elif slurm_job_id: try: - from revocompute.job.runners.slurm_runner import SlurmJob # noqa: F811 - from revocompute.task_types import get as _gt + from revocompute.job.runners.slurm_runner import SlurmJob tt, runner = _gt(task_type) job = SlurmJob(md5sum, tt, runner, [], task["result_dir"]) diff --git a/server/revocompute/task_types/__init__.py b/server/revocompute/task_types/__init__.py index b930e5ca9..33bdda6d9 100644 --- a/server/revocompute/task_types/__init__.py +++ b/server/revocompute/task_types/__init__.py @@ -289,7 +289,8 @@ def _load_input_workspace( # --------------------------------------------------------------------------- -def _load_runner_config(path: str) -> RunnerConfig: +# PTC-W6004: operator-provisioned runner YAML path, not user input +def _load_runner_config(path: str) -> RunnerConfig: # skipcq: PTC-W6004 with open(path, encoding="utf-8") as f: data = yaml.safe_load(f) or {} return RunnerConfig( @@ -315,7 +316,7 @@ def load_registry(task_types_yaml: str, runners_dir: str, enabled: set[str]) -> ``gremlin`` is always enabled. """ with open(task_types_yaml, encoding="utf-8") as f: - types_data = yaml.safe_load(f) + types_data = yaml.safe_load(f) # skipcq: PTC-W6004 — deployment-owned registry path, not user input if not types_data: raise ValueError(f"Task registry is empty: {task_types_yaml}") diff --git a/server/tests/test_runner_script_static.py b/server/tests/test_runner_script_static.py index b40fcf4ee..41791bb30 100644 --- a/server/tests/test_runner_script_static.py +++ b/server/tests/test_runner_script_static.py @@ -283,7 +283,8 @@ def test_esm_image_installs_the_esm1v_csv_dependency(): dockerfile = (SERVER_ROOT / "docker" / "runners" / "esm" / "Dockerfile").read_text() assert '"pandas==2.2.3"' in dockerfile - assert 'python -c "import esm2, pandas"' in dockerfile + assert '"scipy==1.12.0"' in dockerfile + assert 'python -c "import esm2, esm2.inverse_folding, pandas"' in dockerfile def test_easifa_image_requires_the_installed_prediction_cli(): diff --git a/server/tools/audit_runtime_sizes.py b/server/tools/audit_runtime_sizes.py index 3198d124f..38777d404 100644 --- a/server/tools/audit_runtime_sizes.py +++ b/server/tools/audit_runtime_sizes.py @@ -13,6 +13,7 @@ import argparse import json import os +import shutil import subprocess from pathlib import Path from typing import Any @@ -21,8 +22,11 @@ def _docker_size(image: str) -> int | None: + docker = shutil.which("docker") + if not docker: + return None result = subprocess.run( # nosec B603 -- fixed executable and arguments - ["docker", "image", "inspect", "--format", "{{.Size}}", image], + [docker, "image", "inspect", "--format", "{{.Size}}", image], check=False, capture_output=True, text=True, diff --git a/src/REvoDesign/UI/types.py b/src/REvoDesign/UI/types.py index b7700ff00..79ca24fd2 100644 --- a/src/REvoDesign/UI/types.py +++ b/src/REvoDesign/UI/types.py @@ -7,7 +7,7 @@ from typing import Protocol -from REvoDesign.Qt import QtCore, QtGui, QtWidgets +from REvoDesign.Qt import QtGui, QtWidgets class REvoDesignUiProtocol(Protocol): From 55d29051cfefba4404195aa9c6161d221f38589d Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 11:10:08 +0800 Subject: [PATCH 2/7] fix(server): security hardening per audit + task lifecycle polish - Redis: requirepass via restart.sh-generated REDIS_PASSWORD; gateway and SLURM redis publish loopback-only - Compose: executor-scoped docker.sock (new docker-compose.docker.yml); SLURM workers no longer inherit host Docker access - Secure cookie: trusted X-Forwarded-Proto chain (gunicorn --forwarded-allow-ips) + AUTH_COOKIE_SECURE belt-and-braces - Runners assumed hostile: apptainer --containall --cleanenv; docker read-only rootfs, cap_drop=ALL, no-new-privileges, pids_limit, no network - O(1) API-key digest lookup; Redis rate limiting + CAPTCHA nonces with documented in-memory fallback - Per-input-kind content validators; symlink-aware _safe_join containment - PRIME: vendored model code, trust_remote_code=False, optional weights manifest, fail-closed - Artifacts default to attachment + sandbox CSP; CSP drops 'unsafe-inline' - Terminal tasks delete their input workspace; submissions captured to results/debug for reproduction - Dashboard: bounded sequence previews; resource review hidden from the submission form - Repo-wide formatting pass (make black); pre-commit skips documented: UI-typing/i18n hooks need PyMOL; autopep8/isort/flake8 conflict with black formatting (pre-existing) Co-Authored-By: Claude --- .gitignore | 2 + CHANGELOG.md | 99 ++++- server/.env.example | 16 +- server/README.md | 33 +- server/docker-compose.docker.yml | 22 + server/docker-compose.slurm.yml | 18 +- server/docker-compose.yml | 38 +- server/docker/nginx/default.conf.template | 2 + server/docker/runners/esm/esm1v_score.py | 1 - server/docker/runners/esm/esm_if1_design.py | 5 +- server/docker/runners/esm/msa1b_score.py | 9 +- server/docker/runners/prime/Dockerfile | 5 + server/docker/runners/prime/run.sh | 165 +++++++- server/docker/runners/prime/vendor/README.md | 59 +++ .../runners/prime/vendor/placeholder.txt | 3 + server/docker/server/Dockerfile | 4 +- server/nginx_sites/REvoCompute.app | 3 + server/pyproject.toml | 1 + server/revocompute/app.py | 16 +- server/revocompute/auth.py | 99 +++-- server/revocompute/input_validation.py | 243 +++++++++++ .../revocompute/job/runners/docker_runner.py | 17 +- .../revocompute/job/runners/slurm_runner.py | 11 +- server/revocompute/manage_db.py | 14 +- server/revocompute/ratelimit.py | 43 +- server/revocompute/redis_util.py | 42 ++ server/revocompute/resource_audit.py | 5 +- server/revocompute/resource_policy.py | 27 +- server/revocompute/routes.py | 116 +++--- server/revocompute/schemas.py | 2 +- server/revocompute/static/js/dashboard.js | 7 +- .../revocompute/static/js/input-workspace.js | 6 +- .../revocompute/static/js/reset-password.js | 49 +++ server/revocompute/static/js/task-results.js | 2 +- server/revocompute/task_runtime.py | 183 ++++++++- server/revocompute/task_types/__init__.py | 21 +- server/revocompute/templates/dashboard.html | 6 +- .../revocompute/templates/reset-password.html | 49 +-- .../revocompute/templates/task_results.html | 2 +- .../revocompute/templates/user_control.html | 4 +- server/run/restart.sh | 39 +- server/tests/conftest.py | 12 +- server/tests/full_stack_smoke.py | 8 +- server/tests/run_full_stack_test.sh | 4 +- server/tests/test_admin.py | 2 +- server/tests/test_auth.py | 8 +- server/tests/test_browser_contracts.py | 8 +- server/tests/test_debug_capture.py | 248 ++++++++++++ server/tests/test_docker.py | 19 +- server/tests/test_docker_runner.py | 13 +- server/tests/test_input_validation.py | 379 ++++++++++++++++++ server/tests/test_process_isolation.py | 39 +- server/tests/test_resource_policy.py | 12 +- server/tests/test_runner_script_static.py | 139 +++++-- server/tests/test_security_hardening.py | 310 ++++++++++++++ server/tests/test_slurm_runner.py | 27 +- server/tests/test_task_runtime_hardening.py | 99 +++++ server/tests/test_task_type_registry.py | 79 +--- server/tests/test_tasks.py | 56 ++- src/REvoDesign/tools/rosetta_utils.py | 2 +- 60 files changed, 2504 insertions(+), 448 deletions(-) create mode 100644 server/docker-compose.docker.yml create mode 100644 server/docker/runners/prime/vendor/README.md create mode 100644 server/docker/runners/prime/vendor/placeholder.txt create mode 100644 server/revocompute/input_validation.py create mode 100644 server/revocompute/redis_util.py create mode 100644 server/revocompute/static/js/reset-password.js create mode 100644 server/tests/test_debug_capture.py create mode 100644 server/tests/test_input_validation.py create mode 100644 server/tests/test_security_hardening.py create mode 100644 server/tests/test_task_runtime_hardening.py diff --git a/.gitignore b/.gitignore index 9f33c09ae..631126f85 100644 --- a/.gitignore +++ b/.gitignore @@ -156,3 +156,5 @@ playground/config /temperal_pdb # security audit working doc (internal, not a deliverable) /server/security-audit-tracking.md +server/manage.sqlite +server/revocompute.sqlite3 diff --git a/CHANGELOG.md b/CHANGELOG.md index ab6fb98aa..a59e51947 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,12 +13,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Server auth hardening**: API keys are now stored as indexed sha256 + digests (`api_key_digest`) with single-lookup validation; legacy KDF + hashes migrate over with existing keys invalidated by design. CAPTCHA + nonces and rate-limit counters are Redis-first with per-process in-memory + fallback when Redis is down — login/register/captcha endpoints never break + on a Redis outage. The rate limiter no longer re-executes the endpoint + when a Redis call fails mid-request. + ### Removed ``` ## [Unreleased] ### Added +- **Upload content validation**: uploaded inputs are now content-checked by + extension (FASTA/A3M/PDB/mmCIF/JSON) with generous DoS caps, so third-party + parsers never see pathological files. Previously only GREMLIN FASTA inputs + got a first-line `>` check; non-GREMLIN inputs were checked by extension and + a 4096-byte binary sniff alone. NUL bytes beyond the sniff window, gzip + streams disguised as PDB, degenerate record counts, and JSON bombs are all + rejected at upload time. - **ESM-MSA-1b variant-effect task** (`esm_msa`): masked-marginal per-position profile over an uploaded a3m alignment, using `esm_msa1b_t12_100M_UR50S`. Outputs `msa1b_profile.csv` and @@ -182,8 +197,88 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Gunicorn error, Celery worker, and maintenance logs through fixed-name admin-only endpoints. Rotated ZIPs are grouped in a lazy file tree and can be downloaded individually. - -### Fixed +- **Server: artifact responses default to attachment + sandbox CSP**: result + artifacts (untrusted runner output) are served with + `Content-Disposition: attachment` by default (`?download=0` opts back into + inline rendering) and every Flask-mode artifact response carries + `Content-Security-Policy: sandbox`, closing the stored-XSS path via inline + SVG/HTML/XML artifacts (nginx mode sets the same header in + `docker/nginx/default.conf.template`). +- **Server: CSP no longer allows inline scripts**: all four inline + ` + diff --git a/server/revocompute/templates/reset-password.html b/server/revocompute/templates/reset-password.html index 0a9eb3c85..83172673d 100644 --- a/server/revocompute/templates/reset-password.html +++ b/server/revocompute/templates/reset-password.html @@ -37,53 +37,6 @@

Reset Password

- + diff --git a/server/revocompute/templates/task_results.html b/server/revocompute/templates/task_results.html index f7d7ca694..ef7fbf607 100644 --- a/server/revocompute/templates/task_results.html +++ b/server/revocompute/templates/task_results.html @@ -61,7 +61,7 @@

Choose an artifact

- + diff --git a/server/revocompute/templates/user_control.html b/server/revocompute/templates/user_control.html index ee3125cf3..2a0b91dc8 100644 --- a/server/revocompute/templates/user_control.html +++ b/server/revocompute/templates/user_control.html @@ -131,9 +131,7 @@

User Control

- + diff --git a/server/run/restart.sh b/server/run/restart.sh index ab1e3b735..5f2bab111 100755 --- a/server/run/restart.sh +++ b/server/run/restart.sh @@ -6,20 +6,43 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SERVER_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" COMPOSE_FILE="${SERVER_ROOT}/docker-compose.yml" COMPOSE_SLURM_FILE="${SERVER_ROOT}/docker-compose.slurm.yml" +COMPOSE_DOCKER_FILE="${SERVER_ROOT}/docker-compose.docker.yml" ENV_EXAMPLE_FILE="${SERVER_ROOT}/.env.example" PRIMARY_ENV_FILE="${SERVER_ROOT}/.env.production" CALLER_DIR="$(pwd)" -# Return compose -f arguments. When USE_SLURM is set, the slurm override -# file is appended so the worker container gets SLURM client bind-mounts. +# Return compose -f arguments. job_executor selects the matching override: +# docker mode adds the Docker socket to the worker, slurm mode adds SLURM +# client bind-mounts. The base worker is executor-neutral — compose merges +# volume lists by concatenation, so keeping the socket out of the base file +# is the only way to keep it out of SLURM-mode workers. compose_files() { local files=("-f" "${COMPOSE_FILE}") - if [[ "${USE_SLURM:-0}" == "1" ]] && [[ -f "${COMPOSE_SLURM_FILE}" ]]; then - files+=("-f" "${COMPOSE_SLURM_FILE}") + if [[ "${USE_SLURM:-0}" == "1" ]]; then + [[ -f "${COMPOSE_SLURM_FILE}" ]] && files+=("-f" "${COMPOSE_SLURM_FILE}") + else + [[ -f "${COMPOSE_DOCKER_FILE}" ]] && files+=("-f" "${COMPOSE_DOCKER_FILE}") fi printf '%s\n' "${files[@]}" } +# Generate and persist REDIS_PASSWORD when absent, and rewrite the known +# legacy password-less broker URIs so existing deployments keep working after +# Redis gains requirepass. The env file is deployment-owned text; only the +# three legacy URI forms are rewritten, anything custom is left alone. +ensure_redis_password() { + local _pass="" + if [[ -n "${REDIS_PASSWORD:-}" ]]; then return 0; fi + _pass="$(openssl rand -hex 24 2>/dev/null || python3 -c 'import secrets; print(secrets.token_hex(24))')" + printf '\n# Generated by restart.sh — Redis requirepass secret.\nREDIS_PASSWORD=%s\n' "${_pass}" >> "${ENV_FILE}" + export REDIS_PASSWORD="${_pass}" + local _legacy="" + for _legacy in "redis://redis:6379/0" "redis://127.0.0.1:6380/0"; do + sed -i "s#^\\(REDIS_URL\\|BROKER_URL\\|RESULT_BACKEND\\)=${_legacy}#\\1=redis://:${_pass}@${_legacy#redis://}#" "${ENV_FILE}" || true + done + echo "Generated REDIS_PASSWORD and stored it in ${ENV_FILE}." +} + # Normalize empty ENABLED_TASKRUNNERS ("build all") into an explicit list so a # failed runner can be dropped from it for the rest of the run. expand_enabled_runners() { @@ -293,6 +316,7 @@ require_env_file() { echo "Expected ${ENV_FILE} to exist. Run: REVODESIGN_SERVER_ENV=${ENV_FILE} bash server/run/restart.sh setup" >&2 exit 1 fi + ensure_redis_password } validate_required_settings() ( @@ -395,6 +419,11 @@ detect_docker_gid() { } ensure_docker_gid() { + if [[ "${USE_SLURM:-0}" == "1" ]]; then + # The socket mount lives only in docker-compose.docker.yml; SLURM-mode + # workers no longer need (or get) host Docker access. + return 0 + fi if [[ -z "${DOCKER_GID:-}" ]]; then DOCKER_GID="$(detect_docker_gid || true)" fi @@ -830,6 +859,8 @@ cmd_setup() { echo "Unable to auto-detect Docker socket group id; set DOCKER_GID when running build/up/restart." >&2 fi + ensure_redis_password + echo "Setup completed. Using env file: ${ENV_FILE}" echo "Review ${ENV_FILE} before starting services." } diff --git a/server/tests/conftest.py b/server/tests/conftest.py index 142f7ecb3..259e63397 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -25,12 +25,11 @@ from dataclasses import dataclass from pathlib import Path +import docker import pytest import requests from werkzeug.utils import secure_filename -import docker - # ── path setup ──────────────────────────────────────────────────────────────── SERVER_DIR = Path(__file__).resolve().parent.parent @@ -160,6 +159,15 @@ def _load_pssm_module(monkeypatch, tmp_path, extra_env: dict | None = None): monkeypatch.delenv(key, raising=False) else: monkeypatch.setenv(key, value) + # Rate limiting and CAPTCHA use Redis when REDIS_URL is reachable. Tests + # must not share counters with a live local Redis — every test hits the + # app from 127.0.0.1, so the suite would 429 itself across tests. Point + # it at a dead port unless a test explicitly overrides REDIS_URL. + if "REDIS_URL" not in (extra_env or {}): + monkeypatch.setenv("REDIS_URL", "redis://127.0.0.1:1/0") + from revocompute.redis_util import get_redis + + get_redis.cache_clear() # -- module load with import isolation -- server_dir = str(Path(REPO_DIR) / "server") diff --git a/server/tests/full_stack_smoke.py b/server/tests/full_stack_smoke.py index 38c5af580..9075aa545 100644 --- a/server/tests/full_stack_smoke.py +++ b/server/tests/full_stack_smoke.py @@ -145,15 +145,11 @@ def run_full_stack_checks( paths = {artifact["path"] for artifact in artifacts} artifact_prefix = fasta_path.stem assert any(path.endswith("log/task_finished") for path in paths) - assert any( - path.endswith(f"gremlin_res/{artifact_prefix}.i90c75_aln.GREMLIN.mrf.pkl") for path in paths - ) + assert any(path.endswith(f"gremlin_res/{artifact_prefix}.i90c75_aln.GREMLIN.mrf.pkl") for path in paths) assert any(path.endswith(f"pssm_msa/{artifact_prefix}_ascii_mtx_file") for path in paths) artifact = next( - item - for item in artifacts - if item["path"].endswith(f"pssm_msa/{artifact_prefix}_ascii_mtx_file") + item for item in artifacts if item["path"].endswith(f"pssm_msa/{artifact_prefix}_ascii_mtx_file") ) artifact_url = artifact["url"] if artifact_url.startswith("/"): diff --git a/server/tests/run_full_stack_test.sh b/server/tests/run_full_stack_test.sh index 41e466ed4..f7892d00e 100644 --- a/server/tests/run_full_stack_test.sh +++ b/server/tests/run_full_stack_test.sh @@ -19,11 +19,11 @@ cleanup() { local status=$? set +e if [[ ${status} -ne 0 && ${STACK_STARTED} -eq 1 ]]; then - docker compose -f "${SERVER_ROOT}/docker-compose.yml" --env-file "${ENV_FILE}" logs --no-color --tail=200 + docker compose -f "${SERVER_ROOT}/docker-compose.yml" -f "${SERVER_ROOT}/docker-compose.docker.yml" --env-file "${ENV_FILE}" logs --no-color --tail=200 fi if [[ -f "${ENV_FILE}" ]]; then REVODESIGN_SERVER_ENV="${ENV_FILE}" bash "${DEPLOY_SCRIPT}" down - DOCKER_GID=0 docker compose -f "${SERVER_ROOT}/docker-compose.yml" --env-file "${ENV_FILE}" \ + DOCKER_GID=0 docker compose -f "${SERVER_ROOT}/docker-compose.yml" -f "${SERVER_ROOT}/docker-compose.docker.yml" --env-file "${ENV_FILE}" \ down --volumes --remove-orphans fi docker image rm --force "${SERVER_IMAGE}" "${RUNNER_IMAGE}" >/dev/null 2>&1 diff --git a/server/tests/test_admin.py b/server/tests/test_admin.py index deb3286aa..4fee168e4 100644 --- a/server/tests/test_admin.py +++ b/server/tests/test_admin.py @@ -60,7 +60,7 @@ def test_admin_can_list_users(monkeypatch, tmp_path): # Safe fields present, sensitive fields absent for u in data["users"]: assert "password_hash" not in u - assert "api_key_hash" not in u + assert "api_key_digest" not in u assert "id" in u assert "email" in u assert "registration_status" in u diff --git a/server/tests/test_auth.py b/server/tests/test_auth.py index 07cd94d1b..d4564cbe7 100644 --- a/server/tests/test_auth.py +++ b/server/tests/test_auth.py @@ -37,7 +37,7 @@ def test_auth_me_returns_current_user(monkeypatch, tmp_path): assert data["pi_name"] is None assert "is_admin" not in data assert "password_hash" not in data - assert "api_key_hash" not in data + assert "api_key_digest" not in data def test_auth_me_rejects_unauthenticated(monkeypatch, tmp_path): @@ -879,7 +879,8 @@ class _DummyAsyncResult: auth_header = _test_client_auth(module) # Submit 5 tasks with different content to avoid dedup for i in range(5): - content = f">test{i}\nACDE{i}\n".encode() + # Sequence must be a valid protein alphabet so content validation passes. + content = f">test{i}\nACDE{'FGHIK'[i]}\n".encode() resp = client.post( "/compute/api/post", data={"file": (io.BytesIO(content), f"task{i}.fasta")}, @@ -1026,7 +1027,7 @@ def test_schema_batch_user_requires_nonempty_user_ids(monkeypatch, tmp_path): def test_schema_user_response_excludes_password_hash(monkeypatch, tmp_path): - """UserResponse does not accept password_hash or api_key_hash fields.""" + """UserResponse does not accept password_hash or api_key_digest fields.""" from pydantic import ValidationError from revocompute.schemas import UserResponse @@ -1050,3 +1051,4 @@ def test_schema_user_response_excludes_password_hash(monkeypatch, tmp_path): assert user.username == "test" # password_hash should not be in the model assert "password_hash" not in UserResponse.model_fields + assert "api_key_digest" not in UserResponse.model_fields diff --git a/server/tests/test_browser_contracts.py b/server/tests/test_browser_contracts.py index 26de8b4f2..36df822a0 100644 --- a/server/tests/test_browser_contracts.py +++ b/server/tests/test_browser_contracts.py @@ -35,12 +35,16 @@ def test_js_modules_load_in_correct_order() -> None: js_dir = Path(__file__).resolve().parents[1] / "revocompute" / "static" / "js" check = subprocess.run( ["node", "--check", str(js_dir / "plugin-host.js")], - capture_output=True, text=True, timeout=10, + capture_output=True, + text=True, + timeout=10, ) assert check.returncode == 0, f"plugin-host.js syntax: {check.stderr}" for filename in ("result-preview-plugins.js", "input-workspace.js"): result = subprocess.run( ["node", "--check", str(js_dir / filename)], - capture_output=True, text=True, timeout=10, + capture_output=True, + text=True, + timeout=10, ) assert result.returncode == 0, f"{filename} syntax: {result.stderr}" diff --git a/server/tests/test_debug_capture.py b/server/tests/test_debug_capture.py new file mode 100644 index 000000000..c0a0daadc --- /dev/null +++ b/server/tests/test_debug_capture.py @@ -0,0 +1,248 @@ +# Copyright (c) 2026 The REvoDesign Developers. +# Distributed under the terms of the GNU General Public License v3.0. +# SPDX-License-Identifier: GPL-3.0-only + +"""Debug submission capture: the user's submission form and input copies are +written into the result dir before workspace cleanup, so they survive it.""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import shutil +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +SERVER_DIR = Path(__file__).resolve().parent.parent + + +@pytest.fixture +def rt(monkeypatch, tmp_path): + """Import task_runtime with a self-contained server/config layout.""" + env_root = tmp_path / "server" + shutil.copytree(SERVER_DIR / "config", env_root / "config") + monkeypatch.setenv("SERVER_DIR", str(env_root)) + monkeypatch.setenv("CONFIG_DIR", str(env_root / "config")) + monkeypatch.setenv("RUNNER_UID", "1234") + monkeypatch.setenv("RUNNER_GID", "5678") + _pg = sys.modules.get("revocompute") + if _pg is not None: + _pg.__dict__.pop("task_runtime", None) + sys.modules.pop("revocompute.task_runtime", None) + try: + module = importlib.import_module("revocompute.task_runtime") + finally: + if _pg is not None: + _pg.__dict__.pop("task_runtime", None) + sys.modules.pop("revocompute.task_runtime", None) + monkeypatch.setattr( + module, + "CONFIG", + replace( + module.CONFIG, + workspace_folder=str(env_root / "workspaces"), + results_folder=str(env_root / "results"), + ), + ) + return module + + +def _make_task(rt, relative_paths=("query.fasta",)): + md5 = "a" * 32 + ws = Path(rt.CONFIG.workspace_folder) + snapshot_root = ws / "alice" / md5 / "inputs" + snapshot_root.mkdir(parents=True) + entities = [] + for index, relative_path in enumerate(relative_paths): + snapshot = snapshot_root / relative_path + snapshot.parent.mkdir(parents=True, exist_ok=True) + content = f">seq{index}\nACDE\n".encode() + snapshot.write_bytes(content) + entities.append( + { + "name": "primary_input" if index == 0 else f"input_{index + 1}", + "type": "file", + "value": Path(relative_path).name, + "verified_value": relative_path, + "relative_path": relative_path, + "mounted": f"/mnt/revocompute/alice/inputs/{relative_path}", + "hash": hashlib.sha256(content).hexdigest(), + "snapshot_path": str(snapshot), + "snapshot_root": str(snapshot_root), + "workspace_key": "alice", + } + ) + entities.append({"name": "max_iter", "type": "int", "value": 5, "verified_value": 5}) + result_dir = Path(rt.CONFIG.results_folder) / md5 + result_dir.mkdir(parents=True) + task = { + "md5sum": md5, + "task_type": "gremlin", + "username": "alice", + "result_dir": str(result_dir), + "input_form": json.dumps( + { + "user": "alice", + "workspace_key": "alice", + "virtual_root": "/mnt/revocompute/alice", + "snapshot_root": str(snapshot_root), + "submitted_at": "2026-08-14T00:00:00+00:00", + "entities": entities, + } + ), + "uploaded_at": 1700000000.0, + } + return task, entities + + +class _FakeTaskStore: + def __init__(self, task): + self.task = task + self.updates = [] + + def get_task(self, md5sum): + return self.task + + def update_task(self, md5sum, **fields): + self.updates.append(fields) + + +class _FakeTaskType: + stage_markers = {"running": "Running", "done": "Done"} + + +# -- capture helper ------------------------------------------------------------ + + +def test_capture_writes_submission_json_and_input_copies(rt, tmp_path): + task, entities = _make_task(rt) + rt._capture_debug_submission(task, entities) + + debug_dir = tmp_path / "server" / "results" / task["md5sum"] / "debug" + assert (debug_dir / "inputs" / "query.fasta").read_bytes() == b">seq0\nACDE\n" + + submission = json.loads((debug_dir / "submission.json").read_text(encoding="utf-8")) + assert submission["task_type"] == "gremlin" + assert submission["username"] == "alice" + assert submission["submitted_at"] == "2026-08-14T00:00:00+00:00" + assert submission["params"] == {"max_iter": 5} + (file_entry,) = submission["files"] + assert file_entry["name"] == "query.fasta" + assert file_entry["size"] == len(b">seq0\nACDE\n") + assert file_entry["sha256"] == hashlib.sha256(b">seq0\nACDE\n").hexdigest() + + +def test_capture_keeps_nested_user_facing_paths(rt): + task, entities = _make_task(rt, relative_paths=("sub/dir/input.fa",)) + rt._capture_debug_submission(task, entities) + + debug_dir = Path(task["result_dir"]) / "debug" + assert (debug_dir / "inputs" / "sub" / "dir" / "input.fa").read_bytes() == b">seq0\nACDE\n" + submission = json.loads((debug_dir / "submission.json").read_text(encoding="utf-8")) + assert submission["files"][0]["name"] == "sub/dir/input.fa" + + +def test_capture_uses_explicit_params_argument(rt): + task, entities = _make_task(rt) + rt._capture_debug_submission(task, entities, {"overrides": "raw"}) + + debug_dir = Path(task["result_dir"]) / "debug" + submission = json.loads((debug_dir / "submission.json").read_text(encoding="utf-8")) + assert submission["params"] == {"overrides": "raw"} + + +def test_capture_skips_path_traversal(rt): + task, entities = _make_task(rt) + entities.insert( + 0, + { + "name": "evil", + "type": "file", + "relative_path": "../evil.fa", + "snapshot_path": entities[0]["snapshot_path"], + }, + ) + rt._capture_debug_submission(task, entities) + + debug_dir = Path(task["result_dir"]) / "debug" + assert not (debug_dir / "inputs" / "evil.fa").exists() + submission = json.loads((debug_dir / "submission.json").read_text(encoding="utf-8")) + assert all(fe["name"] != "../evil.fa" for fe in submission["files"]) + + +def test_capture_skips_snapshot_outside_workspace(rt, tmp_path): + task, entities = _make_task(rt) + outside = tmp_path / "outside.bin" + outside.write_bytes(b"secret") + entities.insert( + 0, + { + "name": "evil", + "type": "file", + "relative_path": "stolen.bin", + "snapshot_path": str(outside), + }, + ) + rt._capture_debug_submission(task, entities) + + debug_dir = Path(task["result_dir"]) / "debug" + assert not (debug_dir / "inputs" / "stolen.bin").exists() + + +def test_capture_never_raises_on_missing_snapshot(rt): + task, entities = _make_task(rt) + entities[0]["snapshot_path"] = str(Path(entities[0]["snapshot_path"]).parent / "gone.fa") + # Must not raise — the job finalization keeps going regardless. + rt._capture_debug_submission(task, entities) + + debug_dir = Path(task["result_dir"]) / "debug" + submission = json.loads((debug_dir / "submission.json").read_text(encoding="utf-8")) + assert submission["files"] == [] + + +# -- terminal-point wiring ----------------------------------------------------- + + +def test_record_failure_captures_before_workspace_cleanup(rt, monkeypatch): + task, _ = _make_task(rt) + fake_store = _FakeTaskStore(task) + monkeypatch.setattr(rt, "task_store", fake_store) + + rt._record_failure(task["md5sum"], task, 100.0, "running", "boom") + + assert fake_store.updates[-1]["status"] == "failed" + # Workspace was cleaned up, so the debug copy proves capture ran first. + assert not (Path(rt.CONFIG.workspace_folder) / "alice" / task["md5sum"]).exists() + result_dir = Path(task["result_dir"]) + debug_dir = result_dir / "debug" + assert (debug_dir / "submission.json").is_file() + assert (debug_dir / "inputs" / "query.fasta").read_bytes() == b">seq0\nACDE\n" + # The failed-task manifest published after capture includes the debug files. + manifest = json.loads((result_dir / "manifest.json").read_text(encoding="utf-8")) + assert "debug/submission.json" in {a["path"] for a in manifest["artifacts"]} + + +def test_finalize_after_poll_publishes_debug_files_in_manifest(rt, monkeypatch): + task, _ = _make_task(rt) + fake_store = _FakeTaskStore(task) + monkeypatch.setattr(rt, "task_store", fake_store) + + rt._finalize_after_poll(task["md5sum"], task, _FakeTaskType(), rt.JobState.COMPLETED) + + assert fake_store.updates[-1]["status"] == "finished" + assert not (Path(rt.CONFIG.workspace_folder) / "alice" / task["md5sum"]).exists() + manifest = json.loads((Path(task["result_dir"]) / "manifest.json").read_text(encoding="utf-8")) + artifact_paths = {artifact["path"] for artifact in manifest["artifacts"]} + assert "debug/submission.json" in artifact_paths + assert "debug/inputs/query.fasta" in artifact_paths + + +def test_entities_from_input_form_tolerates_bad_rows(rt): + assert rt._entities_from_input_form({}) == [] + assert rt._entities_from_input_form({"input_form": "not json"}) == [] + assert rt._entities_from_input_form({"input_form": '"just a string"'}) == [] + assert rt._entities_from_input_form({"input_form": json.dumps({"entities": {"not": "a list"}})}) == [] diff --git a/server/tests/test_docker.py b/server/tests/test_docker.py index 195124c09..ab8a8b5ba 100644 --- a/server/tests/test_docker.py +++ b/server/tests/test_docker.py @@ -16,6 +16,7 @@ from dataclasses import dataclass from pathlib import Path +import docker import pytest import requests from conftest import ( @@ -41,8 +42,6 @@ has_docker_daemon, ) -import docker - # Docker-specific helpers (most are imported from conftest) # ================================================================== @@ -481,22 +480,6 @@ def _wait_for_task(base_url: str, headers: dict[str, str], md5sum: str, timeout: raise AssertionError("Timed out waiting for GREMLIN task to finish") -def _wait_for_failed_task(base_url: str, headers: dict[str, str], md5sum: str, timeout: float = 900.0) -> dict: - deadline = time.time() + timeout - with requests.Session() as session: - session.headers.update(headers) - url = f"{base_url}/compute/api/running/{md5sum}" - while time.time() < deadline: - response = session.get(url, timeout=10) - payload = response.json() if response.headers.get("Content-Type", "").startswith("application/json") else {} - if response.status_code == 404 and payload.get("status") == "failed": - return payload - if payload.get("status") == "finished": - raise AssertionError("GREMLIN task unexpectedly succeeded") - time.sleep(10) - raise AssertionError("Timed out waiting for GREMLIN task to fail") - - # ================================================================== # Docker integration tests # ================================================================== diff --git a/server/tests/test_docker_runner.py b/server/tests/test_docker_runner.py index 61e4996d6..28dda2b56 100644 --- a/server/tests/test_docker_runner.py +++ b/server/tests/test_docker_runner.py @@ -12,12 +12,11 @@ from pathlib import Path from unittest.mock import MagicMock +import docker import pytest from revocompute.job import JobState from revocompute.job.runners.docker_runner import DockerJob -import docker - def _make_task_type(**kwargs): from revocompute.task_types import RuntimeFamily, TaskType @@ -103,6 +102,16 @@ def test_submit_creates_container_and_returns_id(tmp_path): assert call_kwargs["nano_cpus"] == 1_000_000_000 assert call_kwargs["mem_limit"] == "4g" assert call_kwargs["environment"]["OMP_NUM_THREADS"] == "1" + # Sandbox: untrusted scientific code runs with no capabilities, no + # privilege escalation, no network, read-only rootfs (caches go to the + # tmpfs /tmp), and a PID ceiling. + assert call_kwargs["read_only"] is True + assert call_kwargs["cap_drop"] == ["ALL"] + assert call_kwargs["security_opt"] == ["no-new-privileges:true"] + assert call_kwargs["pids_limit"] == 1024 + assert call_kwargs["network_mode"] == "none" + assert call_kwargs["tmpfs"] == {"/tmp": "mode=1777"} + assert call_kwargs["environment"]["HOME"] == "/tmp" def test_submit_passes_gpu_device_request(tmp_path): diff --git a/server/tests/test_input_validation.py b/server/tests/test_input_validation.py new file mode 100644 index 000000000..e3fdba10a --- /dev/null +++ b/server/tests/test_input_validation.py @@ -0,0 +1,379 @@ +# Copyright (c) 2026 The REvoDesign Developers. +# Distributed under the terms of the GNU General Public License v3.0. +# SPDX-License-Identifier: GPL-3.0-only + +"""Content validators for uploaded scientific inputs. + +Legitimate files pass, pathological files are rejected, and the caps are +generous enough that no plausible real file can trip them. +""" + +from __future__ import annotations + +import gzip +import io +from dataclasses import replace +from pathlib import Path + +import pytest +from conftest import _load_pssm_module, _test_client_auth +from revocompute.input_validation import ( + MAX_CIF_ATOMS, + MAX_CIF_RECORD_LENGTH, + MAX_FASTA_SEQUENCES, + MAX_FASTA_TOTAL_RESIDUES, + MAX_JSON_DEPTH, + MAX_JSON_NODES, + MAX_PDB_LINES, + MAX_PDB_RECORD_LENGTH, + validate_a3m, + validate_fasta, + validate_input_file, + validate_json, + validate_mmcif, + validate_pdb, +) + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _write(tmp_path: Path, content: bytes, name: str = "input") -> Path: + path = tmp_path / name + path.write_bytes(content) + return path + + +# ── real fixtures must pass ──────────────────────────────────────────────────── + + +def test_real_fasta_fixtures_pass(): + for path in ( + REPO_ROOT / "tests/data/msa/2KL8.fasta", + REPO_ROOT / "tests/data/msa/2KL8_blast.fasta", + Path(__file__).parent / "data/test_esm.fasta", + ): + assert validate_fasta(str(path)) is None, path + + +@pytest.mark.parametrize( + "relative", + [ + "tests/data/pdb/1SUO.pdb", + "tests/data/pdb/5an7.pdb", + "tests/data/pdb/2KL8.pdb", + "tests/data/pdb/3fap_hf3_A_short_lig.pdb", + "tests/data/pdb/3fap_hf3_A_short_00001.pdb", + "tests/data/3fap_hf3_A_short.pdb", + "tests/data/6zcy_lig.pdb", + "tests/data/lig/lig.fa.pdb", + "tests/data/lig/lig.cen_conformers.pdb", + ], +) +def test_real_pdb_fixtures_pass(relative): + assert validate_pdb(str(REPO_ROOT / relative)) is None + + +@pytest.mark.parametrize( + "relative", + [ + "tests/data/json/sm_input/12968814160.json", + "tests/data/ddg_csv.json", + "tests/data/kinetics/openkinetics_1SUO/manifest.json", + "tests/data/kinetics/openkinetics_1SUO/substrate.json", + "tests/data/kinetics/openkinetics_1SUO/submit_response.json", + ], +) +def test_real_json_fixtures_pass(relative): + assert validate_json(str(REPO_ROOT / relative)) is None + + +# ── FASTA / A3M ──────────────────────────────────────────────────────────────── + + +def test_fasta_requires_header(tmp_path): + path = _write(tmp_path, b"ACDEFGHIK\n") + assert "'>' header" in validate_fasta(str(path)) + + +def test_fasta_rejects_sequence_before_header(tmp_path): + path = _write(tmp_path, b"ACDE\n>h\nACDE\n") + assert "start with a '>' header" in validate_fasta(str(path)) + + +def test_fasta_rejects_non_alphabet_characters(tmp_path): + path = _write(tmp_path, b">h\nACD2EF\n") + assert "invalid character '2'" in validate_fasta(str(path)) + + +def test_fasta_rejects_lowercase_but_a3m_allows_it(tmp_path): + lower = _write(tmp_path, b">h\nACDEfghi\n") + assert "invalid character" in validate_fasta(str(lower)) + assert validate_a3m(str(lower)) is None + + +def test_fasta_accepts_full_alphabet_and_gaps(tmp_path): + path = _write( + tmp_path, + b">h\nACDEFGHIKLMNPQRSTVWYXBZJOU*-. ACDE\n", # interior space tolerated + ) + assert validate_fasta(str(path)) is None + + +def test_fasta_rejects_nul_byte_deep_in_file(tmp_path): + # The HTTP-layer sniff only reads 4096 bytes, so the NUL must be caught here. + path = _write(tmp_path, b">h\n" + b"A" * 8192 + b"\0ACDE\n") + assert "NUL byte" in validate_fasta(str(path)) + + +def test_fasta_rejects_too_many_sequences(tmp_path): + path = _write(tmp_path, b">s\nA\n" * (MAX_FASTA_SEQUENCES + 1)) + assert f"more than {MAX_FASTA_SEQUENCES} sequences" in validate_fasta(str(path)) + + +def test_fasta_residue_cap_cannot_be_reached_within_upload_limit(): + # 16 MiB upload cap / 1 byte per residue — the cap is a safety valve that + # cannot fire on any file that fits in MAX_CONTENT_LENGTH. + assert MAX_FASTA_TOTAL_RESIDUES > 16 * 1024 * 1024 + + +# ── PDB ──────────────────────────────────────────────────────────────────────── + + +def test_pdb_accepts_long_remark_preamble(tmp_path): + preamble = b"REMARK 999 long preamble\n" * 200 + body = ( + b"CRYST1 100.0 100.0 100.0 90 90 90 P 1\n" + b"ATOM 1 CA ALA A 1 0.000 0.000 0.000 1.00 0.00 C\n" + b"END\n" + ) + path = _write(tmp_path, preamble + body) + assert validate_pdb(str(path)) is None + + +def test_pdb_accepts_single_atom_line_without_end(tmp_path): + # Mirrors the minimal PDB used by existing route tests. + path = _write(tmp_path, b"ATOM 1 CA ALA A 1\n") + assert validate_pdb(str(path)) is None + + +def test_pdb_rejects_gzip_binary(tmp_path): + # Compressed bytes are rejected by either the NUL check or the record + # sniff — what matters is that no gzip stream passes for a PDB. + path = _write(tmp_path, gzip.compress(b"ATOM 1 CA ALA A 1\n" * 100), "model.pdb") + assert validate_pdb(str(path)) is not None + + +def test_pdb_rejects_plain_text_without_records(tmp_path): + path = _write(tmp_path, b"this is not a pdb\n" * 50) + assert "ATOM, HETATM, or END" in validate_pdb(str(path)) + + +def test_pdb_rejects_too_many_lines(tmp_path): + path = _write(tmp_path, b"END\n" * (MAX_PDB_LINES + 1)) + assert f"more than {MAX_PDB_LINES} lines" in validate_pdb(str(path)) + + +def test_pdb_rejects_overlong_record(tmp_path): + path = _write(tmp_path, b"ATOM " + b"X" * MAX_PDB_RECORD_LENGTH + b"\n") + assert "longer than" in validate_pdb(str(path)) + + +def test_pdb_rejects_nul_byte(tmp_path): + path = _write(tmp_path, b"ATOM 1 CA ALA A 1\n\0ACDE\n") + assert "NUL byte" in validate_pdb(str(path)) + + +# ── mmCIF ────────────────────────────────────────────────────────────────────── + + +def _mmcif(atom_rows: int) -> bytes: + head = ( + "data_1SUO\n" + "#\n" + "_cell.length_a 100.0\n" + "_cell.length_b 100.0\n" + "loop_\n" + "_atom_site.group_PDB\n" + "_atom_site.id\n" + "_atom_site.type_symbol\n" + "_atom_site.label_atom_id\n" + "_atom_site.label_comp_id\n" + ) + rows = "".join(f"ATOM {i} N N ALA\n" for i in range(1, atom_rows + 1)) + return (head + rows + "#\nloop_\n_entity.id\n1\n").encode() + + +def test_mmcif_realistic_file_passes(tmp_path): + path = _write(tmp_path, _mmcif(100)) + assert validate_mmcif(str(path)) is None + + +def test_mmcif_accepts_second_data_block_without_atoms(tmp_path): + # A .cif used for restraints/topology may have no _atom_site loop at all. + path = _write(tmp_path, b"data_restraints\n_chem_comp.id 'ALA'\n") + assert validate_mmcif(str(path)) is None + + +def test_mmcif_rejects_plain_text(tmp_path): + path = _write(tmp_path, b"this is not a cif\n" * 50) + assert "data_ block or _atom_site." in validate_mmcif(str(path)) + + +def test_mmcif_rejects_too_many_atoms(tmp_path): + path = _write(tmp_path, _mmcif(MAX_CIF_ATOMS + 1)) + assert f"more than {MAX_CIF_ATOMS} atoms" in validate_mmcif(str(path)) + + +def test_mmcif_rejects_overlong_record(tmp_path): + path = _write(tmp_path, b"data_x\n" + b"_atom_site.id " + b"Y" * MAX_CIF_RECORD_LENGTH + b"\n") + assert "longer than" in validate_mmcif(str(path)) + + +def test_mmcif_rejects_nul_byte(tmp_path): + path = _write(tmp_path, b"data_x\n\x00") + assert "NUL byte" in validate_mmcif(str(path)) + + +# ── JSON ─────────────────────────────────────────────────────────────────────── + + +def test_json_accepts_valid_documents(tmp_path): + for doc in ("{}", "[]", '"plain string"', "42", '[{"a": [1, 2, {"b": null}]}]'): + path = _write(tmp_path, doc.encode()) + assert validate_json(str(path)) is None, doc + + +def test_json_rejects_invalid_json(tmp_path): + path = _write(tmp_path, b'{"contigs": ["A1-10", }') + assert "not appear to be valid JSON" in validate_json(str(path)) + + +def test_json_rejects_too_many_nodes(tmp_path): + # A flat list of MAX_JSON_NODES + 1 elements is well-formed JSON but too big. + path = _write(tmp_path, ("[" + "0," * MAX_JSON_NODES + "0]").encode()) + assert f"more than {MAX_JSON_NODES} values" in validate_json(str(path)) + + +def test_json_rejects_deep_nesting(tmp_path): + doc = "[" * (MAX_JSON_DEPTH + 1) + "0" + "]" * (MAX_JSON_DEPTH + 1) + path = _write(tmp_path, doc.encode()) + assert f"nested deeper than {MAX_JSON_DEPTH}" in validate_json(str(path)) + + +def test_json_accepts_nesting_at_the_cap(tmp_path): + # The deepest value of MAX_JSON_DEPTH containers sits at depth + # MAX_JSON_DEPTH and must pass. + doc = "[" * (MAX_JSON_DEPTH - 1) + "0" + "]" * (MAX_JSON_DEPTH - 1) + path = _write(tmp_path, doc.encode()) + assert validate_json(str(path)) is None + + +def test_json_rejects_non_utf8(tmp_path): + path = _write(tmp_path, b'{"name": "\xff\xfe"}') + assert "not valid UTF-8" in validate_json(str(path)) + + +def test_json_rejects_nul_byte(tmp_path): + path = _write(tmp_path, b'{"a": 1}\x00') + assert "NUL byte" in validate_json(str(path)) + + +# ── extension dispatch ───────────────────────────────────────────────────────── + + +def test_dispatch_routes_by_extension(tmp_path): + pdb = _write(tmp_path, b"ATOM 1 CA ALA A 1\n", "model.pdb") + assert validate_input_file(str(pdb), "model.pdb") is None + assert validate_input_file(str(pdb), "sub/dir/model.pdb") is None + fasta = _write(tmp_path, b"not fasta\n", "seqs.fasta") + assert validate_input_file(str(fasta), "seqs.fasta") is not None + assert validate_input_file(str(pdb), "model.txt") is None # no validator -> pass + + +def test_a3m_dispatched_by_extension(tmp_path): + path = _write(tmp_path, b">h\nACDEfghi\n", "msa.a3m") + assert validate_input_file(str(path), "msa.a3m") is None + + +# ── route level: the security fix ────────────────────────────────────────────── + + +def _pdb_task_module(monkeypatch, tmp_path): + """Load the app with a registered non-GREMLIN .pdb task type.""" + module = _load_pssm_module(monkeypatch, tmp_path, extra_env={"RUNNER_UID": "1234", "RUNNER_GID": "5678"}) + base_type, runner = module.task_runtime._get_task_type("gremlin") + module.task_runtime._register_tt( + replace( + base_type, + name="pdb_only", + display_name="PDB Only", + input_extension=".pdb", + input_extensions=(".pdb",), + primary_input_extensions=(".pdb",), + input_label="PDB file", + params=(), + ), + runner, + ) + return module + + +def test_upload_gzip_disguised_as_pdb_rejected(monkeypatch, tmp_path): + """Non-GREMLIN inputs are content-checked: a gzip bomb named .pdb is refused.""" + module = _pdb_task_module(monkeypatch, tmp_path) + client = module.app.test_client() + auth_header = _test_client_auth(module) + payload = gzip.compress(b"ATOM 1 CA ALA A 1\n" * 100) + + response = client.post( + "/compute/api/post", + data={"task_type": "pdb_only", "file": (io.BytesIO(payload), "model.pdb")}, + headers=auth_header, + ) + assert response.status_code == 400, response.get_data(as_text=True) + + +def test_upload_text_without_pdb_records_rejected(monkeypatch, tmp_path): + """Plain text (not caught by the binary sniff) named .pdb is refused.""" + module = _pdb_task_module(monkeypatch, tmp_path) + client = module.app.test_client() + auth_header = _test_client_auth(module) + + response = client.post( + "/compute/api/post", + data={"task_type": "pdb_only", "file": (io.BytesIO(b"this is not a pdb\n" * 50), "model.pdb")}, + headers=auth_header, + ) + assert response.status_code == 400, response.get_data(as_text=True) + assert "ATOM, HETATM, or END" in response.json["error"] + + +def test_upload_bad_fasta_for_gremlin_rejected(monkeypatch, tmp_path): + module = _load_pssm_module(monkeypatch, tmp_path, extra_env={"RUNNER_UID": "1234", "RUNNER_GID": "5678"}) + client = module.app.test_client() + auth_header = _test_client_auth(module) + + response = client.post( + "/compute/api/post", + data={"file": (io.BytesIO(b"ACDE\n>h\nACDE\n"), "seqs.fasta")}, + headers=auth_header, + ) + assert response.status_code == 400, response.get_data(as_text=True) + assert "start with a '>' header" in response.json["error"] + + +def test_upload_valid_pdb_accepted(monkeypatch, tmp_path): + module = _pdb_task_module(monkeypatch, tmp_path) + client = module.app.test_client() + auth_header = _test_client_auth(module) + + class _Queued: + id = "queued-pdb" + + monkeypatch.setattr(module.run_compute_task, "apply_async", lambda *args, **kwargs: _Queued()) + response = client.post( + "/compute/api/post", + data={"task_type": "pdb_only", "file": (io.BytesIO(b"ATOM 1 CA ALA A 1\n"), "model.pdb")}, + headers=auth_header, + ) + assert response.status_code == 302, response.get_json() diff --git a/server/tests/test_process_isolation.py b/server/tests/test_process_isolation.py index b2031b7d3..d4d3f8c46 100644 --- a/server/tests/test_process_isolation.py +++ b/server/tests/test_process_isolation.py @@ -32,11 +32,11 @@ def _run_restart_script( docker_log = tmp_path / "docker.log" docker = fake_bin / "docker" docker.write_text( - '#!/usr/bin/env bash\n' + "#!/usr/bin/env bash\n" 'printf "%s\\n" "$*" >> "${DOCKER_LOG}"\n' 'if [[ "$*" == *" ps --status running --services"* ]]; then\n' ' printf "redis\\nweb\\ngateway\\nmaintenance\\nworker\\n"\n' - 'fi\n', + "fi\n", encoding="utf-8", ) docker.chmod(0o755) @@ -138,7 +138,9 @@ def test_restart_modes_choose_build_or_pull(tmp_path): assert dev_result.returncode == 0, dev_result.stderr assert "Bootstrap admin credentials written to:" in dev_result.stdout assert "password:" not in dev_result.stdout - assert any("build --build-arg" in command and "revodesign-revocompute-runner" in command for command in dev_commands) + assert any( + "build --build-arg" in command and "revodesign-revocompute-runner" in command for command in dev_commands + ) assert any("build web worker" in command for command in dev_commands) assert not any(" pull " in command for command in dev_commands) assert any("up --no-build -d redis web gateway maintenance worker" in command for command in dev_commands) @@ -262,9 +264,7 @@ def test_up_generates_bootstrap_password_for_empty_user_database(tmp_path): assert "password:" not in result.stdout assert any("up -d redis web gateway maintenance worker" in command for command in commands) assert any('exec -T web sh -c test -w "$1" && test -x "$1"' in command for command in commands) - assert any( - "exec -T gateway sh -c test -r /srv/results && test -x /srv/results" in command for command in commands - ) + assert any("exec -T gateway sh -c test -r /srv/results && test -x /srv/results" in command for command in commands) assert any("exec -T web python -c" in command and "BEGIN IMMEDIATE" in command for command in commands) assert (root / "tasks" / "results").is_dir() @@ -298,7 +298,9 @@ def test_reset_passwd_rotates_hash_invalidates_tokens_and_writes_protected_crede ).fetchone() assert check_password_hash(password_hash, password) assert token_version == 1 - backup_line = next(line for line in result.stdout.splitlines() if line.startswith("Auth database backup written to:")) + backup_line = next( + line for line in result.stdout.splitlines() if line.startswith("Auth database backup written to:") + ) backup_db = Path(backup_line.removeprefix("Auth database backup written to: ").split(" ", 1)[0]) assert backup_db.is_file() assert backup_db.stat().st_mode & 0o777 == 0o600 @@ -406,7 +408,9 @@ def test_global_slurm_executor_selects_override_without_cli_backend_flag(tmp_pat assert result.returncode == 0, result.stderr slurm_override = str(Path(REPO_DIR) / "server" / "docker-compose.slurm.yml") - assert any(slurm_override in command and "up -d redis web gateway maintenance worker" in command for command in commands) + assert any( + slurm_override in command and "up -d redis web gateway maintenance worker" in command for command in commands + ) def test_missing_global_slurm_family_image_is_rejected_before_shutdown(tmp_path): @@ -476,7 +480,7 @@ def test_compose_isolates_worker_auth_and_web_docker_socket(): assert "AUTH_SECRET_KEY" not in compose task_env = compose.split("x-task-env:", 1)[1].split("x-web-auth-env:", 1)[0] web_auth_env = compose.split("x-web-auth-env:", 1)[1].split("x-maintenance-env:", 1)[0] - maintenance_env = compose.split("x-maintenance-env:", 1)[1].split("x-docker-socket-access:", 1)[0] + maintenance_env = compose.split("x-maintenance-env:", 1)[1].split("services:", 1)[0] gateway = compose.split(" gateway:", 1)[1].split(" web:", 1)[0] web = compose.split(" web:", 1)[1].split(" maintenance:", 1)[0] maintenance = compose.split(" maintenance:", 1)[1].split(" worker:", 1)[0] @@ -519,7 +523,22 @@ def test_compose_isolates_worker_auth_and_web_docker_socket(): assert "web-auth-env" not in worker assert "/var/lib/revodesign-auth" not in worker assert "revocompute.task_runtime.celery" in worker - assert "/var/run/docker.sock:/var/run/docker.sock" in worker + # Executor-neutral base worker: the Docker socket lives only in + # docker-compose.docker.yml (compose concatenates volume lists, so a + # socket defined here could never be removed by the SLURM override). + assert "/var/run/docker.sock" not in worker + + +def test_docker_executor_override_holds_socket_and_slurm_override_does_not(): + docker_override = (Path(REPO_DIR) / "server" / "docker-compose.docker.yml").read_text(encoding="utf-8") + slurm_override = (Path(REPO_DIR) / "server" / "docker-compose.slurm.yml").read_text(encoding="utf-8") + + assert "/var/run/docker.sock:/var/run/docker.sock" in docker_override + assert "DOCKER_GID" in docker_override + assert "group_add" in docker_override + assert "/var/run/docker.sock" not in slurm_override + assert "REDIS_PASSWORD" in slurm_override + assert "127.0.0.1:6380:6379" in slurm_override def test_nginx_result_location_is_internal_and_read_only(): diff --git a/server/tests/test_resource_policy.py b/server/tests/test_resource_policy.py index 8f71d798e..21c7113f0 100644 --- a/server/tests/test_resource_policy.py +++ b/server/tests/test_resource_policy.py @@ -95,9 +95,7 @@ def test_slurm_constraint_expressions_are_preserved_without_whitespace_or_option def test_resource_snapshot_round_trip_is_strict(): - resources = _resolve( - {"cpus": 8, "memory": "16G", "slurm_partition": "normal"}, gpu=True - ) + resources = _resolve({"cpus": 8, "memory": "16G", "slurm_partition": "normal"}, gpu=True) restored = ResolvedResources.from_snapshot(resources.public_dict()) assert restored.public_dict() == resources.public_dict() broken = resources.public_dict() @@ -122,15 +120,11 @@ def test_manage_database_migrates_canonical_columns_and_resolves_policy(tmp_path try: columns = {row[1] for row in database._conn.execute("PRAGMA table_info(task_type_config)")} assert {"cpus", "memory"}.issubset(columns) - resources = database.resolve_task_resources( - "gremlin", requires_gpu=False, default_timeout_seconds=3600 - ) + resources = database.resolve_task_resources("gremlin", requires_gpu=False, default_timeout_seconds=3600) assert resources.cpus == 6 assert resources.memory == "12G" database.task_type_upsert("gremlin", cpus=10, memory="20G") - updated = database.resolve_task_resources( - "gremlin", requires_gpu=False, default_timeout_seconds=3600 - ) + updated = database.resolve_task_resources("gremlin", requires_gpu=False, default_timeout_seconds=3600) assert updated.cpus == 10 assert updated.memory == "20G" finally: diff --git a/server/tests/test_runner_script_static.py b/server/tests/test_runner_script_static.py index 41791bb30..2226e89e7 100644 --- a/server/tests/test_runner_script_static.py +++ b/server/tests/test_runner_script_static.py @@ -6,8 +6,8 @@ import json import os -from pathlib import Path import subprocess +from pathlib import Path RUNNER_SCRIPT = Path(__file__).resolve().parents[1] / "docker" / "runners" / "pssm_gremlin" / "run.sh" OPENDDE_RUNNER_SCRIPT = Path(__file__).resolve().parents[1] / "docker" / "runners" / "opendde" / "run.sh" @@ -99,8 +99,8 @@ def test_opendde_runner_preserves_read_only_nested_snapshot(tmp_path): auxiliary.parent.mkdir(parents=True) output_dir.mkdir() bin_dir.mkdir() - input_file.write_text('{}\n') - auxiliary.write_text('{}\n') + input_file.write_text("{}\n") + auxiliary.write_text("{}\n") _write_fake_opendde(bin_dir) env = os.environ.copy() @@ -118,7 +118,7 @@ def test_opendde_runner_preserves_read_only_nested_snapshot(tmp_path): assert (output_dir / "model.cif").read_text() == "data_model\n" assert (output_dir / "task_finished").is_file() assert not (input_file.parent / "job-update-msa.json").exists() - assert auxiliary.read_text() == '{}\n' + assert auxiliary.read_text() == "{}\n" def test_opendde_runner_uses_task_private_template_cache(tmp_path): @@ -136,8 +136,8 @@ def test_opendde_runner_uses_task_private_template_cache(tmp_path): source_cache.mkdir(parents=True) (database_root / "checkpoint").mkdir() (database_root / "checkpoint" / "opendde.pt").write_text("checkpoint\n") - input_file.write_text('{}\n') - auxiliary.write_text('{}\n') + input_file.write_text("{}\n") + auxiliary.write_text("{}\n") _write_fake_opendde(bin_dir) env = os.environ.copy() @@ -168,8 +168,8 @@ def test_opendde_runner_rejects_zero_exit_without_results(tmp_path): auxiliary.parent.mkdir(parents=True) output_dir.mkdir() bin_dir.mkdir() - input_file.write_text('{}\n') - auxiliary.write_text('{}\n') + input_file.write_text("{}\n") + auxiliary.write_text("{}\n") _write_fake_opendde(bin_dir) env = os.environ.copy() @@ -199,8 +199,8 @@ def test_opendde_runner_rejects_error_and_msa_intermediates(tmp_path): auxiliary.parent.mkdir(parents=True) output_dir.mkdir() bin_dir.mkdir() - input_file.write_text('{}\n') - auxiliary.write_text('{}\n') + input_file.write_text("{}\n") + auxiliary.write_text("{}\n") _write_fake_opendde(bin_dir) env = os.environ.copy() @@ -240,9 +240,7 @@ def test_ligandmpnn_runner_omits_blank_optional_cli_values(tmp_path): env.update( { "TASK_TYPE": "ligandmpnn", - "TASK_PARAMS": json.dumps( - {"seed": "", "batch_size": 2, "verbose": 0, "chains_to_design": ""} - ), + "TASK_PARAMS": json.dumps({"seed": "", "batch_size": 2, "verbose": 0, "chains_to_design": ""}), "LIGANDMPNN_PATH": str(ligand_root), "CAPTURE_ARGV": str(capture), } @@ -290,7 +288,7 @@ def test_esm_image_installs_the_esm1v_csv_dependency(): def test_easifa_image_requires_the_installed_prediction_cli(): dockerfile = (SERVER_ROOT / "docker" / "runners" / "easifa" / "Dockerfile").read_text() - assert '/opt/easifa-env/bin/python -m pip install' in dockerfile + assert "/opt/easifa-env/bin/python -m pip install" in dockerfile assert '/opt/easifa-env/bin/python -c "import easifa_core"' in dockerfile assert "test -x /opt/easifa-env/bin/easifa-predict" in dockerfile assert 'cpp_extension.load("torch_ext"' in dockerfile @@ -326,8 +324,7 @@ def test_thermompnn_uses_preprovisioned_read_only_weights(): assert 'XDG_DATA_HOME: "/mnt/db/weights/thermompnn"' in runner assert "ThermoMPNN-ens1.ckpt ThermoMPNN-D-ens1.ckpt" in script assert ( - 'THERMOMPNN_VANILLA_WEIGHT_DIR: ' - '"/mnt/db/weights/thermompnn/ProteinMPNN/vanilla/vanilla_model_weights"' + "THERMOMPNN_VANILLA_WEIGHT_DIR: " '"/mnt/db/weights/thermompnn/ProteinMPNN/vanilla/vanilla_model_weights"' ) in runner assert "ThermoMPNN ProteinMPNN backbone checkpoint is missing" in script assert "runtime downloads are disabled" in script @@ -336,20 +333,106 @@ def test_thermompnn_uses_preprovisioned_read_only_weights(): def test_ligandmpnn_runner_uses_a_mounted_absolute_checkpoint(): script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text() - assert 'checkpoint_ligand_mpnn' in script - assert 'ligandmpnn_v_32_010_25.pt' in script - assert 'LIGANDMPNN_MODEL_PARAMS' in script + assert "checkpoint_ligand_mpnn" in script + assert "ligandmpnn_v_32_010_25.pt" in script + assert "LIGANDMPNN_MODEL_PARAMS" in script def test_slurm_runner_limits_threaded_libraries_to_the_allocation(): script = (SERVER_ROOT / "revocompute" / "job" / "runners" / "slurm_runner.py").read_text() - assert 'SLURM_CPUS_PER_TASK' in script - assert 'APPTAINERENV_OMP_NUM_THREADS' in script - assert 'APPTAINERENV_MKL_NUM_THREADS' in script - assert 'APPTAINERENV_OPENBLAS_NUM_THREADS' in script - assert 'APPTAINERENV_NPROC' in script - assert 'APPTAINERENV_GREMLIN_CALC_CPU_NUM' in script - assert 'APPTAINERENV_VECLIB_MAXIMUM_THREADS' in script - assert 'APPTAINERENV_TF_NUM_INTRAOP_THREADS' in script - assert 'cmd += \' -j "${allocated_cpus}"\'' in script + assert "SLURM_CPUS_PER_TASK" in script + assert "APPTAINERENV_OMP_NUM_THREADS" in script + assert "APPTAINERENV_MKL_NUM_THREADS" in script + assert "APPTAINERENV_OPENBLAS_NUM_THREADS" in script + assert "APPTAINERENV_NPROC" in script + assert "APPTAINERENV_GREMLIN_CALC_CPU_NUM" in script + assert "APPTAINERENV_VECLIB_MAXIMUM_THREADS" in script + assert "APPTAINERENV_TF_NUM_INTRAOP_THREADS" in script + assert "cmd += ' -j \"${allocated_cpus}\"'" in script + + +PRIME_DIR = SERVER_ROOT / "docker" / "runners" / "prime" + + +def test_prime_runner_vendors_model_code_instead_of_trust_remote_code(): + script = (PRIME_DIR / "run.sh").read_text(encoding="utf-8") + dockerfile = (PRIME_DIR / "Dockerfile").read_text(encoding="utf-8") + + assert "trust_remote_code=True" not in script + assert script.count("trust_remote_code=False") == 4 # tokenizer + model in both branches + assert ( + "COPY --chown=${RUNNER_UID}:${RUNNER_GID} ./docker/runners/prime/vendor/ /opt/prime_model_code/" in dockerfile + ) + assert "PRIME_VENDOR_DIR" in script + assert "sys.path.insert(0, str(code_dir))" in script + assert "vendor/README.md" in script + assert (PRIME_DIR / "vendor" / "README.md").is_file() + assert (PRIME_DIR / "vendor" / "placeholder.txt").is_file() + + +def _write_fake_prime_model(tmp_path, auto_map=True) -> Path: + model_dir = tmp_path / "weights" / "ProPrime_650M_OGT_Prediction-91490f95c707" + model_dir.mkdir(parents=True) + config = {"model_type": "prime"} + if auto_map: + config["auto_map"] = { + "AutoConfig": ["modeling_prime.PrimeConfig"], + "AutoModel": ["modeling_prime.PrimeForPrediction"], + "AutoTokenizer": ["tokenization_prime.PrimeTokenizer"], + } + (model_dir / "config.json").write_text(json.dumps(config), encoding="utf-8") + return model_dir + + +def test_prime_runner_fails_closed_without_vendored_model_code(tmp_path): + model_dir = _write_fake_prime_model(tmp_path) + input_file = tmp_path / "input.fasta" + input_file.write_text(">test\nACDEFGHIK\n", encoding="utf-8") + output_dir = tmp_path / "outputs" + + env = os.environ.copy() + env["PRIME_MODEL_DIR"] = str(model_dir) + env["PRIME_VENDOR_DIR"] = str(tmp_path / "vendor") + completed = subprocess.run( + ["bash", str(PRIME_DIR / "run.sh"), "ogt", "-i", str(input_file), "-o", str(output_dir)], + env=env, + check=False, + capture_output=True, + text=True, + ) + + assert completed.returncode != 0 + assert "PRIME vendored model code missing" in completed.stderr + assert "vendor/README.md" in completed.stderr + assert "trust_remote_code" not in completed.stderr + assert not (output_dir / "task_finished").exists() + + +def test_prime_runner_rejects_weights_manifest_mismatch(tmp_path): + model_dir = _write_fake_prime_model(tmp_path) + (model_dir / "weights.bin").write_bytes(b"checkpoint") + input_file = tmp_path / "input.fasta" + input_file.write_text(">test\nACDEFGHIK\n", encoding="utf-8") + output_dir = tmp_path / "outputs" + vendor_dir = tmp_path / "vendor" + vendor_dir.mkdir() + (vendor_dir / "manifest.sha256").write_text( + "0" * 64 + " ProPrime_650M_OGT_Prediction-91490f95c707/weights.bin\n", + encoding="utf-8", + ) + + env = os.environ.copy() + env["PRIME_MODEL_DIR"] = str(model_dir) + env["PRIME_VENDOR_DIR"] = str(vendor_dir) + completed = subprocess.run( + ["bash", str(PRIME_DIR / "run.sh"), "ogt", "-i", str(input_file), "-o", str(output_dir)], + env=env, + check=False, + capture_output=True, + text=True, + ) + + assert completed.returncode != 0 + assert "weights integrity check FAILED" in completed.stderr + assert not (output_dir / "task_finished").exists() diff --git a/server/tests/test_security_hardening.py b/server/tests/test_security_hardening.py new file mode 100644 index 000000000..f6dc5b068 --- /dev/null +++ b/server/tests/test_security_hardening.py @@ -0,0 +1,310 @@ +# Copyright (c) 2026 The REvoDesign Developers. +# Distributed under the terms of the GNU General Public License v3.0. +# SPDX-License-Identifier: GPL-3.0-only + +"""Security-hardening tests: API key digests, rate limiting, CAPTCHA nonces. + +Redis is optional at runtime — these tests cover both paths (a throwaway +local ``redis-server``, and the in-memory fallback when Redis is down). The +Redis client is cached per process, so every test that changes ``REDIS_URL`` +must call ``get_redis.cache_clear()`` first. +""" + +from __future__ import annotations + +import os +import re +import shutil +import socket +import sqlite3 +import subprocess +import time +from pathlib import Path + +import pytest +import redis +from flask import Flask +from revocompute.auth import UserDatabase, _used_captcha_nonces, generate_captcha, validate_captcha +from revocompute.ratelimit import rate_limit +from revocompute.redis_util import get_redis +from werkzeug.security import generate_password_hash + + +@pytest.fixture(autouse=True) +def _reset_redis_probe(): + """Re-probe Redis in every test — the client is cached per process.""" + yield + get_redis.cache_clear() + _used_captcha_nonces.clear() + + +# --------------------------------------------------------------------------- +# API keys — sha256 digest storage, single indexed lookup +# --------------------------------------------------------------------------- + + +def test_api_key_generate_and_validate(tmp_path): + """A generated key validates; wrong keys, prefixes, and empties do not.""" + db = UserDatabase(str(tmp_path / "users.sqlite3")) + user = db.create_user("alice", "alice@example.com", "password123") + key = db.generate_api_key(user["id"]) + assert key.startswith("revodesign_") + assert key != user["api_key_digest"] # only the digest is stored + + got = db.validate_api_key(key) + assert got is not None + assert got["username"] == "alice" + + assert db.validate_api_key("revodesign_" + "0" * 64) is None # wrong key + assert db.validate_api_key("not-an-api-key") is None # no prefix + assert db.validate_api_key("") is None + assert db.validate_api_key(key[:-1]) is None # truncated + db.revoke_api_key(user["id"]) + assert db.validate_api_key(key) is None # revoked key is dead + + +def test_api_key_validation_with_several_users(tmp_path): + """Validation resolves the right user among several, by digest lookup.""" + db = UserDatabase(str(tmp_path / "users.sqlite3")) + keys: dict[str, str] = {} + for i, name in enumerate(("alice", "bob", "carol", "dave")): + user = db.create_user(name, f"{name}@example.com", f"password{i}123") + keys[name] = db.generate_api_key(user["id"]) + + for name, key in keys.items(): + got = db.validate_api_key(key) + assert got is not None and got["username"] == name + + # valid prefix, wrong content — digest matches nothing + assert db.validate_api_key(keys["alice"] + "ff") is None + + # the digest column is actually indexed — validation is one lookup + with db.engine.connect() as conn: + indexes = {row[1] for row in conn.exec_driver_sql("PRAGMA index_list(users)")} + assert "ix_users_api_key_digest" in indexes + + +def test_migration_from_old_api_key_hash_schema(tmp_path): + """A DB created with the old api_key_hash schema gains api_key_digest. + + The old werkzeug KDF hashes are one-way — existing keys become invalid + by design; the column is added, indexed, and the user data survives. + """ + path = tmp_path / "legacy.sqlite3" + old_key = "revodesign_" + os.urandom(32).hex() + old_kdf_hash = generate_password_hash(old_key) + conn = sqlite3.connect(path) + conn.execute( + """ + CREATE TABLE users ( + id INTEGER PRIMARY KEY, + username VARCHAR(128) NOT NULL UNIQUE, + email VARCHAR(256) NOT NULL UNIQUE, + password_hash VARCHAR(256) NOT NULL, + email_verified BOOLEAN NOT NULL DEFAULT 0, + created_at FLOAT NOT NULL, + api_key_hash VARCHAR(256), + full_name VARCHAR(128), + affiliation VARCHAR(256), + position VARCHAR(64), + pi_name VARCHAR(128), + terms_agreed BOOLEAN NOT NULL DEFAULT 0, + registration_status VARCHAR(32) NOT NULL DEFAULT 'email_sent', + user_status VARCHAR(32) NOT NULL DEFAULT 'pending', + approved_by INTEGER, + approved_at FLOAT, + deleted BOOLEAN NOT NULL DEFAULT 0, + role VARCHAR(32) NOT NULL DEFAULT 'user', + admin_notified BOOLEAN NOT NULL DEFAULT 0, + verification_resend_count INTEGER NOT NULL DEFAULT 0, + verification_resend_at FLOAT, + registration_ip VARCHAR(45), + registration_country VARCHAR(8), + token_version INTEGER NOT NULL DEFAULT 0, + allow_gpu_use BOOLEAN NOT NULL DEFAULT 0 + ) + """ + ) + conn.execute( + "INSERT INTO users (username, email, password_hash, email_verified, created_at, api_key_hash)" + " VALUES (?, ?, ?, 1, ?, ?)", + ("legacy", "legacy@example.com", generate_password_hash("password123"), time.time(), old_kdf_hash), + ) + conn.commit() + conn.close() + + db = UserDatabase(str(path)) # runs the migration + + with db.engine.connect() as c: + cols = {row[1] for row in c.exec_driver_sql("PRAGMA table_info(users)")} + assert "api_key_digest" in cols # column added + assert "api_key_hash" in cols # old column left in place + indexes = {row[1] for row in c.exec_driver_sql("PRAGMA index_list(users)")} + assert "ix_users_api_key_digest" in indexes # migrated column indexed + + user = db.get_user_by_username("legacy") + assert user is not None and user["api_key_digest"] is None + # the old KDF hash was never a digest — the old key is invalid by design + assert db.validate_api_key(old_key) is None + + # the migrated DB is fully functional for new keys + new_key = db.generate_api_key(user["id"]) + assert db.validate_api_key(new_key) is not None + + +# --------------------------------------------------------------------------- +# Rate limiting — Redis path and in-memory fallback +# --------------------------------------------------------------------------- + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@pytest.fixture +def live_redis(monkeypatch, tmp_path): + """Start a throwaway redis-server and point REDIS_URL at it. + + Skips cleanly when the redis-server binary is absent. + """ + if shutil.which("redis-server") is None: + pytest.skip("redis-server binary not available") + # redis-py 8 speaks RESP3 (HELLO); pre-6.0 servers do not know the + # command. Production pins redis:7.2-alpine — this skip only covers + # ancient local binaries used as a live test double. + version_out = subprocess.run(["redis-server", "--version"], capture_output=True, text=True).stdout + version_match = re.search(r"v=(\d+)", version_out) + if version_match and int(version_match.group(1)) < 6: + pytest.skip("local redis-server predates RESP3 HELLO; redis-py 8 requires redis >= 6") + port = _free_port() + proc = subprocess.Popen( + [ + "redis-server", + "--port", + str(port), + "--save", + "", + "--appendonly", + "no", + "--bind", + "127.0.0.1", + "--dir", + str(tmp_path), + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + client = None + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + try: + client = redis.Redis(host="127.0.0.1", port=port, socket_timeout=0.5) + client.ping() + break + except Exception: + time.sleep(0.05) + if client is None: + proc.terminate() + pytest.fail("redis-server did not become ready") + monkeypatch.setenv("REDIS_URL", f"redis://127.0.0.1:{port}/0") + get_redis.cache_clear() + yield client + proc.terminate() + proc.wait(timeout=10) + get_redis.cache_clear() + + +def _limited_app(max_requests: int, window_seconds: int, calls: list) -> Flask: + """Return a Flask app whose POST /login is rate limited (fresh state).""" + app = Flask(__name__) + + @app.route("/login", methods=["POST"]) + @rate_limit(max_requests=max_requests, window_seconds=window_seconds) + def login(): + calls.append(1) + return "ok", 200 + + return app + + +def test_rate_limit_fallback_without_redis(monkeypatch): + """No reachable Redis → in-memory per-worker limiter still 429s.""" + monkeypatch.setenv("REDIS_URL", "redis://127.0.0.1:1/0") # nothing listens + get_redis.cache_clear() + assert get_redis() is None + + calls: list = [] + client = _limited_app(max_requests=2, window_seconds=60, calls=calls).test_client() + assert client.post("/login").status_code == 200 + assert client.post("/login").status_code == 200 + resp = client.post("/login") + assert resp.status_code == 429 + assert resp.json["error"] == "Too many requests" + assert resp.json["retry_after_seconds"] >= 1 + assert len(calls) == 2 # the 429 never reached the endpoint + + +def test_rate_limit_redis_path(live_redis): + """With Redis up: fixed-window counter, 429 past the limit with TTL.""" + calls: list = [] + app = _limited_app(max_requests=3, window_seconds=60, calls=calls) + client = app.test_client() + for _ in range(3): + assert client.post("/login").status_code == 200 + resp = client.post("/login") + assert resp.status_code == 429 + assert resp.json["retry_after_seconds"] >= 1 + assert len(calls) == 3 + + # the fixed-window key exists in Redis with a live TTL + view = client.application.view_functions["login"] + key = f"{view.__wrapped__.__module__}.{view.__wrapped__.__qualname__}:127.0.0.1" + assert live_redis.get(key) is not None + assert 0 < live_redis.ttl(key) <= 60 + + +# --------------------------------------------------------------------------- +# CAPTCHA nonces — Redis-first, in-memory fallback +# --------------------------------------------------------------------------- + + +def _captcha_answer(question: str) -> int: + m = re.search(r"(\d+) \+ (\d+)", question) + assert m is not None, f"unparseable CAPTCHA question: {question!r}" + return int(m.group(1)) + int(m.group(2)) + + +def test_captcha_valid_then_replay_fails(live_redis): + """A correct answer passes once; the Redis nonce rejects the replay.""" + question, token = generate_captcha() + answer = str(_captcha_answer(question)) + assert validate_captcha(token, answer) is True + assert validate_captcha(token, answer) is False # replay + + +def test_captcha_wrong_answer_does_not_burn_nonce(live_redis): + """A wrong answer fails without consuming the nonce — retry works.""" + question, token = generate_captcha() + assert validate_captcha(token, "999999") is False + assert validate_captcha(token, str(_captcha_answer(question))) is True + + +def test_captcha_tampered_token_rejected(live_redis): + """A token with a broken signature is rejected outright.""" + _, token = generate_captcha() + tampered = token[:-6] + ("0" if token[-6] != "0" else "1") + token[-5:] + assert validate_captcha(tampered, "1") is False + + +def test_captcha_redis_down_fallback(monkeypatch): + """Redis down → per-process nonce store: passes once, replay fails.""" + monkeypatch.setenv("REDIS_URL", "redis://127.0.0.1:1/0") + get_redis.cache_clear() + assert get_redis() is None + + question, token = generate_captcha() + answer = str(_captcha_answer(question)) + assert validate_captcha(token, answer) is True + assert validate_captcha(token, answer) is False # replay in memory diff --git a/server/tests/test_slurm_runner.py b/server/tests/test_slurm_runner.py index 2cb41eed2..9988f16e2 100644 --- a/server/tests/test_slurm_runner.py +++ b/server/tests/test_slurm_runner.py @@ -141,10 +141,17 @@ def test_build_srun_args_gpu_task_uses_configured_gres(tmp_path): class _ManageDb: def resolve_task_resources(self, tool, *, requires_gpu, default_timeout_seconds): return ResolvedResources( - cpus=1, memory="4G", max_runtime_seconds=3600, - partition=None, gres="gpu:a100:1", - nodes=1, ntasks=1, qos=None, account=None, - constraint=None, exclusive=False, + cpus=1, + memory="4G", + max_runtime_seconds=3600, + partition=None, + gres="gpu:a100:1", + nodes=1, + ntasks=1, + qos=None, + account=None, + constraint=None, + exclusive=False, requires_gpu=True, sources={"gres": "task:slurm_gres"}, ) @@ -179,12 +186,16 @@ def test_render_apptainer_binds_and_env(tmp_path): script = job._render_wrapper() assert "apptainer run --nv" in script assert "--bind" in script + # Strong containment: private /tmp + $HOME tmpfs, no host env or mounts + # beyond the explicit binds below. + assert "--containall" in script + assert "--cleanenv" in script assert "/mnt/revocompute/tester/inputs" in script assert "/mnt/revocompute/tester/outputs" in script assert "export APPTAINERENV_TASK_ID=" in script assert "export APPTAINERENV_TASK_TYPE=" in script - assert 'export APPTAINERENV_TASK_PARAMS=' in script - assert 'export APPTAINERENV_TASK_INPUTS=' in script + assert "export APPTAINERENV_TASK_PARAMS=" in script + assert "export APPTAINERENV_TASK_INPUTS=" in script assert '{"iter":"100"}' in script assert "/opt/images/gremlin_v1.sif" in script @@ -193,14 +204,14 @@ def test_render_apptainer_omits_nvidia_flag_for_cpu_task(tmp_path): job = SlurmJob("task-1", _make_task_type(gpus=False), _make_runner(), _make_entities(), str(tmp_path / "out")) script = job._render_wrapper() assert "apptainer run --nv" not in script - assert "apptainer run --bind" in script + assert "apptainer run --containall --cleanenv --bind" in script def test_render_apptainer_keeps_parameters_in_typed_json_env(tmp_path): job = SlurmJob("task-1", _make_task_type(), _make_runner(), _make_entities(), str(tmp_path / "out")) script = job._render_wrapper() assert "-r 100" not in script - assert 'export APPTAINERENV_TASK_PARAMS=' in script + assert "export APPTAINERENV_TASK_PARAMS=" in script assert '"iter":"100"' in script diff --git a/server/tests/test_task_runtime_hardening.py b/server/tests/test_task_runtime_hardening.py new file mode 100644 index 000000000..5af7eaa4c --- /dev/null +++ b/server/tests/test_task_runtime_hardening.py @@ -0,0 +1,99 @@ +# Copyright (c) 2026 The REvoDesign Developers. +# Distributed under the terms of the GNU General Public License v3.0. +# SPDX-License-Identifier: GPL-3.0-only + +"""Security hardening for task_runtime: symlink-aware path containment and +post-completion workspace cleanup.""" + +from __future__ import annotations + +import importlib +import os +import shutil +from dataclasses import replace +from pathlib import Path + +import pytest + +SERVER_DIR = Path(__file__).resolve().parent.parent + + +@pytest.fixture +def rt(monkeypatch, tmp_path): + """Import task_runtime with a self-contained server/config layout.""" + env_root = tmp_path / "server" + shutil.copytree(SERVER_DIR / "config", env_root / "config") + monkeypatch.setenv("SERVER_DIR", str(env_root)) + monkeypatch.setenv("CONFIG_DIR", str(env_root / "config")) + monkeypatch.setenv("RUNNER_UID", "1234") + monkeypatch.setenv("RUNNER_GID", "5678") + module = importlib.import_module("revocompute.task_runtime") + monkeypatch.setattr( + module, + "CONFIG", + replace(module.CONFIG, workspace_folder=str(env_root / "workspaces"), results_folder=str(env_root / "results")), + ) + return module + + +# -- symlink-aware containment ------------------------------------------------- + + +def test_safe_join_rejects_symlink_escape(rt, tmp_path): + base = tmp_path / "base" + outside = tmp_path / "outside" + base.mkdir() + outside.mkdir() + (outside / "secret").write_text("secret") + os.symlink(outside, base / "link") + + with pytest.raises(ValueError): + rt._safe_join(base, "link", "x") + + +def test_safe_join_rejects_dangling_symlink(rt, tmp_path): + base = tmp_path / "base" + base.mkdir() + os.symlink(tmp_path / "outside" / "not-there-yet", base / "dangling") + + with pytest.raises(ValueError): + rt._safe_join(base, "dangling", "x") + + +def test_safe_join_accepts_new_child_and_symlink_inside_base(rt, tmp_path): + base = tmp_path / "base" + base.mkdir() + (base / "real").mkdir() + + # Not-yet-existing paths are fine (lexical check covers them). + assert rt._safe_join(base, "a", "b") == str(base / "a" / "b") + # A symlink that stays inside the base is fine; the returned path stays + # lexical (the OS resolves the symlink) — the guarantee is containment. + assert rt._safe_join(base, "link", "f") == str(base / "link" / "f") + + +# -- workspace cleanup ---------------------------------------------------------- + + +def test_cleanup_task_workspace_removes_workspace_not_results(rt): + ws = rt.CONFIG.workspace_folder + res = rt.CONFIG.results_folder + md5 = "a" * 32 + (Path(ws) / "alice" / md5 / "inputs").mkdir(parents=True) + (Path(ws) / "alice" / md5 / "inputs" / "query.fasta").write_text(">t\nACDE\n") + result_dir = Path(res) / md5 + result_dir.mkdir(parents=True) + (result_dir / "manifest.json").write_text("{}") + + rt._cleanup_task_workspace({"username": "alice", "md5sum": md5}) + + assert not (Path(ws) / "alice" / md5).exists() + assert result_dir.exists() + assert (result_dir / "manifest.json").exists() + + +def test_cleanup_task_workspace_ignores_malformed_rows(rt): + # Missing username / md5sum / traversal usernames must never raise. + rt._cleanup_task_workspace({}) + rt._cleanup_task_workspace({"username": "", "md5sum": ""}) + rt._cleanup_task_workspace({"username": "../evil", "md5sum": "b" * 32}) diff --git a/server/tests/test_task_type_registry.py b/server/tests/test_task_type_registry.py index ee41eeb50..8c0d8f450 100644 --- a/server/tests/test_task_type_registry.py +++ b/server/tests/test_task_type_registry.py @@ -6,8 +6,8 @@ from __future__ import annotations -from contextlib import contextmanager import re +from contextlib import contextmanager from pathlib import Path import pytest @@ -100,9 +100,7 @@ def test_input_workspace_capabilities_cover_simple_and_complex_tasks(): "parameters", "review", ] - region_options = next( - cap.options for cap in rfdiffusion.input_workspace if cap.plugin == "regions" - ) + region_options = next(cap.options for cap in rfdiffusion.input_workspace if cap.plugin == "regions") assert {"contig", "hotspot_res", "inpaint_seq"}.issubset(region_options["fields"]) assert [cap.plugin for cap in easifa.input_workspace] == [ "files", @@ -166,9 +164,9 @@ def test_git_runner_sources_are_commit_pinned_and_clone_metadata_is_removed_in_l def test_mpnn_cpu_runtime_omits_inference_unused_gpu_and_media_wheels(): requirements = { line.split("==", 1)[0].lower() - for raw in (SERVER_ROOT / "docker" / "runners" / "mpnn" / "requirements.txt").read_text( - encoding="utf-8" - ).splitlines() + for raw in (SERVER_ROOT / "docker" / "runners" / "mpnn" / "requirements.txt") + .read_text(encoding="utf-8") + .splitlines() if (line := raw.strip()) and not line.startswith("#") } assert not any(package.startswith("nvidia-") for package in requirements) @@ -178,9 +176,7 @@ def test_mpnn_cpu_runtime_omits_inference_unused_gpu_and_media_wheels(): def test_ligandmpnn_uses_the_pinned_upstream_cli_flags(): - run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text( - encoding="utf-8" - ) + run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text(encoding="utf-8") ligand_case = run_script.split(" ligandmpnn)", 1)[1].split(" ;;", 1)[0] assert '--number_of_batches "${NUMBER_OF_BATCHES}"' in ligand_case @@ -190,12 +186,8 @@ def test_ligandmpnn_uses_the_pinned_upstream_cli_flags(): def test_proteinmpnn_and_solublempnn_share_the_pinned_official_runtime(): - dockerfile = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "Dockerfile").read_text( - encoding="utf-8" - ) - run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text( - encoding="utf-8" - ) + dockerfile = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "Dockerfile").read_text(encoding="utf-8") + run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text(encoding="utf-8") registry = yaml.safe_load((SERVER_ROOT / "config" / "task_types.yaml").read_text(encoding="utf-8")) assert "MPNN_REPO=https://github.com/YaoYinYing/ProteinMPNN.git" in dockerfile @@ -210,12 +202,8 @@ def test_proteinmpnn_and_solublempnn_share_the_pinned_official_runtime(): def test_lasermpnn_uses_pinned_source_checkpoints_and_cpu_runtime(): - dockerfile = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "Dockerfile").read_text( - encoding="utf-8" - ) - run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text( - encoding="utf-8" - ) + dockerfile = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "Dockerfile").read_text(encoding="utf-8") + run_script = (SERVER_ROOT / "docker" / "runners" / "mpnn" / "run.sh").read_text(encoding="utf-8") registry = yaml.safe_load((SERVER_ROOT / "config" / "task_types.yaml").read_text(encoding="utf-8")) assert "LASERMPNN_REPO=https://github.com/YaoYinYing/LASErMPNN.git" in dockerfile @@ -244,9 +232,7 @@ def test_every_declared_submission_parameter_is_consumed_by_its_runtime_script() runtime = registry["runtime_families"][task["runtime_family"]] script = (SERVER_ROOT / Path(runtime["dockerfile"]).parent / "run.sh").read_text(encoding="utf-8") consumed = { - name - for name in declared - if re.search(rf"(?= 1 - assert form["resources"]["memory"] - assert form["resources"]["max_runtime_seconds"] >= 1 + # Resource usage is not part of the user-facing submission review. + assert "resources" not in form assert form["input_workspace"]["version"] == 1 assert form["input_workspace"]["capabilities"][0]["plugin"] == "files" assert form["input_workspace"]["capabilities"][-1]["plugin"] == "review" @@ -111,9 +109,7 @@ def test_dashboard_links_to_dedicated_manifest_first_result_workspace(): assert "PY2DMOL_SCRIPT_INTEGRITY" in script assert "renderPy2DmolFallback" in script assert "parseCifAlphaCarbons" in script - preview_plugins = (SERVER_PACKAGE / "static" / "js" / "result-preview-plugins.js").read_text( - encoding="utf-8" - ) + preview_plugins = (SERVER_PACKAGE / "static" / "js" / "result-preview-plugins.js").read_text(encoding="utf-8") plugin_host = (SERVER_PACKAGE / "static" / "js" / "plugin-host.js").read_text(encoding="utf-8") assert "ResultPreviewHost" in preview_plugins assert 'id: "structure"' in preview_plugins @@ -128,7 +124,7 @@ def test_execution_logs_are_diagnostic_text_artifacts_not_main_results(): results = (SERVER_PACKAGE / "static" / "js" / "task-results.js").read_text(encoding="utf-8") assert 'artifact["role"] = "diagnostic"' in runtime assert 'artifact.role !== "diagnostic"' in results - assert 'Execution log · ' in results + assert "Execution log · " in results def test_create_task_uses_capability_plugins_with_safe_fallbacks(): @@ -148,7 +144,7 @@ def test_create_task_uses_capability_plugins_with_safe_fallbacks(): def test_full_stack_smoke_uses_manifest_first_result_contract(): script = (Path(__file__).parent / "full_stack_smoke.py").read_text(encoding="utf-8") - assert 'manifest = results.json()' in script + assert "manifest = results.json()" in script assert 'artifact["url"]' in script assert 'f"{base_url}/compute/api/results/{task_id}/archive"' in script assert "artifact_prefix = fasta_path.stem" in script @@ -460,8 +456,10 @@ def test_result_manifest_allows_only_published_artifacts(monkeypatch, tmp_path): manifest_response = client.get(f"/compute/api/results/{md5sum}", headers=auth_header) result_page = client.get(f"/compute/results/{md5sum}", headers=auth_header) artifact = manifest_response.json["artifacts"][0] - inline = client.get(artifact["url"], headers=auth_header) - download = client.get(f"{artifact['url']}?download=1", headers=auth_header) + artifact_url = artifact["url"] + default = client.get(artifact_url, headers=auth_header) + download = client.get(f"{artifact_url}?download=1", headers=auth_header) + inline = client.get(f"{artifact_url}?download=0", headers=auth_header) unpublished = client.get( f"/compute/api/results/{md5sum}/artifacts/not-published.txt", headers=auth_header, @@ -471,14 +469,44 @@ def test_result_manifest_allows_only_published_artifacts(monkeypatch, tmp_path): assert result_page.status_code == 200 assert "Main Results" in result_page.get_data(as_text=True) assert md5sum in result_page.get_data(as_text=True) + # Page bootstrap is an inert JSON script block, not executable inline JS. + assert 'id="result-task-data"' in result_page.get_data(as_text=True) assert artifact["path"] == "scores/result.csv" assert artifact["preview"] == "table" - assert inline.status_code == 200 - assert inline.get_data(as_text=True) == "score\n1.0\n" + # Artifacts are untrusted runner output: default to attachment + sandbox. + assert default.status_code == 200 + assert default.headers["Content-Disposition"].startswith("attachment;") + assert default.headers["Content-Security-Policy"] == "sandbox" + assert default.get_data(as_text=True) == "score\n1.0\n" assert download.headers["Content-Disposition"].startswith("attachment;") + assert inline.headers["Content-Disposition"].startswith("inline;") + assert inline.get_data(as_text=True) == "score\n1.0\n" assert unpublished.status_code == 404 +def test_page_csp_forbids_inline_scripts(monkeypatch, tmp_path): + """Main app CSP must not allow inline scripts; page bootstraps are inert + JSON blocks (see security-audit-tracking.md §11).""" + module = _load_pssm_module( + monkeypatch, + tmp_path, + extra_env={"RUNNER_UID": "1234", "RUNNER_GID": "5678"}, + ) + client = module.app.test_client() + admin_header = _test_client_auth(module, username="admin", password="test-admin-password") + + for path, auth_header in ( + ("/compute/dashboard", _test_client_auth(module)), + ("/compute/user_control", admin_header), + ): + response = client.get(path, headers=auth_header) + assert response.status_code == 200 + csp = response.headers["Content-Security-Policy"] + script_src = next(part.strip() for part in csp.split(";") if part.strip().startswith("script-src")) + assert "'unsafe-inline'" not in script_src + assert " + diff --git a/server/revocompute/templates/task_results.html b/server/revocompute/templates/task_results.html index ef7fbf607..ffb7669f0 100644 --- a/server/revocompute/templates/task_results.html +++ b/server/revocompute/templates/task_results.html @@ -63,6 +63,7 @@

Choose an artifact

+ diff --git a/server/tests/test_tasks.py b/server/tests/test_tasks.py index aef020f78..b2bf8aa41 100644 --- a/server/tests/test_tasks.py +++ b/server/tests/test_tasks.py @@ -105,10 +105,12 @@ def test_dashboard_links_to_dedicated_manifest_first_result_workspace(): assert "A.authFetch(artifact.url)" in script assert "loadStructureFromData" in script assert "loadStructureFromUrl" not in script - assert 'PY2DMOL_COMMIT = "8c95fd9efae6007e124e143cd276244d89228c66"' in script - assert "PY2DMOL_SCRIPT_INTEGRITY" in script assert "renderPy2DmolFallback" in script - assert "parseCifAlphaCarbons" in script + py2dmol_preview = (SERVER_PACKAGE / "static" / "js" / "py2dmol-preview.js").read_text(encoding="utf-8") + assert 'PY2DMOL_COMMIT = "8c95fd9efae6007e124e143cd276244d89228c66"' in py2dmol_preview + assert "PY2DMOL_SCRIPT_INTEGRITY" in py2dmol_preview + assert "parseCifAlphaCarbons" in py2dmol_preview + assert "renderAlphaTrace" in py2dmol_preview preview_plugins = (SERVER_PACKAGE / "static" / "js" / "result-preview-plugins.js").read_text(encoding="utf-8") plugin_host = (SERVER_PACKAGE / "static" / "js" / "plugin-host.js").read_text(encoding="utf-8") assert "ResultPreviewHost" in preview_plugins @@ -157,6 +159,36 @@ def test_full_stack_smoke_uses_manifest_first_result_contract(): assert "results.status_code == 302" not in script +def test_dashboard_serves_structure_preview_for_pdb_tasks(monkeypatch, tmp_path): + module = _load_pssm_module( + monkeypatch, + tmp_path, + extra_env={ + "RUNNER_UID": "1234", + "RUNNER_GID": "5678", + "ENABLED_TASKRUNNERS": "pythia_ddg", + }, + ) + client = module.app.test_client() + auth_header = _test_client_auth(module) + result_dir = Path(module.task_runtime.CONFIG.results_folder) / "tasks" + md5sum = _insert_pending_task(module, result_dir, filename="input.pdb") + module.task_store.update_task(md5sum, task_type="pythia_ddg") + + dashboard = client.get("/compute/dashboard", headers=auth_header) + html = dashboard.get_data(as_text=True) + assert '"structure_input": true' in html + assert f'"/compute/api/tasks/{md5sum}/input"' in html + assert '"sequence": ""' in html + + resp = client.get(f"/compute/api/tasks/{md5sum}/input", headers=auth_header) + assert resp.status_code == 200 + assert resp.data == b">test\nACDE\n" + + missing = client.get(f"/compute/api/tasks/{'b' * 32}/input", headers=auth_header) + assert missing.status_code == 404 + + def _insert_pending_task( module, result_dir: Path, filename: str = "input.fasta", entities: list[dict] | None = None ) -> str: From f6d59d803e1d88d30351f933b5b7057f005f3245 Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 11:40:28 +0800 Subject: [PATCH 4/7] fix(server): address review findings and CI failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docker-compose.yml: move the forwarded-allow-ips comment out of the folded gunicorn command scalar (comment text broke the command string and the web service failed to start — DockerFullStack CI failure); reword the REDIS_PASSWORD interpolation message (GitGuardian generic-password false positive) - restart.sh: ensure_redis_password reads the password already persisted in the env file before generating a new one, so reload/build/down no longer desync from the running broker - prime/run.sh: normalize config.json auto_map entries — scalars like "AutoModel": "modeling_prime.PrimeModel" were iterated character by character; both OGT and DMS branches fixed - routes.py: content-validate every uploaded input of a multi-file task (primary and auxiliary), not just saved_inputs[0] - tests: auxiliary-upload validation regression test Co-Authored-By: Claude --- server/docker-compose.yml | 8 +++--- server/docker/runners/prime/run.sh | 24 +++++++++++++--- server/revocompute/redis_util.py | 2 +- server/revocompute/routes.py | 38 +++++++++++++++---------- server/run/restart.sh | 8 ++++++ server/tests/test_security.py | 34 ++++++++++++++++++++++ server/tests/test_security_hardening.py | 1 - 7 files changed, 90 insertions(+), 25 deletions(-) diff --git a/server/docker-compose.yml b/server/docker-compose.yml index df9861808..b233215b1 100644 --- a/server/docker-compose.yml +++ b/server/docker-compose.yml @@ -71,7 +71,7 @@ services: restart: unless-stopped # --requirepass is mandatory: restart.sh generates and persists # REDIS_PASSWORD in the deployment env file, and the Celery URIs embed it. - command: ["redis-server", "--save", "", "--appendonly", "no", "--requirepass", "${REDIS_PASSWORD:?run restart.sh setup to generate REDIS_PASSWORD}"] + command: ["redis-server", "--save", "", "--appendonly", "no", "--requirepass", "${REDIS_PASSWORD:?required; restart.sh setup generates the broker secret}"] volumes: - redis-data:/data @@ -118,13 +118,13 @@ services: user: ${RUNNER_UID}:${RUNNER_GID} depends_on: - redis + # Trust X-Forwarded-Proto only from the gateway container. The web + # service publishes no ports, so nothing outside the compose bridge + # (default docker range 172.16.0.0/12) can reach gunicorn directly. command: >- gunicorn -w ${GUNICORN_WORKERS:-2} --timeout ${GUNICORN_TIMEOUT:-120} --preload - # Trust X-Forwarded-Proto only from the gateway container. The web - # service publishes no ports, so nothing outside the compose bridge - # (default docker range 172.16.0.0/12) can reach gunicorn directly. --forwarded-allow-ips 127.0.0.1,172.16.0.0/12 -b 0.0.0.0:${PORT:-8080} --access-logfile ${LOG_DIR}/gunicorn-access.log diff --git a/server/docker/runners/prime/run.sh b/server/docker/runners/prime/run.sh index 337dcceda..9b5a49459 100644 --- a/server/docker/runners/prime/run.sh +++ b/server/docker/runners/prime/run.sh @@ -73,6 +73,14 @@ def load_vendored_code(model_dir): if not model_type: raise SystemExit(f'PRIME {model_dir.name} config.json has no model_type') + def _entries(value): + # config.json auto_map values are conventionally strings + # ("AutoModel": "modeling_prime.PrimeModel"); only tokenizer maps + # use [slow, fast] lists. Normalize both shapes. + if isinstance(value, str): + return [value] + return list(value) + def _load(entry): module_name, _, class_name = entry.rpartition('.') try: @@ -91,7 +99,7 @@ def load_vendored_code(model_dir): return cls config_class = None - for entry in auto_map.get('AutoConfig', ()): + for entry in _entries(auto_map.get('AutoConfig', ())): config_class = _load(entry) AutoConfig.register(model_type, config_class) if config_class is None: @@ -99,7 +107,7 @@ def load_vendored_code(model_dir): for auto_key, entries in auto_map.items(): if auto_key == 'AutoConfig': continue - for index, entry in enumerate(entries): + for index, entry in enumerate(_entries(entries)): cls = _load(entry) if auto_key == 'AutoModel': AutoModel.register(config_class, cls) @@ -179,6 +187,14 @@ def load_vendored_code(model_dir): if not model_type: raise SystemExit(f'PRIME {model_dir.name} config.json has no model_type') + def _entries(value): + # config.json auto_map values are conventionally strings + # ("AutoModel": "modeling_prime.PrimeModel"); only tokenizer maps + # use [slow, fast] lists. Normalize both shapes. + if isinstance(value, str): + return [value] + return list(value) + def _load(entry): module_name, _, class_name = entry.rpartition('.') try: @@ -197,7 +213,7 @@ def load_vendored_code(model_dir): return cls config_class = None - for entry in auto_map.get('AutoConfig', ()): + for entry in _entries(auto_map.get('AutoConfig', ())): config_class = _load(entry) AutoConfig.register(model_type, config_class) if config_class is None: @@ -205,7 +221,7 @@ def load_vendored_code(model_dir): for auto_key, entries in auto_map.items(): if auto_key == 'AutoConfig': continue - for index, entry in enumerate(entries): + for index, entry in enumerate(_entries(entries)): cls = _load(entry) if auto_key == 'AutoModel': AutoModel.register(config_class, cls) diff --git a/server/revocompute/redis_util.py b/server/revocompute/redis_util.py index f789248c8..63b7b4c6c 100644 --- a/server/revocompute/redis_util.py +++ b/server/revocompute/redis_util.py @@ -25,7 +25,7 @@ @lru_cache(maxsize=1) -def get_redis() -> "redis.Redis | None": +def get_redis() -> redis.Redis | None: """Return a Redis client for ``REDIS_URL``, or ``None`` if unavailable. The client (or the ``None`` failure) is cached for the process lifetime diff --git a/server/revocompute/routes.py b/server/revocompute/routes.py index b3fb7d8c0..d986f13ae 100644 --- a/server/revocompute/routes.py +++ b/server/revocompute/routes.py @@ -522,23 +522,31 @@ def _prepare_task_record( } -def _reject_invalid_input(md5sum: str, base_record: dict[str, Any], task_type: str = "gremlin"): +def _reject_invalid_input( + md5sum: str, base_record: dict[str, Any], saved_inputs: list[dict[str, Any]], task_type: str = "gremlin" +): """Reject uploads whose content doesn't match the expected format. - Every upload passes the 4096-byte binary sniff; the primary input is then - content-validated by extension (FASTA/A3M/PDB/mmCIF/JSON) with generous - DoS caps (see revocompute.input_validation), so third-party parsers never - see pathological content. + Every uploaded file — primary and auxiliary alike — passes the + 4096-byte binary sniff and is then content-validated by extension + (FASTA/A3M/PDB/mmCIF/JSON) with generous DoS caps (see + revocompute.input_validation), so third-party parsers never see + pathological content from any input of a multi-file task. """ - upload_path = base_record["file_path"] - if base_record["is_binary"]: - error_message = "Binary file uploads are not supported." - response_message = "Uploaded file contains binary content" - else: - error_message = validate_input_file(upload_path, base_record.get("filename") or "") - if error_message is None: - return None - response_message = error_message + error_message = None + response_message = "" + for item in saved_inputs: + blob_path = item["blob_path"] + if _is_binary_file(blob_path): + error_message = f"Binary file uploads are not supported: {item['relative_path']}" + response_message = "Uploaded file contains binary content" + break + error_message = validate_input_file(blob_path, item["relative_path"] or "") + if error_message is not None: + response_message = error_message + break + if error_message is None: + return None failed_task = {**base_record, "md5sum": md5sum, "status": "failed", "error": error_message} task_store.upsert_task(md5sum, **base_record, status="failed", error=error_message) @@ -676,7 +684,7 @@ def upload_file(): # skipcq: PY-R1000 -- route validation branches form one tra task_type=task_type, input_form=input_form, ) - if invalid_response := _reject_invalid_input(md5sum, base_record, task_type): + if invalid_response := _reject_invalid_input(md5sum, base_record, saved_inputs, task_type): return invalid_response task_store.upsert_task( diff --git a/server/run/restart.sh b/server/run/restart.sh index 5f2bab111..1f7233ecc 100755 --- a/server/run/restart.sh +++ b/server/run/restart.sh @@ -33,6 +33,14 @@ compose_files() { ensure_redis_password() { local _pass="" if [[ -n "${REDIS_PASSWORD:-}" ]]; then return 0; fi + # The password may already be persisted in the env file (this shell was not + # sourced from it yet). Reuse it — generating a new one would desync from + # the running broker for commands that don't restart Redis (reload, build). + _pass="$(grep -m1 '^REDIS_PASSWORD=' "${ENV_FILE}" 2>/dev/null | cut -d= -f2- || true)" + if [[ -n "${_pass}" ]]; then + export REDIS_PASSWORD="${_pass}" + return 0 + fi _pass="$(openssl rand -hex 24 2>/dev/null || python3 -c 'import secrets; print(secrets.token_hex(24))')" printf '\n# Generated by restart.sh — Redis requirepass secret.\nREDIS_PASSWORD=%s\n' "${_pass}" >> "${ENV_FILE}" export REDIS_PASSWORD="${_pass}" diff --git a/server/tests/test_security.py b/server/tests/test_security.py index 5e70bf80b..dcbcb890c 100644 --- a/server/tests/test_security.py +++ b/server/tests/test_security.py @@ -104,6 +104,40 @@ def test_security_email_enumeration_resend_verification(monkeypatch, tmp_path): assert resp1.json["message"] == resp2.json["message"] +def test_security_auxiliary_uploads_content_validated(monkeypatch, tmp_path): + """Multi-file tasks: auxiliary files get the same content validation as + the primary (binary sniff + per-extension validators).""" + module = _load_pssm_module(monkeypatch, tmp_path, extra_env={"RUNNER_UID": "1234", "RUNNER_GID": "5678"}) + valid_pdb = tmp_path / "struc.pdb" + valid_pdb.write_text( + "ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N\n" + "ATOM 2 CA ALA A 1 1.500 0.000 0.000 1.00 0.00 C\n" + "END\n" + ) + broken_json = tmp_path / "aux.json" + broken_json.write_text("this is not json") + from revocompute.routes import _reject_invalid_input + + base_record = { + "file_path": str(valid_pdb), + "filename": "struc.pdb", + "is_binary": 0, + "result_dir": str(tmp_path / "results"), + "uploaded_at": time.time(), + "username": "tester", + } + saved_inputs = [ + {"blob_path": str(valid_pdb), "relative_path": "struc.pdb"}, + {"blob_path": str(broken_json), "relative_path": "aux.json"}, + ] + with module.app.app_context(): + response = _reject_invalid_input("a" * 32, base_record, saved_inputs, "rfdiffusion") + assert response is not None and response[1] == 400 + # All-valid inputs pass. + with module.app.app_context(): + assert _reject_invalid_input("b" * 32, base_record, saved_inputs[:1], "rfdiffusion") is None + + def test_security_bearer_vs_cookie_csrf_gate(monkeypatch, tmp_path): """State-changing endpoints reject cookie-only auth (CSRF protection).""" module = _load_pssm_module(monkeypatch, tmp_path, extra_env={"RUNNER_UID": "1234", "RUNNER_GID": "5678"}) diff --git a/server/tests/test_security_hardening.py b/server/tests/test_security_hardening.py index f6dc5b068..41de89fad 100644 --- a/server/tests/test_security_hardening.py +++ b/server/tests/test_security_hardening.py @@ -19,7 +19,6 @@ import sqlite3 import subprocess import time -from pathlib import Path import pytest import redis From c8593ce605cea3558f236d8af8bbda2405728ebc Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 11:48:47 +0800 Subject: [PATCH 5/7] fix(server): address CodeRabbit review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ratelimit: key the distributed limiter on X-Real-IP (the gateway nginx overwrites it with the socket peer), so each client gets its own quota instead of one shared gateway-address bucket - redis_util: never log the authenticated REDIS_URL — redact credentials in the fallback warning - input_validation: reject oversized JSON before json.loads allocates the full object graph (1 MiB pre-parse ceiling) - slurm_runner.reconnect: tri-state (True/False/None); recovery leaves the task running when the job state is unknown instead of recording a failure and deleting the input workspace under a live job - dashboard: pick the structure parser (pdb vs mmcif) from the uploaded filename, not from the task type's accepted extensions (types accepting both receive .pdb files too) - tests: tri-state reconnect, JSON byte-ceiling regression tests Co-Authored-By: Claude --- server/revocompute/input_validation.py | 6 +++++ .../revocompute/job/runners/slurm_runner.py | 17 +++++++++---- server/revocompute/ratelimit.py | 13 ++++++---- server/revocompute/redis_util.py | 5 +++- server/revocompute/routes.py | 11 +++++---- server/revocompute/task_runtime.py | 11 ++++++++- server/tests/test_input_validation.py | 9 ++++--- server/tests/test_slurm_runner.py | 24 +++++++++++++++++++ 8 files changed, 76 insertions(+), 20 deletions(-) diff --git a/server/revocompute/input_validation.py b/server/revocompute/input_validation.py index 4a66795af..bf8772a20 100644 --- a/server/revocompute/input_validation.py +++ b/server/revocompute/input_validation.py @@ -57,6 +57,10 @@ # JSON MAX_JSON_NODES = 1_000_000 # ~8 MB of "0,0,0,..." would be needed to reach it MAX_JSON_DEPTH = 50 +# Byte ceiling applied BEFORE json.loads: a compact array of tiny values can +# allocate tens of MiB of Python objects per worker even when the node count +# passes. Scientific JSON inputs (config/metadata) are far below 1 MiB. +MAX_JSON_BYTES = 1024 * 1024 def _read_text(path: str, *, kind: str) -> tuple[str | None, str]: @@ -205,6 +209,8 @@ def validate_json(path: str) -> str | None: return f"Could not read uploaded JSON file: {exc}" if b"\0" in data: return "Uploaded JSON file contains binary content (NUL byte)" + if len(data) > MAX_JSON_BYTES: + return f"JSON file exceeds the {MAX_JSON_BYTES // (1024 * 1024)} MiB input limit" try: value = json.loads(data.decode("utf-8")) except UnicodeDecodeError: diff --git a/server/revocompute/job/runners/slurm_runner.py b/server/revocompute/job/runners/slurm_runner.py index 676cc2e8b..3e8594075 100644 --- a/server/revocompute/job/runners/slurm_runner.py +++ b/server/revocompute/job/runners/slurm_runner.py @@ -63,14 +63,21 @@ def __init__( self._job_id_event = threading.Event() self._resolved_resource_policy = resource_policy - def reconnect(self, slurm_job_id: str) -> bool: + def reconnect(self, slurm_job_id: str) -> bool | None: """Check whether a SLURM job is still alive after a server restart. - We cannot re-attach the srun subprocess, but we can query sacct.""" + + We cannot re-attach the srun subprocess, but we can query sacct. + Returns ``True`` when the job is still active, ``False`` when sacct + says it is no longer active, and ``None`` when the state cannot be + determined (sacct missing, query failed, or timed out). Callers must + treat ``None`` as unknown — not as failure — because the job may + still be running on the cluster. + """ self._slurm_job_id = slurm_job_id self._job_id_event.set() sacct = shutil.which("sacct") if not sacct: - return False + return None try: result = subprocess.run( [sacct, "-j", slurm_job_id, "--noheader", "-o", "State", "-P"], @@ -79,11 +86,11 @@ def reconnect(self, slurm_job_id: str) -> bool: timeout=10, ) if result.returncode != 0: - return False + return None state = (result.stdout or "").strip().split("\n")[0].strip() return state in ("RUNNING", "PENDING", "CONFIGURING") except Exception: - return False + return None # -- Job ABC ------------------------------------------------------------- diff --git a/server/revocompute/ratelimit.py b/server/revocompute/ratelimit.py index b4d2bdfe9..3d0ee9a41 100644 --- a/server/revocompute/ratelimit.py +++ b/server/revocompute/ratelimit.py @@ -48,11 +48,14 @@ def decorator(f: Callable) -> Callable: @wraps(f) def decorated(*args: Any, **kwargs: Any) -> Any: nonlocal _last_cleanup - # Forwarded-IP headers are useful for audit metadata but are not a - # trustworthy limiter key: clients can spoof them unless every - # request is guaranteed to traverse a trusted proxy. The socket - # peer cannot be changed by an HTTP header. - ip = request.remote_addr or "unknown" + # The compose gateway nginx overwrites X-Real-IP with the socket + # peer ($remote_addr) and the web service accepts connections + # only from that gateway, so X-Real-IP is the canonical + # per-client address in the supported deployment. remote_addr + # would be the gateway container itself, collapsing every user + # into one shared quota. Fall back to the socket peer for + # direct (non-gateway) deployments. + ip = (request.headers.get("X-Real-IP", "").split(",")[0].strip()) or request.remote_addr or "unknown" now = time.monotonic() cutoff = now - window_seconds diff --git a/server/revocompute/redis_util.py b/server/revocompute/redis_util.py index 63b7b4c6c..be2944518 100644 --- a/server/revocompute/redis_util.py +++ b/server/revocompute/redis_util.py @@ -15,6 +15,7 @@ import logging import os +import re from functools import lru_cache import redis @@ -37,6 +38,8 @@ def get_redis() -> redis.Redis | None: try: client.ping() except Exception: - _LOGGER.warning("Redis unavailable at %s — rate limiting and CAPTCHA fall back to per-process state", url) + # Never log the URL itself — it may carry the broker password. + redacted = re.sub(r"://:[^@]*@", "://:***@", url) + _LOGGER.warning("Redis unavailable at %s — rate limiting and CAPTCHA fall back to per-process state", redacted) return None return client diff --git a/server/revocompute/routes.py b/server/revocompute/routes.py index d986f13ae..23c444aae 100644 --- a/server/revocompute/routes.py +++ b/server/revocompute/routes.py @@ -1017,12 +1017,13 @@ def _dashboard_task_status(task: dict[str, Any], index: int, current_user: str, tt_obj = None if tt_obj is not None: extensions = set(tt_obj.input_extensions or (tt_obj.input_extension,)) - if extensions & {".cif", ".mmcif"}: + if extensions & {".pdb", ".cif", ".mmcif"}: structure_input = True - structure_format = "mmcif" - elif ".pdb" in extensions: - structure_input = True - structure_format = "pdb" + # The parser depends on the UPLOADED file, not on the type's + # accepted extensions — a type accepting both PDB and mmCIF + # receives .pdb files too. + filename_lower = str(task.get("filename") or "").lower() + structure_format = "mmcif" if filename_lower.endswith((".cif", ".mmcif")) else "pdb" sequence_truncated = False if structure_input: # Structure tasks render a py2Dmol snapshot instead of sequence text; diff --git a/server/revocompute/task_runtime.py b/server/revocompute/task_runtime.py index f5413f4a6..c4ca95277 100644 --- a/server/revocompute/task_runtime.py +++ b/server/revocompute/task_runtime.py @@ -814,12 +814,21 @@ def _recover_orphaned_tasks() -> int: tt, runner = _gt(task_type) job = SlurmJob(md5sum, tt, runner, [], task["result_dir"]) - if job.reconnect(slurm_job_id): + slurm_state = job.reconnect(slurm_job_id) + if slurm_state is True: logging.info("Recovery: SLURM job %s still running for %s, re-queuing poll", slurm_job_id, md5sum) run_compute_task.apply_async( args=[md5sum], kwargs={"task_type": task_type, "recover_slurm": slurm_job_id} ) recovered += 1 + elif slurm_state is None: + # Unknown state (sacct missing or query failed): the job + # may still be running on the cluster. Leave the task + # running — do not record a failure and do not clean up + # its input workspace under a live job. + logging.warning( + "Recovery: SLURM job %s state unknown for %s; leaving task running", slurm_job_id, md5sum + ) else: _record_failure( md5sum, diff --git a/server/tests/test_input_validation.py b/server/tests/test_input_validation.py index e3fdba10a..0d409b023 100644 --- a/server/tests/test_input_validation.py +++ b/server/tests/test_input_validation.py @@ -248,10 +248,13 @@ def test_json_rejects_invalid_json(tmp_path): assert "not appear to be valid JSON" in validate_json(str(path)) -def test_json_rejects_too_many_nodes(tmp_path): - # A flat list of MAX_JSON_NODES + 1 elements is well-formed JSON but too big. +def test_json_rejects_oversized_input_before_parsing(tmp_path): + # A flat list of MAX_JSON_NODES + 1 elements is well-formed JSON but + # exceeds the pre-parse byte ceiling, which rejects it before the full + # object graph is allocated (the node-count cap is the second line of + # defence and stays for future ceiling changes). path = _write(tmp_path, ("[" + "0," * MAX_JSON_NODES + "0]").encode()) - assert f"more than {MAX_JSON_NODES} values" in validate_json(str(path)) + assert "MiB input limit" in validate_json(str(path)) def test_json_rejects_deep_nesting(tmp_path): diff --git a/server/tests/test_slurm_runner.py b/server/tests/test_slurm_runner.py index 9988f16e2..fc00bf66b 100644 --- a/server/tests/test_slurm_runner.py +++ b/server/tests/test_slurm_runner.py @@ -6,6 +6,7 @@ from __future__ import annotations +import shutil import subprocess from dataclasses import replace from unittest.mock import patch @@ -175,6 +176,29 @@ def resolve_task_resources(self, tool, *, requires_gpu, default_timeout_seconds) # -- apptainer invocation ----------------------------------------------------- +def test_reconnect_returns_none_when_sacct_missing(monkeypatch, tmp_path): + """Unknown SLURM job state is tri-state — missing sacct must not read as + 'job finished' (recovery keeps the task running and its workspace).""" + from revocompute.job.runners.slurm_runner import SlurmJob + + job = SlurmJob("task-1", _make_task_type(), _make_runner(), _make_entities(), str(tmp_path / "out")) + monkeypatch.setattr(shutil, "which", lambda _name: None) + assert job.reconnect("12345") is None + + +def test_reconnect_returns_none_when_sacct_fails(monkeypatch, tmp_path): + from revocompute.job.runners.slurm_runner import SlurmJob + + job = SlurmJob("task-1", _make_task_type(), _make_runner(), _make_entities(), str(tmp_path / "out")) + monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/sacct") + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **kw: type("R", (), {"returncode": 1, "stdout": ""})(), + ) + assert job.reconnect("12345") is None + + def test_render_apptainer_binds_and_env(tmp_path): job = SlurmJob( "task-1", From c6d8ebeccbf92562be099cf6c0c582acf4cc29e2 Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 11:51:22 +0800 Subject: [PATCH 6/7] fix(server): hardlink debug captures; clear redis probe cache in tests - task_runtime debug capture hardlinks input snapshots into the results tree (copy fallback for cross-mount), so the workspace cleanup's disk savings are not undone by a duplicate copy - tests/conftest: always clear the cached Redis client after REDIS_URL is set, including when a test overrides it explicitly Co-Authored-By: Claude --- server/revocompute/task_runtime.py | 10 +++++++++- server/tests/conftest.py | 6 ++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/server/revocompute/task_runtime.py b/server/revocompute/task_runtime.py index c4ca95277..6b6fed91b 100644 --- a/server/revocompute/task_runtime.py +++ b/server/revocompute/task_runtime.py @@ -579,7 +579,15 @@ def _capture_debug_submission(task: dict[str, Any], entities: list[dict], params continue destination = _safe_join(inputs_dir, *parts) os.makedirs(os.path.dirname(destination), exist_ok=True) - shutil.copyfile(snapshot_path, destination) + # Hardlink first: workspace and results live on the same server + # filesystem, so the debug copy costs no extra disk and the + # workspace deletion later only drops its own link. Copy when + # linking is impossible (e.g. the results dir is a different + # mount). + try: + os.link(snapshot_path, destination) + except OSError: + shutil.copyfile(snapshot_path, destination) files.append( { "name": relative_path, diff --git a/server/tests/conftest.py b/server/tests/conftest.py index 259e63397..cb9dd8a02 100644 --- a/server/tests/conftest.py +++ b/server/tests/conftest.py @@ -165,9 +165,11 @@ def _load_pssm_module(monkeypatch, tmp_path, extra_env: dict | None = None): # it at a dead port unless a test explicitly overrides REDIS_URL. if "REDIS_URL" not in (extra_env or {}): monkeypatch.setenv("REDIS_URL", "redis://127.0.0.1:1/0") - from revocompute.redis_util import get_redis + # Always clear the cached client — get_redis() caches both live clients + # and fallback None, and an overridden REDIS_URL must win in this test. + from revocompute.redis_util import get_redis - get_redis.cache_clear() + get_redis.cache_clear() # -- module load with import isolation -- server_dir = str(Path(REPO_DIR) / "server") From c67b9bad2289deb147dc6ccf67608e509537973d Mon Sep 17 00:00:00 2001 From: YaoYinYing <33014714+YaoYinYing@users.noreply.github.com> Date: Fri, 14 Aug 2026 12:05:36 +0800 Subject: [PATCH 7/7] test(server): tighten review-flagged test assertions - JSON depth: reject exactly at cap+1 (previously tested cap+2); accept stays at the cap - API key: assert the stored digest equals sha256(key) after re-read - _safe_join: actually create the in-base symlink before asserting it - structure preview: seed a real PDB payload (helper gains a content parameter) so the input endpoint test exercises the PDB path Co-Authored-By: Claude --- server/tests/test_input_validation.py | 3 ++- server/tests/test_security_hardening.py | 7 ++++++- server/tests/test_task_runtime_hardening.py | 1 + server/tests/test_tasks.py | 16 ++++++++++++---- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/server/tests/test_input_validation.py b/server/tests/test_input_validation.py index 0d409b023..02fd0a97a 100644 --- a/server/tests/test_input_validation.py +++ b/server/tests/test_input_validation.py @@ -258,7 +258,8 @@ def test_json_rejects_oversized_input_before_parsing(tmp_path): def test_json_rejects_deep_nesting(tmp_path): - doc = "[" * (MAX_JSON_DEPTH + 1) + "0" + "]" * (MAX_JSON_DEPTH + 1) + # The leaf sits at depth MAX_JSON_DEPTH + 1 — one level past the cap. + doc = "[" * MAX_JSON_DEPTH + "0" + "]" * MAX_JSON_DEPTH path = _write(tmp_path, doc.encode()) assert f"nested deeper than {MAX_JSON_DEPTH}" in validate_json(str(path)) diff --git a/server/tests/test_security_hardening.py b/server/tests/test_security_hardening.py index 41de89fad..b2d0058fd 100644 --- a/server/tests/test_security_hardening.py +++ b/server/tests/test_security_hardening.py @@ -12,6 +12,7 @@ from __future__ import annotations +import hashlib import os import re import shutil @@ -48,7 +49,11 @@ def test_api_key_generate_and_validate(tmp_path): user = db.create_user("alice", "alice@example.com", "password123") key = db.generate_api_key(user["id"]) assert key.startswith("revodesign_") - assert key != user["api_key_digest"] # only the digest is stored + # Re-read after generate — the stored value must be the sha256 digest, + # never the plaintext key. + stored = db.get_user(user["id"]) + assert stored is not None and stored["api_key_digest"] == hashlib.sha256(key.encode("utf-8")).hexdigest() + assert stored["api_key_digest"] != key got = db.validate_api_key(key) assert got is not None diff --git a/server/tests/test_task_runtime_hardening.py b/server/tests/test_task_runtime_hardening.py index 5af7eaa4c..5a3950e09 100644 --- a/server/tests/test_task_runtime_hardening.py +++ b/server/tests/test_task_runtime_hardening.py @@ -69,6 +69,7 @@ def test_safe_join_accepts_new_child_and_symlink_inside_base(rt, tmp_path): assert rt._safe_join(base, "a", "b") == str(base / "a" / "b") # A symlink that stays inside the base is fine; the returned path stays # lexical (the OS resolves the symlink) — the guarantee is containment. + os.symlink(base / "real", base / "link") assert rt._safe_join(base, "link", "f") == str(base / "link" / "f") diff --git a/server/tests/test_tasks.py b/server/tests/test_tasks.py index b2bf8aa41..11631caee 100644 --- a/server/tests/test_tasks.py +++ b/server/tests/test_tasks.py @@ -172,7 +172,12 @@ def test_dashboard_serves_structure_preview_for_pdb_tasks(monkeypatch, tmp_path) client = module.app.test_client() auth_header = _test_client_auth(module) result_dir = Path(module.task_runtime.CONFIG.results_folder) / "tasks" - md5sum = _insert_pending_task(module, result_dir, filename="input.pdb") + pdb_content = ( + b"ATOM 1 N ALA A 1 0.000 0.000 0.000 1.00 0.00 N\n" + b"ATOM 2 CA ALA A 1 1.500 0.000 0.000 1.00 0.00 C\n" + b"END\n" + ) + md5sum = _insert_pending_task(module, result_dir, filename="input.pdb", content=pdb_content) module.task_store.update_task(md5sum, task_type="pythia_ddg") dashboard = client.get("/compute/dashboard", headers=auth_header) @@ -183,18 +188,21 @@ def test_dashboard_serves_structure_preview_for_pdb_tasks(monkeypatch, tmp_path) resp = client.get(f"/compute/api/tasks/{md5sum}/input", headers=auth_header) assert resp.status_code == 200 - assert resp.data == b">test\nACDE\n" + assert resp.data == pdb_content missing = client.get(f"/compute/api/tasks/{'b' * 32}/input", headers=auth_header) assert missing.status_code == 404 def _insert_pending_task( - module, result_dir: Path, filename: str = "input.fasta", entities: list[dict] | None = None + module, + result_dir: Path, + filename: str = "input.fasta", + entities: list[dict] | None = None, + content: bytes = b">test\nACDE\n", ) -> str: result_dir.mkdir(parents=True, exist_ok=True) fasta_path = result_dir / filename - content = b">test\nACDE\n" fasta_path.write_bytes(content) md5sum = uuid.uuid4().hex blob_hash = hashlib.sha256(content).hexdigest()