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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions .github/workflows/smoke-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,56 @@ jobs:
done < "$RUNNER_TEMP/tracked-paths"
exit "$bad"

- name: Reject untimed network downloads
# A download with no timeout can hang in ssl.read until the 300 s smoke
# cap kills the script: 2026-09-07, PyAutoHeart run 34099198772, an
# untimed urlretrieve to hips2fits in autolens_workspace. Fixed once in
# autolens_workspace#293, back in four scripts within three weeks
# (#537). So the pattern is gated, not remembered: any
# `urlretrieve(` call (it takes no timeout at all) or `urlopen(`
# without a timeout under scripts/ fails here, in seconds, with the
# file:line. Use `urlopen(url, timeout=...)` and write the bytes.
# AST-based, so comments and strings never trip it. Self-contained
# (no `${{ }}`) so tests/test_workflow_wiring.py runs it verbatim.
shell: bash
run: |
set -euo pipefail
python3 - <<'PY'
import ast, os, sys, warnings
from pathlib import Path

warnings.simplefilter("ignore", SyntaxWarning) # a script's own escapes are not ours to report

root = Path(os.environ.get("WORKSPACE_DIR", "workspace"))
bad = 0
for path in sorted((root / "scripts").rglob("*.py")):
rel = path.relative_to(root).as_posix()
try:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=rel)
except (SyntaxError, UnicodeDecodeError) as exc:
print(f"::warning file={rel}::not scanned for untimed downloads: {exc}")
continue
calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)]
for node in sorted(calls, key=lambda n: (n.lineno, n.col_offset)):
func = node.func
name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
if name == "urlretrieve":
why = "urlretrieve() cannot take a timeout; use urlopen(url, timeout=...)"
elif name == "urlopen" and not (
len(node.args) >= 3 # urlopen(url, data, timeout)
or any(k.arg in ("timeout", None) for k in node.keywords)
):
why = "urlopen() without timeout="
else:
continue
print(f"::error file={rel},line={node.lineno}::{why}")
print(f"{rel}:{node.lineno}: {why}")
bad += 1
if bad:
print(f"{bad} untimed network download(s) under scripts/", file=sys.stderr)
sys.exit(1 if bad else 0)
PY

- name: Clone dependency chain + PyAutoHands (matching branch if it exists)
# DEPTH 1, on the clone and on the matching-branch fetch alike: nothing
# downstream reads this history. The libraries are `pip install`ed from
Expand Down Expand Up @@ -719,6 +769,8 @@ jobs:
import subprocess
from pathlib import Path

warnings.simplefilter("ignore", SyntaxWarning) # a script's own escapes are not ours to report


def as_int(text):
try:
Expand Down
73 changes: 73 additions & 0 deletions tests/test_workflow_wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,3 +488,76 @@ def test_ordered_results_artifact_name_is_valid_and_distinct():
"results-scripts-${{ matrix.project.name }}-"
"${{ matrix.project.script_list && 'ordered' || matrix.project.directory }}"
)


# The untimed-download gate (PyAutoHeart#326): an AST scan of scripts/ in the
# PR gate, self-contained so it runs verbatim here against planted scripts.

DOWNLOAD_STEP = "Reject untimed network downloads"


def _download_step():
gate = _job_steps("smoke-tests.yml", "smoke")
return gate, _index(gate, DOWNLOAD_STEP)


def test_download_gate_runs_before_the_install_and_is_self_contained():
gate, i = _download_step()
assert _index(gate, "Checkout workspace") < i < _index(gate, "Install")
assert "${{" not in gate[i]["run"]
assert "if" not in gate[i] # every smoke run, every workspace caller


def test_download_gate_flags_untimed_calls_with_file_and_line(tmp_path):
_, i = _download_step()
step = _job_steps("smoke-tests.yml", "smoke")[i]
scripts = tmp_path / "workspace" / "scripts" / "cluster"
scripts.mkdir(parents=True)
(scripts / "bad.py").write_text(
"import urllib.request\n"
"from urllib.request import urlopen, urlretrieve\n"
"urllib.request.urlretrieve('https://x', 'f.fits')\n"
"urlretrieve('https://x', 'f.fits')\n"
"with urllib.request.urlopen('https://x') as r:\n"
" r.read()\n"
"urlopen('https://x', None)\n"
)
res = _run_discard(step, tmp_path)
assert res.returncode == 1, res.stdout + res.stderr
plain = [l for l in res.stdout.splitlines() if not l.startswith("::")]
assert [l.split(":")[1] for l in plain] == ["3", "4", "5", "7"], res.stdout
assert all(l.startswith("scripts/cluster/bad.py:") for l in plain)
assert sum(l.startswith("::error file=scripts/cluster/bad.py,line=")
for l in res.stdout.splitlines()) == 4


def test_download_gate_passes_timed_calls_and_mentions(tmp_path):
_, i = _download_step()
step = _job_steps("smoke-tests.yml", "smoke")[i]
scripts = tmp_path / "workspace" / "scripts"
scripts.mkdir(parents=True)
(scripts / "ok.py").write_text(
'"""Never use urlretrieve(url, path) here."""\n'
"import urllib.request\n"
"# urllib.request.urlopen(url) without a timeout would hang\n"
"with urllib.request.urlopen('https://x', timeout=30) as r:\n"
" r.read()\n"
"urllib.request.urlopen('https://x', None, 60)\n"
"kw = {'timeout': 5}\n"
"urllib.request.urlopen('https://x', **kw)\n"
)
res = _run_discard(step, tmp_path)
assert res.returncode == 0, res.stdout + res.stderr
assert "::error" not in res.stdout


def test_download_gate_is_a_no_op_without_scripts_and_honours_workspace_dir(tmp_path):
_, i = _download_step()
step = _job_steps("smoke-tests.yml", "smoke")[i]
res = _run_discard(step, tmp_path)
assert res.returncode == 0, res.stderr
other = tmp_path / "elsewhere" / "scripts"
other.mkdir(parents=True)
(other / "bad.py").write_text("from urllib.request import urlretrieve\nurlretrieve('u', 'p')\n")
res = _run_discard(step, tmp_path, env={"WORKSPACE_DIR": "elsewhere"})
assert res.returncode == 1 and "scripts/bad.py:2" in res.stdout
Loading