diff --git a/.gitignore b/.gitignore index ccd0594f..631126f8 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,7 @@ playground/config 4MB8_GREMLIN_mtx_zscore.png /mutagenese /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 75af90b4..6114cfdd 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 @@ -26,6 +41,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 +86,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 +95,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 @@ -187,8 +197,101 @@ 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 0a9eb3c8..83172673 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 f7d7ca69..ffb7669f 100644 --- a/server/revocompute/templates/task_results.html +++ b/server/revocompute/templates/task_results.html @@ -61,8 +61,9 @@

Choose an artifact

- + + diff --git a/server/revocompute/templates/user_control.html b/server/revocompute/templates/user_control.html index ee3125cf..2a0b91dc 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 ab1e3b73..1f7233ec 100755 --- a/server/run/restart.sh +++ b/server/run/restart.sh @@ -6,20 +6,51 @@ 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 + # 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}" + 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 +324,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 +427,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 +867,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 142f7ecb..cb9dd8a0 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,17 @@ 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") + # 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() # -- 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 38c5af58..9075aa54 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 41e466ed..f7892d00 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 deb3286a..4fee168e 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 07cd94d1..d4564cbe 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 26de8b4f..36df822a 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 00000000..c0a0daad --- /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 195124c0..ab8a8b5b 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 61e4996d..28dda2b5 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 00000000..02fd0a97 --- /dev/null +++ b/server/tests/test_input_validation.py @@ -0,0 +1,383 @@ +# 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_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 "MiB input limit" in validate_json(str(path)) + + +def test_json_rejects_deep_nesting(tmp_path): + # 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)) + + +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 b2031b7d..d4d3f8c4 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 8f71d798..21c7113f 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 b40fcf4e..2226e89e 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), } @@ -283,13 +281,14 @@ 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(): 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 @@ -325,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 @@ -335,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.py b/server/tests/test_security.py index 5e70bf80..dcbcb890 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 new file mode 100644 index 00000000..b2d0058f --- /dev/null +++ b/server/tests/test_security_hardening.py @@ -0,0 +1,314 @@ +# 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 hashlib +import os +import re +import shutil +import socket +import sqlite3 +import subprocess +import time + +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_") + # 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 + 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 2cb41eed..fc00bf66 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 @@ -141,10 +142,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"}, ) @@ -168,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", @@ -179,12 +210,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 +228,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 00000000..5a3950e0 --- /dev/null +++ b/server/tests/test_task_runtime_hardening.py @@ -0,0 +1,100 @@ +# 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. + os.symlink(base / "real", base / "link") + 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 ee41eeb5..8c0d8f45 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" @@ -107,13 +105,13 @@ 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 - preview_plugins = (SERVER_PACKAGE / "static" / "js" / "result-preview-plugins.js").read_text( - encoding="utf-8" - ) + 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 assert 'id: "structure"' in preview_plugins @@ -128,7 +126,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 +146,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 @@ -161,12 +159,50 @@ 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" + 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) + 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 == 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() @@ -460,8 +496,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 +509,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 "