| 1 | """Security regression tests for PR02 (HIGH-223, HIGH-224, HIGH-225, HIGH-226). |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-223: Private mktemp directory + noclobber + EXIT cleanup for host |
| 5 | Reddit/shortform envelopes in skills/last30days/references/research-runbook.md. |
| 6 | - HIGH-224: Quoted heredoc capture and `--` / `=` separation preventing shell |
| 7 | command substitution and flag injection in followups.md and library-queue.md. |
| 8 | - HIGH-225: Release workflow tag validation, refs/tags/ checkout pinning, |
| 9 | lockstep manifest verification, and zizmor-safe env handling in release.yml. |
| 10 | - HIGH-226: Secret/cache exclusions and non-runtime script parity across |
| 11 | .skillignore, .clawhubignore, and skills/last30days/.skillignore. |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import json |
| 17 | import os |
| 18 | import re |
| 19 | import shutil |
| 20 | import subprocess |
| 21 | import sys |
| 22 | from pathlib import Path |
| 23 | |
| 24 | import pytest |
| 25 | import yaml |
| 26 | |
| 27 | from tests.skill_contract import reference_text |
| 28 | |
| 29 | ROOT = Path(__file__).resolve().parents[1] |
| 30 | SKILL_ROOT = ROOT / "skills" / "last30days" |
| 31 | REFERENCES_DIR = SKILL_ROOT / "references" |
| 32 | RELEASE_WORKFLOW = ROOT / ".github" / "workflows" / "release.yml" |
| 33 | |
| 34 | |
| 35 | def _ignore_entries(path: Path) -> set[str]: |
| 36 | return { |
| 37 | line.strip() |
| 38 | for line in path.read_text(encoding="utf-8").splitlines() |
| 39 | if line.strip() and not line.lstrip().startswith("#") |
| 40 | } |
| 41 | |
| 42 | |
| 43 | def _extract_bash_blocks(markdown: str) -> list[str]: |
| 44 | return re.findall(r"```bash\n(.*?)```", markdown, re.DOTALL) |
| 45 | |
| 46 | |
| 47 | def _assert_run_blocks_indented(text: str, *, label: str) -> None: |
| 48 | in_run = False |
| 49 | run_indent = 0 |
| 50 | for lineno, line in enumerate(text.splitlines(), 1): |
| 51 | match = re.match(r"^(\s*)run:\s*\|\s*$", line) |
| 52 | if match: |
| 53 | in_run = True |
| 54 | run_indent = len(match.group(1)) |
| 55 | continue |
| 56 | if not in_run or not line.strip(): |
| 57 | continue |
| 58 | indent = len(line) - len(line.lstrip(" ")) |
| 59 | if indent > run_indent: |
| 60 | continue |
| 61 | looks_like_yaml = bool( |
| 62 | re.match(r"^\s*(- )?[A-Za-z_][\w-]*\s*:", line) |
| 63 | or re.match(r"^\s*-\s+\S", line) |
| 64 | or re.match(r"^\s+#", line) |
| 65 | ) |
| 66 | if indent == 0 or not looks_like_yaml: |
| 67 | raise AssertionError( |
| 68 | f"{label}:{lineno} under-indented inside run: | " |
| 69 | f"(indent={indent}, run_indent={run_indent}): {line!r}" |
| 70 | ) |
| 71 | in_run = False |
| 72 | |
| 73 | |
| 74 | # --------------------------------------------------------------------------- |
| 75 | # HIGH-223: Private mktemp dir + noclobber + cleanup for host thread envelopes |
| 76 | # --------------------------------------------------------------------------- |
| 77 | |
| 78 | |
| 79 | def test_no_predictable_tmp_envelope_paths_in_references() -> None: |
| 80 | for path in sorted(REFERENCES_DIR.glob("*.md")): |
| 81 | text = path.read_text(encoding="utf-8") |
| 82 | assert "/tmp/l30d-threads.json" not in text, path.name |
| 83 | assert "/tmp/l30d-shortform.json" not in text, path.name |
| 84 | |
| 85 | |
| 86 | def test_research_runbook_host_envelopes_use_private_mktemp_noclobber_and_cleanup() -> None: |
| 87 | runbook = reference_text("research-runbook") |
| 88 | section_2b = runbook.split("**2b. Host Reddit threads.**", 1)[1].split( |
| 89 | "**2c. Host TikTok/Instagram URLs.**", 1 |
| 90 | )[0] |
| 91 | section_2c = runbook.split("**2c. Host TikTok/Instagram URLs.**", 1)[1].split( |
| 92 | "**3. TikTok hashtags", 1 |
| 93 | )[0] |
| 94 | |
| 95 | assert 'mktemp -d "${TMPDIR:-/tmp}/last30days-envelopes.XXXXXX"' in section_2b |
| 96 | assert 'if [ "${_L30D_TMP_PID:-}" != "$$" ] || [ -z "${_L30D_TMP_DIR:-}" ]; then' in section_2b |
| 97 | assert 'REDDIT_THREADS_DIR="$_L30D_TMP_DIR"' in section_2b |
| 98 | assert 'REDDIT_THREADS_FILE="$REDDIT_THREADS_DIR/threads.json"' in section_2b |
| 99 | assert 'trap \'rm -rf -- "$_L30D_TMP_DIR"\' EXIT' in section_2b |
| 100 | assert "cat >| \"$REDDIT_THREADS_FILE\" <<'THREADS_EOF_{NONCE}'" in section_2b |
| 101 | assert '--reddit-threads="$REDDIT_THREADS_FILE"' in section_2b |
| 102 | |
| 103 | assert "mktemp -d" in section_2c |
| 104 | assert "EXIT" in section_2c |
| 105 | assert ">|" in section_2c |
| 106 | assert "$_L30D_TMP_DIR" in section_2c and '_L30D_TMP_PID == "$$"' in section_2c |
| 107 | assert '--shortform-urls="$SHORTFORM_FILE"' in section_2c |
| 108 | |
| 109 | |
| 110 | @pytest.mark.parametrize("order", ["x_then_reddit", "reddit_then_x"]) |
| 111 | def test_grok_bot_x_and_reddit_threads_traps_clean_up_all_temp_dirs_in_both_orders( |
| 112 | tmp_path: Path, order: str |
| 113 | ) -> None: |
| 114 | runbook = reference_text("research-runbook") |
| 115 | section_2b = runbook.split("**2b. Host Reddit threads.**", 1)[1].split( |
| 116 | "**2c. Host TikTok/Instagram URLs.**", 1 |
| 117 | )[0] |
| 118 | reddit_block = _extract_bash_blocks(section_2b)[0] |
| 119 | reddit_block = reddit_block.replace("{NONCE}", "Ab12Cd34Ef56") |
| 120 | reddit_block = re.sub( |
| 121 | r'\{"schema": "last30days-reddit-threads/1".*\}', |
| 122 | lambda _: json.dumps( |
| 123 | { |
| 124 | "schema": "last30days-reddit-threads/1", |
| 125 | "topic": "test topic", |
| 126 | "threads": [ |
| 127 | {"url": "https://www.reddit.com/r/python/comments/abc123/test_post/"} |
| 128 | ], |
| 129 | } |
| 130 | ), |
| 131 | reddit_block, |
| 132 | ) |
| 133 | |
| 134 | grok_block = _extract_bash_blocks(reference_text("grok-bot-x"))[0] |
| 135 | grok_block = grok_block.replace("{X_POSTS_NONCE}", "Zy98Xw76Vu54").replace( |
| 136 | "{X_POSTS_ENVELOPE_JSON}", |
| 137 | json.dumps({"schema": "last30days-x-posts/1", "topic": "test topic", "calls": []}), |
| 138 | ) |
| 139 | |
| 140 | combined = ( |
| 141 | grok_block + "\n" + reddit_block |
| 142 | if order == "x_then_reddit" |
| 143 | else reddit_block + "\n" + grok_block |
| 144 | ) |
| 145 | script = ( |
| 146 | "set -euo pipefail\n" |
| 147 | "set -o noclobber\n" |
| 148 | + combined |
| 149 | + "\n" |
| 150 | + 'test -f "$X_POSTS_FILE"\n' |
| 151 | + 'test -f "$REDDIT_THREADS_FILE"\n' |
| 152 | + 'printf "X_DIR=%s\\nR_DIR=%s\\n" "$X_POSTS_DIR" "$REDDIT_THREADS_DIR"\n' |
| 153 | ) |
| 154 | result = subprocess.run( |
| 155 | ["bash", "-c", script], |
| 156 | capture_output=True, |
| 157 | text=True, |
| 158 | env={**os.environ, "TMPDIR": str(tmp_path)}, |
| 159 | timeout=30, |
| 160 | ) |
| 161 | assert result.returncode == 0, result.stdout + result.stderr |
| 162 | |
| 163 | x_dir = Path(re.search(r"^X_DIR=(.+)$", result.stdout, re.MULTILINE).group(1)) |
| 164 | r_dir = Path(re.search(r"^R_DIR=(.+)$", result.stdout, re.MULTILINE).group(1)) |
| 165 | assert not x_dir.exists(), f"X_POSTS_DIR leaked for order={order}: {x_dir}" |
| 166 | assert not r_dir.exists(), f"REDDIT_THREADS_DIR leaked for order={order}: {r_dir}" |
| 167 | assert list(tmp_path.iterdir()) == [], f"Leftover temp dirs in TMPDIR: {list(tmp_path.iterdir())}" |
| 168 | |
| 169 | |
| 170 | def test_envelope_snippets_never_delete_preexisting_env_dirs( |
| 171 | tmp_path: Path, |
| 172 | ) -> None: |
| 173 | """Ambient X_POSTS_DIR / REDDIT_THREADS_DIR / foreign _L30D_TMP_DIR must survive EXIT.""" |
| 174 | runbook = reference_text("research-runbook") |
| 175 | section_2b = runbook.split("**2b. Host Reddit threads.**", 1)[1].split( |
| 176 | "**2c. Host TikTok/Instagram URLs.**", 1 |
| 177 | )[0] |
| 178 | reddit_block = _extract_bash_blocks(section_2b)[0].replace("{NONCE}", "Ab12Cd34Ef56") |
| 179 | reddit_block = re.sub( |
| 180 | r'\{"schema": "last30days-reddit-threads/1".*\}', |
| 181 | lambda _: json.dumps( |
| 182 | { |
| 183 | "schema": "last30days-reddit-threads/1", |
| 184 | "topic": "test topic", |
| 185 | "threads": [ |
| 186 | {"url": "https://www.reddit.com/r/python/comments/abc123/test_post/"} |
| 187 | ], |
| 188 | } |
| 189 | ), |
| 190 | reddit_block, |
| 191 | ) |
| 192 | grok_block = ( |
| 193 | _extract_bash_blocks(reference_text("grok-bot-x"))[0] |
| 194 | .replace("{X_POSTS_NONCE}", "Zy98Xw76Vu54") |
| 195 | .replace( |
| 196 | "{X_POSTS_ENVELOPE_JSON}", |
| 197 | json.dumps({"schema": "last30days-x-posts/1", "topic": "test topic", "calls": []}), |
| 198 | ) |
| 199 | ) |
| 200 | |
| 201 | for label, snippet in (("reddit", reddit_block), ("grok", grok_block)): |
| 202 | work_tmp = tmp_path / f"{label}-tmp" |
| 203 | work_tmp.mkdir() |
| 204 | keep_x = tmp_path / f"{label}-keep-x" |
| 205 | keep_r = tmp_path / f"{label}-keep-reddit" |
| 206 | keep_foreign = tmp_path / f"{label}-keep-foreign" |
| 207 | for d in (keep_x, keep_r, keep_foreign): |
| 208 | d.mkdir() |
| 209 | (d / "sentinel.txt").write_text("keep", encoding="utf-8") |
| 210 | result = subprocess.run( |
| 211 | ["bash", "-euo", "pipefail", "-c", f"set -o noclobber\n{snippet}"], |
| 212 | capture_output=True, |
| 213 | text=True, |
| 214 | env={ |
| 215 | **os.environ, |
| 216 | "TMPDIR": str(work_tmp), |
| 217 | "X_POSTS_DIR": str(keep_x), |
| 218 | "REDDIT_THREADS_DIR": str(keep_r), |
| 219 | "_L30D_TMP_DIR": str(keep_foreign), |
| 220 | "_L30D_TMP_PID": "1", |
| 221 | }, |
| 222 | timeout=15, |
| 223 | ) |
| 224 | assert result.returncode == 0, result.stdout + result.stderr |
| 225 | for d in (keep_x, keep_r, keep_foreign): |
| 226 | assert (d / "sentinel.txt").read_text(encoding="utf-8") == "keep", ( |
| 227 | f"{label} snippet deleted pre-existing dir: {d}" |
| 228 | ) |
| 229 | assert list(work_tmp.iterdir()) == [], ( |
| 230 | f"{label} snippet leaked freshly created temp dir in {work_tmp}" |
| 231 | ) |
| 232 | |
| 233 | |
| 234 | def test_research_runbook_host_threads_snippet_runs_under_noclobber_and_cleans_up( |
| 235 | tmp_path: Path, |
| 236 | ) -> None: |
| 237 | runbook = reference_text("research-runbook") |
| 238 | section_2b = runbook.split("**2b. Host Reddit threads.**", 1)[1].split( |
| 239 | "**2c. Host TikTok/Instagram URLs.**", 1 |
| 240 | )[0] |
| 241 | blocks = _extract_bash_blocks(section_2b) |
| 242 | assert len(blocks) == 1 |
| 243 | |
| 244 | canary = tmp_path / "pwned" |
| 245 | hostile_topic = f'topic $(touch "{canary}") `id` $HOME' |
| 246 | payload = json.dumps( |
| 247 | { |
| 248 | "schema": "last30days-reddit-threads/1", |
| 249 | "topic": hostile_topic, |
| 250 | "threads": [ |
| 251 | {"url": "https://www.reddit.com/r/python/comments/abc123/test_post/"} |
| 252 | ], |
| 253 | } |
| 254 | ) |
| 255 | snippet = blocks[0].replace("{NONCE}", "Ab12Cd34Ef56") |
| 256 | snippet = re.sub( |
| 257 | r'\{"schema": "last30days-reddit-threads/1".*\}', |
| 258 | lambda _: payload, |
| 259 | snippet, |
| 260 | ) |
| 261 | |
| 262 | script = ( |
| 263 | "set -euo pipefail\n" |
| 264 | "set -o noclobber\n" |
| 265 | + snippet |
| 266 | + "\n" |
| 267 | + 'printf "DIR=%s\\nFILE=%s\\n" "$REDDIT_THREADS_DIR" "$REDDIT_THREADS_FILE"\n' |
| 268 | + f'"{sys.executable}" -c ' |
| 269 | + "'import sys; sys.path.insert(0, sys.argv[1]); " |
| 270 | + "from lib import reddit_envelope; " |
| 271 | + "env = reddit_envelope.read(sys.argv[2], sys.argv[3]); " |
| 272 | + "assert len(env.refs) == 1 and env.refs[0].post_id == \"abc123\"' " |
| 273 | + f'"{SKILL_ROOT / "scripts"}" "$REDDIT_THREADS_FILE" "$HOSTILE_TOPIC"\n' |
| 274 | ) |
| 275 | result = subprocess.run( |
| 276 | ["bash", "-c", script], |
| 277 | capture_output=True, |
| 278 | text=True, |
| 279 | env={ |
| 280 | **os.environ, |
| 281 | "TMPDIR": str(tmp_path), |
| 282 | "HOSTILE_TOPIC": hostile_topic, |
| 283 | }, |
| 284 | timeout=30, |
| 285 | ) |
| 286 | assert result.returncode == 0, result.stdout + result.stderr |
| 287 | assert not canary.exists() |
| 288 | |
| 289 | dir_match = re.search(r"^DIR=(.+)$", result.stdout, re.MULTILINE) |
| 290 | file_match = re.search(r"^FILE=(.+)$", result.stdout, re.MULTILINE) |
| 291 | assert dir_match and file_match |
| 292 | created_dir = Path(dir_match.group(1)) |
| 293 | created_file = Path(file_match.group(1)) |
| 294 | assert created_file.suffix == ".json" |
| 295 | assert created_file.parent == created_dir |
| 296 | assert not created_dir.exists(), "EXIT trap must remove the temporary directory" |
| 297 | |
| 298 | |
| 299 | # --------------------------------------------------------------------------- |
| 300 | # HIGH-224: Quoted heredoc + `--`/`=` separation in followups & library-queue |
| 301 | # --------------------------------------------------------------------------- |
| 302 | |
| 303 | |
| 304 | def test_followups_and_library_queue_eliminate_double_quoted_untrusted_interpolation() -> None: |
| 305 | followups = reference_text("followups") |
| 306 | library_queue = reference_text("library-queue") |
| 307 | |
| 308 | assert '--drill "<their target>"' not in followups |
| 309 | assert 'queue cover "<topic name>"' not in followups |
| 310 | assert 'queue cover "<topic name>"' not in library_queue |
| 311 | assert 'library search "${LIBRARY_QUERY}"' not in library_queue |
| 312 | |
| 313 | assert "IFS= read -r -d '' DRILL_TARGET <<'TARGET_EOF' || true" in followups |
| 314 | assert '--drill="$DRILL_TARGET"' in followups |
| 315 | assert "IFS= read -r -d '' TOPIC_NAME <<'TOPIC_EOF' || true" in followups |
| 316 | assert '--save-dir="${LAST30DAYS_MEMORY_DIR}" -- queue cover "$TOPIC_NAME"' in followups |
| 317 | |
| 318 | assert "IFS= read -r -d '' LIBRARY_QUERY <<'QUERY_EOF' || true" in library_queue |
| 319 | assert '--save-dir="${LAST30DAYS_MEMORY_DIR}" -- library search "$LIBRARY_QUERY"' in library_queue |
| 320 | assert "IFS= read -r -d '' TOPIC_NAME <<'TOPIC_EOF' || true" in library_queue |
| 321 | assert '--save-dir="${LAST30DAYS_MEMORY_DIR}" -- queue cover "$TOPIC_NAME"' in library_queue |
| 322 | |
| 323 | |
| 324 | def test_followups_and_library_queue_snippets_block_shell_and_flag_injection( |
| 325 | tmp_path: Path, |
| 326 | ) -> None: |
| 327 | probe_skill = tmp_path / "skill" |
| 328 | probe_scripts = probe_skill / "scripts" |
| 329 | probe_scripts.mkdir(parents=True) |
| 330 | (probe_scripts / "last30days.py").write_text( |
| 331 | "import json, sys\n" |
| 332 | f"sys.path.insert(0, {str(SKILL_ROOT / 'scripts')!r})\n" |
| 333 | "import last30days as cli\n" |
| 334 | "args, extra = cli.build_parser().parse_known_args(sys.argv[1:])\n" |
| 335 | "print(json.dumps({'topic': args.topic, 'drill': args.drill, " |
| 336 | "'followup_topic': args.followup_topic, 'followup_run': args.followup_run, " |
| 337 | "'save_dir': args.save_dir, 'extra': extra}))\n", |
| 338 | encoding="utf-8", |
| 339 | ) |
| 340 | |
| 341 | canary = tmp_path / "injected" |
| 342 | hostile = f"--mock $(touch {canary}) `touch {canary}` $HOME 'single' \"double\"" |
| 343 | env = { |
| 344 | **os.environ, |
| 345 | "LAST30DAYS_PYTHON": sys.executable, |
| 346 | "SKILL_DIR": str(probe_skill), |
| 347 | "LAST30DAYS_MEMORY_DIR": str(tmp_path / "memory"), |
| 348 | "FOLLOWUP_CACHE_ID": "0123456789abcdef0123456789abcdef", |
| 349 | } |
| 350 | |
| 351 | followups_blocks = _extract_bash_blocks(reference_text("followups")) |
| 352 | assert len(followups_blocks) == 2 |
| 353 | |
| 354 | # 1. followups.md --drill block |
| 355 | drill_script = ( |
| 356 | followups_blocks[0] |
| 357 | .replace("<their target>", hostile) |
| 358 | .replace("<original topic>", hostile) |
| 359 | ) |
| 360 | res = subprocess.run(["bash", "-euo", "pipefail", "-c", drill_script], capture_output=True, text=True, env=env, timeout=30) |
| 361 | assert res.returncode == 0, res.stdout + res.stderr |
| 362 | assert not canary.exists() |
| 363 | parsed = json.loads(res.stdout) |
| 364 | assert parsed["drill"] == hostile |
| 365 | assert parsed["followup_topic"] == hostile |
| 366 | assert parsed["extra"] == [] |
| 367 | |
| 368 | # 2. followups.md queue cover block |
| 369 | cover_script = followups_blocks[1].replace("<topic name>", hostile) |
| 370 | res = subprocess.run(["bash", "-euo", "pipefail", "-c", cover_script], capture_output=True, text=True, env=env, timeout=30) |
| 371 | assert res.returncode == 0, res.stdout + res.stderr |
| 372 | assert not canary.exists() |
| 373 | parsed = json.loads(res.stdout) |
| 374 | assert parsed["topic"] == ["queue", "cover", hostile] |
| 375 | assert parsed["save_dir"] == str(tmp_path / "memory") |
| 376 | assert parsed["extra"] == [] |
| 377 | |
| 378 | # 3. library-queue.md library search & queue cover blocks |
| 379 | lq_blocks = _extract_bash_blocks(reference_text("library-queue")) |
| 380 | search_block = next(b for b in lq_blocks if "library search" in b) |
| 381 | lq_cover_block = next(b for b in lq_blocks if "queue cover" in b) |
| 382 | |
| 383 | res = subprocess.run( |
| 384 | ["bash", "-euo", "pipefail", "-c", search_block.replace("<query>", hostile)], |
| 385 | capture_output=True, |
| 386 | text=True, |
| 387 | env=env, |
| 388 | timeout=30, |
| 389 | ) |
| 390 | assert res.returncode == 0, res.stdout + res.stderr |
| 391 | assert not canary.exists() |
| 392 | parsed = json.loads(res.stdout) |
| 393 | assert parsed["topic"] == ["library", "search", hostile] |
| 394 | assert parsed["save_dir"] == str(tmp_path / "memory") |
| 395 | assert parsed["extra"] == [] |
| 396 | |
| 397 | res = subprocess.run( |
| 398 | ["bash", "-euo", "pipefail", "-c", lq_cover_block.replace("<topic name>", hostile)], |
| 399 | capture_output=True, |
| 400 | text=True, |
| 401 | env=env, |
| 402 | timeout=30, |
| 403 | ) |
| 404 | assert res.returncode == 0, res.stdout + res.stderr |
| 405 | assert not canary.exists() |
| 406 | parsed = json.loads(res.stdout) |
| 407 | assert parsed["topic"] == ["queue", "cover", hostile] |
| 408 | assert parsed["save_dir"] == str(tmp_path / "memory") |
| 409 | assert parsed["extra"] == [] |
| 410 | |
| 411 | |
| 412 | # --------------------------------------------------------------------------- |
| 413 | # HIGH-225: Release workflow tag validation, refs/tags/ pin & zizmor hygiene |
| 414 | # --------------------------------------------------------------------------- |
| 415 | |
| 416 | |
| 417 | def test_release_workflow_structure_permissions_pinning_and_zizmor_safety() -> None: |
| 418 | text = RELEASE_WORKFLOW.read_text(encoding="utf-8") |
| 419 | _assert_run_blocks_indented(text, label=str(RELEASE_WORKFLOW)) |
| 420 | workflow = yaml.safe_load(text) |
| 421 | |
| 422 | assert workflow.get("permissions") == {} |
| 423 | assert "env" not in workflow, "Untrusted RELEASE_TAG must not be exported workflow-wide" |
| 424 | |
| 425 | jobs = workflow["jobs"] |
| 426 | assert "validate" in jobs |
| 427 | validate_job = jobs["validate"] |
| 428 | assert validate_job["permissions"] == {"contents": "read"} |
| 429 | assert set(validate_job.get("outputs", {}).keys()) >= {"tag", "version", "commit"} |
| 430 | |
| 431 | for gated_job in ("build-skill", "build-mcpb", "build-rust-core"): |
| 432 | needs = jobs[gated_job].get("needs") |
| 433 | needs_list = [needs] if isinstance(needs, str) else list(needs or []) |
| 434 | assert "validate" in needs_list, f"{gated_job} must depend on validate" |
| 435 | |
| 436 | release_needs = jobs["release"].get("needs") or [] |
| 437 | assert {"validate", "build-skill", "build-mcpb", "build-rust-core"} <= set(release_needs) |
| 438 | |
| 439 | checkout_count = 0 |
| 440 | for job_name, job in jobs.items(): |
| 441 | for step in job.get("steps", []): |
| 442 | if "uses" in step: |
| 443 | ref = step["uses"] |
| 444 | _, _, sha = ref.partition("@") |
| 445 | assert len(sha) == 40 and all(c in "0123456789abcdef" for c in sha), ( |
| 446 | f"{job_name}: unpinned action {ref}" |
| 447 | ) |
| 448 | if ref.startswith("actions/checkout@"): |
| 449 | checkout_count += 1 |
| 450 | with_cfg = step.get("with") or {} |
| 451 | assert with_cfg.get("persist-credentials") is False |
| 452 | checkout_ref = str(with_cfg.get("ref", "")) |
| 453 | assert checkout_ref.startswith("refs/tags/${{"), ( |
| 454 | f"{job_name}: checkout ref must pin refs/tags/, got {checkout_ref!r}" |
| 455 | ) |
| 456 | if "run" in step: |
| 457 | run_body = step["run"] |
| 458 | assert "${{" not in run_body, ( |
| 459 | f"{job_name}/{step.get('name')}: never inline GitHub expressions in run:" |
| 460 | ) |
| 461 | |
| 462 | assert checkout_count == 5 |
| 463 | |
| 464 | mcpb_build_step = next( |
| 465 | s for s in jobs["build-mcpb"]["steps"] if s.get("name") == "Build MCP binary" |
| 466 | ) |
| 467 | assert "^v[0-9]+\\.[0-9]+\\.[0-9]+$" in mcpb_build_step["run"] |
| 468 | |
| 469 | |
| 470 | @pytest.mark.parametrize( |
| 471 | "raw_tag,expected_ok", |
| 472 | [ |
| 473 | ("v4.6.0", True), |
| 474 | ("v0.0.1", True), |
| 475 | ("v12.34.56", True), |
| 476 | ("", False), |
| 477 | ("4.6.0", False), |
| 478 | ("main", False), |
| 479 | ("48385610", False), |
| 480 | ("refs/tags/v4.6.0", False), |
| 481 | ("v4.6.0 -extldflags=-Wl,--evil", False), |
| 482 | ("v4.6.0 -X main.Version=pwn", False), |
| 483 | ("v4.6.0$(id)", False), |
| 484 | ("v4.6.0;id", False), |
| 485 | ("v4.6.0`id`", False), |
| 486 | ('v4.6.0"quoted', False), |
| 487 | ("v4.6.0..main", False), |
| 488 | ("v4.6.0\nv4.6.1", False), |
| 489 | ], |
| 490 | ) |
| 491 | def test_release_workflow_tag_format_step_executes_strict_validation( |
| 492 | tmp_path: Path, raw_tag: str, expected_ok: bool |
| 493 | ) -> None: |
| 494 | workflow = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8")) |
| 495 | step = next( |
| 496 | s for s in workflow["jobs"]["validate"]["steps"] if s.get("id") == "format" |
| 497 | ) |
| 498 | gh_output = tmp_path / "github_output" |
| 499 | gh_output.write_text("", encoding="utf-8") |
| 500 | |
| 501 | result = subprocess.run( |
| 502 | ["bash", "-c", step["run"]], |
| 503 | capture_output=True, |
| 504 | text=True, |
| 505 | env={ |
| 506 | **os.environ, |
| 507 | "RAW_RELEASE_TAG": raw_tag, |
| 508 | "GITHUB_OUTPUT": str(gh_output), |
| 509 | }, |
| 510 | timeout=15, |
| 511 | ) |
| 512 | if expected_ok: |
| 513 | assert result.returncode == 0, result.stdout + result.stderr |
| 514 | output = gh_output.read_text(encoding="utf-8") |
| 515 | assert f"tag={raw_tag}\n" in output |
| 516 | assert f"version={raw_tag[1:]}\n" in output |
| 517 | else: |
| 518 | assert result.returncode != 0, f"Expected rejection for {raw_tag!r}" |
| 519 | assert gh_output.read_text(encoding="utf-8") == "" |
| 520 | |
| 521 | |
| 522 | def test_release_workflow_verify_step_checks_git_tag_and_manifest_versions( |
| 523 | tmp_path: Path, |
| 524 | ) -> None: |
| 525 | workflow = yaml.safe_load(RELEASE_WORKFLOW.read_text(encoding="utf-8")) |
| 526 | step = next( |
| 527 | s for s in workflow["jobs"]["validate"]["steps"] if s.get("id") == "verify" |
| 528 | ) |
| 529 | |
| 530 | repo = tmp_path / "repo" |
| 531 | (repo / ".github" / "scripts").mkdir(parents=True) |
| 532 | (repo / "mcp").mkdir() |
| 533 | shutil.copy2( |
| 534 | ROOT / ".github" / "scripts" / "read_manifest_version.py", |
| 535 | repo / ".github" / "scripts" / "read_manifest_version.py", |
| 536 | ) |
| 537 | (repo / "pyproject.toml").write_text('[project]\nversion = "4.6.0"\n', encoding="utf-8") |
| 538 | (repo / "mcp" / "manifest.json").write_text( |
| 539 | json.dumps({"manifest_version": "0.3", "version": "4.6.0"}) + "\n", |
| 540 | encoding="utf-8", |
| 541 | ) |
| 542 | |
| 543 | git_env = { |
| 544 | **os.environ, |
| 545 | "HOME": str(tmp_path), |
| 546 | "GIT_CONFIG_GLOBAL": os.devnull, |
| 547 | "GIT_CONFIG_NOSYSTEM": "1", |
| 548 | } |
| 549 | for cmd in ( |
| 550 | ["git", "-c", "init.templateDir=", "init", "-q"], |
| 551 | ["git", "add", "."], |
| 552 | [ |
| 553 | "git", |
| 554 | "-c", "user.name=Test", |
| 555 | "-c", "user.email=test@example.invalid", |
| 556 | "-c", "commit.gpgsign=false", |
| 557 | "commit", "-qm", "Initial", |
| 558 | ], |
| 559 | ): |
| 560 | subprocess.run(cmd, cwd=repo, env=git_env, check=True) |
| 561 | |
| 562 | def run_verify(tag: str, version: str) -> tuple[int, str, str]: |
| 563 | gh_out = tmp_path / f"out-{tag}-{version}" |
| 564 | gh_out.write_text("", encoding="utf-8") |
| 565 | proc = subprocess.run( |
| 566 | ["bash", "-c", step["run"]], |
| 567 | cwd=repo, |
| 568 | capture_output=True, |
| 569 | text=True, |
| 570 | env={ |
| 571 | **git_env, |
| 572 | "RELEASE_TAG": tag, |
| 573 | "RELEASE_VERSION": version, |
| 574 | "GITHUB_OUTPUT": str(gh_out), |
| 575 | }, |
| 576 | timeout=15, |
| 577 | ) |
| 578 | return proc.returncode, proc.stdout + proc.stderr, gh_out.read_text(encoding="utf-8") |
| 579 | |
| 580 | # 1. Missing git tag (even if a branch with that name exists) -> must fail. |
| 581 | subprocess.run(["git", "branch", "v4.6.0"], cwd=repo, env=git_env, check=True) |
| 582 | rc, _, _ = run_verify("v4.6.0", "4.6.0") |
| 583 | assert rc != 0 |
| 584 | |
| 585 | # 2. Real git tag matching both manifests -> passes and emits commit SHA. |
| 586 | subprocess.run( |
| 587 | [ |
| 588 | "git", |
| 589 | "-c", "user.name=Test", |
| 590 | "-c", "user.email=test@example.invalid", |
| 591 | "-c", "tag.gpgSign=false", |
| 592 | "tag", "-a", "v4.6.0", "-m", "Release v4.6.0", |
| 593 | ], |
| 594 | cwd=repo, |
| 595 | env=git_env, |
| 596 | check=True, |
| 597 | ) |
| 598 | rc, msg, out = run_verify("v4.6.0", "4.6.0") |
| 599 | assert rc == 0, msg |
| 600 | assert "tag=v4.6.0\n" in out |
| 601 | assert "version=4.6.0\n" in out |
| 602 | assert re.search(r"^commit=[0-9a-f]{40}$", out, re.MULTILINE) |
| 603 | |
| 604 | # 3. mcp/manifest.json version mismatch -> fails. |
| 605 | (repo / "mcp" / "manifest.json").write_text( |
| 606 | json.dumps({"manifest_version": "0.3", "version": "4.5.0"}) + "\n", |
| 607 | encoding="utf-8", |
| 608 | ) |
| 609 | rc, msg, _ = run_verify("v4.6.0", "4.6.0") |
| 610 | assert rc != 0 and "mcp/manifest.json" in msg |
| 611 | |
| 612 | # 4. pyproject.toml version mismatch -> fails. |
| 613 | (repo / "mcp" / "manifest.json").write_text( |
| 614 | json.dumps({"manifest_version": "0.3", "version": "4.6.0"}) + "\n", |
| 615 | encoding="utf-8", |
| 616 | ) |
| 617 | (repo / "pyproject.toml").write_text('[project]\nversion = "4.5.0"\n', encoding="utf-8") |
| 618 | rc, msg, _ = run_verify("v4.6.0", "4.6.0") |
| 619 | assert rc != 0 and "pyproject.toml" in msg |
| 620 | |
| 621 | |
| 622 | # --------------------------------------------------------------------------- |
| 623 | # HIGH-226: Packaging / scanner ignore files exclude secrets & stay in parity |
| 624 | # --------------------------------------------------------------------------- |
| 625 | |
| 626 | |
| 627 | def test_all_ignore_files_exclude_secrets_keys_and_caches() -> None: |
| 628 | required_secrets = {".env", ".env.*", ".claude/", "*.pem", "*.key", "__pycache__/", "*.pyc"} |
| 629 | for path in ( |
| 630 | ROOT / ".skillignore", |
| 631 | ROOT / ".clawhubignore", |
| 632 | SKILL_ROOT / ".skillignore", |
| 633 | ): |
| 634 | entries = _ignore_entries(path) |
| 635 | missing = required_secrets - entries |
| 636 | assert not missing, f"{path.relative_to(ROOT)} missing secret/cache exclusions: {sorted(missing)}" |
| 637 | |
| 638 | |
| 639 | def test_root_skillignore_and_clawhubignore_stay_in_parity_with_dev_exclusions() -> None: |
| 640 | skillignore = _ignore_entries(ROOT / ".skillignore") |
| 641 | clawhubignore = _ignore_entries(ROOT / ".clawhubignore") |
| 642 | assert skillignore == clawhubignore |
| 643 | |
| 644 | required_root = { |
| 645 | ".env", |
| 646 | ".env.*", |
| 647 | ".claude/", |
| 648 | "*.pem", |
| 649 | "*.key", |
| 650 | ".entire/", |
| 651 | ".context/", |
| 652 | ".memsearch/", |
| 653 | ".pytest_cache/", |
| 654 | ".worktrees/", |
| 655 | ".codex-plugin/", |
| 656 | ".grok-plugin/", |
| 657 | "uv.lock", |
| 658 | "changelog.d/", |
| 659 | "CONTRIBUTING.md", |
| 660 | "SECURITY.md", |
| 661 | "README.*.md", |
| 662 | "skills/last30days/agents/", |
| 663 | "skills/last30days/scripts/reddit_canary.py", |
| 664 | "skills/last30days/scripts/x_lane_parity.py", |
| 665 | "skills/last30days/scripts/setup-keychain.sh", |
| 666 | "skills/last30days/scripts/setup-pass.sh", |
| 667 | } |
| 668 | assert required_root <= skillignore |
| 669 | |
| 670 | |
| 671 | def test_skill_dir_skillignore_reconciles_non_runtime_scripts_and_keeps_runtime() -> None: |
| 672 | root_entries = _ignore_entries(ROOT / ".skillignore") |
| 673 | skill_entries = _ignore_entries(SKILL_ROOT / ".skillignore") |
| 674 | |
| 675 | root_skill_scoped = { |
| 676 | entry.removeprefix("skills/last30days/") |
| 677 | for entry in root_entries |
| 678 | if entry.startswith("skills/last30days/") |
| 679 | } |
| 680 | assert root_skill_scoped <= skill_entries, ( |
| 681 | f"skills/last30days/.skillignore missing entries from root .skillignore: " |
| 682 | f"{sorted(root_skill_scoped - skill_entries)}" |
| 683 | ) |
| 684 | |
| 685 | for runtime_entry in ( |
| 686 | "SKILL.md", |
| 687 | "references/", |
| 688 | "scripts/", |
| 689 | "scripts/last30days.py", |
| 690 | "scripts/lib/", |
| 691 | "scripts/watchlist.py", |
| 692 | "scripts/store.py", |
| 693 | "scripts/briefing.py", |
| 694 | ): |
| 695 | assert runtime_entry not in skill_entries |
| 696 | assert f"skills/last30days/{runtime_entry}" not in root_entries |
| 697 |