diff options
Diffstat (limited to '.github/scripts')
| -rw-r--r-- | .github/scripts/sg_platform_annotate.py | 20 | ||||
| -rw-r--r-- | .github/scripts/sg_platform_compare.py | 143 | ||||
| -rw-r--r-- | .github/scripts/sg_platform_extras.py | 262 | ||||
| -rw-r--r-- | .github/scripts/sg_platform_sdk_bootstrap.py | 120 | ||||
| -rw-r--r-- | .github/scripts/sg_platform_store_cert.py | 219 |
5 files changed, 764 insertions, 0 deletions
diff --git a/.github/scripts/sg_platform_annotate.py b/.github/scripts/sg_platform_annotate.py new file mode 100644 index 00000000..e8567d81 --- /dev/null +++ b/.github/scripts/sg_platform_annotate.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Print ten chunks of a text file as notice annotations, starting at chunk N.""" +import sys + +CHUNK = 3600 # an annotation keeps 4096 bytes +lines = open(sys.argv[1], encoding="utf-8", errors="replace").read().splitlines() +chunks, current = [], "" +for line in lines: + if current and len((current + line).encode("utf-8")) + 1 > CHUNK: + chunks.append(current) + current = "" + current += line[:CHUNK] + "\n" +if current: + chunks.append(current) +first = int(sys.argv[2]) +for index in range(first, min(first + 10, len(chunks))): + body = chunks[index].replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print("::notice title=report %03d of %03d::%s" % (index + 1, len(chunks), body)) +if first == 0: + print("%d chunks, %d characters" % (len(chunks), sum(map(len, chunks)))) diff --git a/.github/scripts/sg_platform_compare.py b/.github/scripts/sg_platform_compare.py new file mode 100644 index 00000000..0d897775 --- /dev/null +++ b/.github/scripts/sg_platform_compare.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Print, per runner image, how each tested tree's suite differs from main's.""" +import os +import sys +import xml.etree.ElementTree as ET + + +SKIP_REASONS = {} +FAILURE_TEXT = {} +# Failing tests whose whole failure text is printed for every tree. +FULL_TEXT_FOR = ("test_agentic_commit_review_runs", "test_findings_not_replaced_by_the_inner_cli_warning") +FULL_TEXT = {} +# Trees whose behaviour-check output is printed: main and the pull requests the checks were written for. +EXTRAS_FOR = {"main", "6628", "6721", "6722", "6807", "6808", "6875", "6922"} +LATER = [] +FIRST = [] + + +def read_suite(folder): + path = os.path.join(folder, "junit.xml") + if not os.path.exists(path): + return None + outcomes = {} + for case in ET.parse(path).getroot().iter("testcase"): + name = "%s::%s" % (case.get("classname", ""), case.get("name", "")) + skipped = case.find("skipped") + failure = case.find("failure") if case.find("failure") is not None else case.find("error") + if failure is not None: + outcomes[name] = "failed" + FAILURE_TEXT[(folder, name)] = ( + (failure.text or failure.get("message", ""))[-3000:] + + "\n--- captured stderr ---\n" + (case.findtext("system-err") or "")[-1500:]) + FULL_TEXT[(folder, name)] = (failure.text or failure.get("message", ""))[-20000:] + elif skipped is not None: + outcomes[name] = "skipped" + SKIP_REASONS[name] = skipped.get("message", "") + else: + outcomes[name] = "passed" + return outcomes + + +def module_of(name): + """tests.test_x.TestY::test_z -> test_x; a module-level skip has no class part.""" + parts = [p for p in name.replace("::", ".").split(".") if p.startswith("test_")] + return parts[0] if parts else name + + +def read_text(folder, name): + try: + with open(os.path.join(folder, name), encoding="utf-8", errors="replace") as handle: + return handle.read().strip() + except OSError: + return "?" + + +def main(root): + trees = {} + for entry in sorted(os.listdir(root)): + if not entry.startswith("results-"): + continue + image, _, ref = entry[len("results-"):].rpartition("-") + trees.setdefault(image, {})[ref] = os.path.join(root, entry) + for entry in sorted(os.listdir(root)): + if entry.startswith("sdk-"): + for name in ("launcher-choice.txt", "sdk-bootstrap.txt"): + LATER.append("\n## %s: %s\n\n```\n%s\n```" % (entry[len("sdk-"):], name, read_text(os.path.join(root, entry), name))) + for image, refs in trees.items(): + base = read_suite(refs["main"]) if "main" in refs else None + print("\n## %s\n" % image) + print("| Tree | Commit | Passed | Failed | Skipped | Launch exit | Five launches | Fails here, not on main |") + print("|---|---|---|---|---|---|---|---|") + details, extra, skips = [], [], {} + base_modules = {module_of(n) for n in base or {}} + for ref in sorted(refs, key=lambda r: (r != "main", r)): + suite = read_suite(refs[ref]) + sha = read_text(refs[ref], "sha")[:8] + launch = read_text(refs[ref], "launch.exit") + timing = [ln.split(": ")[1] for ln in read_text(refs[ref], "launch.txt").splitlines() + if ln.startswith("five launches")] + launch = "%s | %s" % (launch, timing[0] if timing else "?") + if suite is None: + print("| %s | %s | no result | | | %s | |" % (ref, sha, launch)) + continue + failed = sorted(n for n, o in suite.items() if o == "failed") + counts = [sum(1 for o in suite.values() if o == kind) for kind in ("passed", "failed", "skipped")] + if ref == "main" or base is None: + added = [] + cell = "baseline" if ref == "main" else "no baseline" + else: + added = [n for n in failed if base.get(n) != "failed"] + cell = str(len(added)) + print("| %s | %s | %d | %d | %d | %s | %s |" % (ref, sha, counts[0], counts[1], counts[2], launch, cell)) + for name in failed: + if name.endswith(FULL_TEXT_FOR): + FIRST.append("\n## %s, %s: `%s` (whole failure text)\n\n```\n%s\n```" + % (image, ref, name, FULL_TEXT.get((refs[ref], name), ""))) + if ref == "main": + details.append(("main (baseline failures)", failed)) + elif added: + marked = ["%s%s" % (n, "" if n in base else " (new test)") for n in added] + details.append((ref, marked)) + seen = set() + for name in added: + text = FAILURE_TEXT.get((refs[ref], name), "") + last = text.strip().splitlines()[-1:] or [""] + if last[0][:60] not in seen: + seen.add(last[0][:60]) + FIRST.append("\n## %s, %s: `%s` (end of the failure text)\n\n```\n%s\n```" + % (image, ref, name, text)) + if base is not None and ref != "main": + per_file = {} + for name, outcome in suite.items(): + module = module_of(name) + if module not in base_modules: + per_file.setdefault(module, {"passed": 0, "failed": 0, "skipped": 0})[outcome] += 1 + for module, tally in sorted(per_file.items()): + extra.append("- %s adds `%s`: %d passed, %d failed, %d skipped" + % (ref, module, tally["passed"], tally["failed"], tally["skipped"])) + for name in sorted(n for n, o in suite.items() if o == "skipped"): + skips.setdefault("%s: %s" % (name, SKIP_REASONS.get(name, "")), []).append(ref) + for title, names in details: + print("\n**%s**\n" % title) + for name in names: + print("- `%s`" % name) + if extra: + print("\n**Test files a tree adds over main**\n") + print("\n".join(extra)) + if skips: + print("\n**Skipped tests (trees)**\n") + for text, where in sorted(skips.items()): + print("- `%s` (%s)" % (text, ", ".join(where))) + for ref in sorted(refs, key=lambda r: (r != "main", r)): + if read_text(refs[ref], "launch.exit") != "0" or ref == "main": + print("\n**%s launcher**\n\n```\n%s\n```" % (ref, read_text(refs[ref], "launch.txt"))) + for ref in sorted(refs, key=lambda r: (r != "main", r)): + if ref in EXTRAS_FOR: + LATER.append("\n## %s, %s: behaviour checks\n\n```\n%s\n```" + % (image, ref, read_text(refs[ref], "extras.txt"))) + print("\n".join(FIRST + LATER)) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/.github/scripts/sg_platform_extras.py b/.github/scripts/sg_platform_extras.py new file mode 100644 index 00000000..6240dbf6 --- /dev/null +++ b/.github/scripts/sg_platform_extras.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Behaviour checks for one checkout of the security-guidance plugin that the +unit suite does not make on its own: path handling with platform spellings, +files written by other tools, and the Stop hook's memory on large new files. + + sg_platform_extras.py <plugin dir> [--memory] + +Every check prints what it saw. A check whose code is not in this checkout +prints "not in this tree". Nothing here decides pass or fail.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time + +PLUGIN = os.path.abspath(sys.argv[1]) +HOOKS = os.path.join(PLUGIN, "hooks") +TESTS = os.path.join(PLUGIN, "tests") +WINDOWS = os.name == "nt" + + +def snippet(title, code, env=None, cwd=None): + """Run `code` in a fresh interpreter with the hooks folder importable.""" + print("\n### %s\n" % title, flush=True) + full_env = dict(os.environ, PYTHONPATH=os.pathsep.join([HOOKS, TESTS]), + PYTHONDONTWRITEBYTECODE="1", PYTHONIOENCODING="utf-8") + full_env.update(env or {}) + r = subprocess.run([sys.executable, "-c", textwrap.dedent(code)], env=full_env, + cwd=cwd, capture_output=True, text=True, encoding="utf-8", + errors="replace", timeout=900) + print(r.stdout.rstrip()) + if r.returncode or r.stderr.strip(): + print("exit=%d stderr:\n%s" % (r.returncode, r.stderr.rstrip())) + sys.stdout.flush() + + +def inflight_markers(): + snippet("In-flight review markers without fcntl", """ + import importlib.util, os, subprocess, tempfile + import diffstate + if not hasattr(diffstate, "_mark_inflight"): + raise SystemExit("not in this tree") + d = tempfile.mkdtemp() + subprocess.run(["git", "init", "-q", d], check=True) + r = diffstate._mark_inflight(d, ["a" * 40]) + print("fcntl", importlib.util.find_spec("fcntl") is not None) + print("returned", r) + print("held", len(diffstate._inflight_held)) + print("markers", [n for n in os.listdir(os.path.join(d, ".git")) if n.startswith("sg-inflight-")]) + """) + + +def secret_paths(): + snippet("Secret-shaped and secret-named paths", r""" + import gitutil + shaped = [".credentials.json", ".claude.json", r"C:\Users\x\.claude\.credentials.json", + ".CREDENTIALS.JSON", "config/credentials.json", r"src\claude.json"] + for p in shaped: + print("shaped", repr(p), gitutil._is_secret_shaped(p)) + if not hasattr(gitutil, "_is_secret_named"): + raise SystemExit("_is_secret_named: not in this tree") + named = ["secrets.yml", r"config\secrets.yml", "Credentials.JSON", "client_secret_123.apps.json", + "service-account.json", "secrets.example.yml", "secrets.enc.yaml", "secretsmanager.py", + "secret.txt"] + for p in named: + print("named", repr(p), gitutil._is_secret_named(p)) + print("count", gitutil.count_secret_named([("a\\secrets.yml", ""), ("b.py", "")])) + """) + + +def patterns_files(): + home = tempfile.mkdtemp(prefix="sg-home-") + valid = json.dumps({"patterns": [{"rule_name": "demo_rule", "regex": "AKIA[0-9A-Z]{16}", + "reminder": "DEMO_RULE_REMINDER"}]}) + load = """ + import sys + import extensibility + extensibility.load_for_session(sys.argv[1] if len(sys.argv) > 1 else %r) + print("loaded", [r["ruleName"] for r in extensibility.user_patterns()]) + """ + cases = [("local file is [1,2], written as UTF-8", "[1,2]", None)] + if WINDOWS and shutil.which("powershell.exe"): + cases.append(("local file is [1,2], written by Windows PowerShell Set-Content -Encoding Unicode", + "[1,2]", "Unicode")) + cases.append(("local file is a valid rule file, written by Windows PowerShell Set-Content -Encoding Unicode", + valid.replace("demo_rule", "local_rule"), "Unicode")) + for title, body, encoding in cases: + proj = tempfile.mkdtemp(prefix="sg-proj-") + subprocess.run(["git", "init", "-q", proj], check=True) + os.makedirs(os.path.join(proj, ".claude")) + with open(os.path.join(proj, ".claude", "security-patterns.json"), "w") as handle: + handle.write(valid) + local = os.path.join(proj, ".claude", "security-patterns.local.json") + if encoding: + subprocess.run(["powershell.exe", "-NoProfile", "-Command", + "Set-Content -Encoding %s -Path $env:SG_LOCAL -Value $env:SG_BODY" % encoding], + env=dict(os.environ, SG_LOCAL=local, SG_BODY=body), check=True) + else: + with open(local, "w") as handle: + handle.write(body) + with open(local, "rb") as handle: + print("\nfirst bytes of the local file:", handle.read(8)) + env = {"HOME": home, "USERPROFILE": home, "CLAUDE_CONFIG_DIR": ""} + snippet("Pattern files: " + title, load % proj, env=env, cwd=proj) + + +def review_scope(): + root = os.path.realpath(tempfile.mkdtemp(prefix="sg-Scope-")) + repo = os.path.join(root, "Root") + out = os.path.join(root, "Out") + os.makedirs(os.path.join(repo, "src")) + os.makedirs(out) + subprocess.run(["git", "init", "-q", repo], check=True) + with open(os.path.join(repo, "src", "app.py"), "w") as handle: + handle.write("x = 1\n") + snippet("Review scope: path spellings", r""" + import os, sys + import diffstate + if not hasattr(diffstate, "touched_scope"): + raise SystemExit("not in this tree") + from diffstate import touched_scope, review_scope_code + ROOT, OUT = sys.argv[1] if len(sys.argv) > 1 else %r, %r + app = os.path.join(ROOT, "src", "app.py") + def show(label, *args): + try: + print(label, touched_scope(*args)) + except Exception as e: + print(label, "EXCEPTION", type(e).__name__, e) + show("a absolute", ROOT, ROOT, [app]) + show("b case changed", ROOT.swapcase(), ROOT.swapcase(), [os.path.join(ROOT.swapcase(), "SRC", "APP.PY")]) + show("b root as given, path case changed", ROOT, ROOT, [os.path.join(ROOT, "SRC", "APP.PY")]) + show("c relative", ROOT, ROOT, ["src/app.py"]) + show("d outside", ROOT, ROOT, [os.path.join(OUT, "x.py")]) + show("d mixed", ROOT, ROOT, [app, os.path.join(OUT, "x.py")]) + show("d none", ROOT, ROOT, []) + if os.name == "nt": + show("e forward slashes", ROOT.replace("\\", "/"), ROOT.replace("\\", "/"), [app.replace("\\", "/")]) + show("e backslashes", ROOT.replace("/", "\\"), ROOT.replace("/", "\\"), [app.replace("/", "\\")]) + show("e other drive", ROOT, ROOT, ["Q:\\x.py"]) + import ctypes + buf = ctypes.create_unicode_buffer(1024) + n = ctypes.windll.kernel32.GetShortPathNameW(ROOT, buf, 1024) + short = buf.value if n else "" + print("e short form:", short if short and short != ROOT else "none different from the long form") + if short and short != ROOT: + show("e short root", short, short, [app]) + s, inside = touched_scope(ROOT, ROOT, [app]) + print("g one file", review_scope_code(ROOT, s, inside, ["src/app.py"], 0)) + print("g with untouched", review_scope_code(ROOT, s, inside, ["src/app.py", "other.py"], 0)) + print("g case changed", review_scope_code(ROOT, s, inside, ["SRC/App.py"], 0)) + print("g base_fail 1", review_scope_code(ROOT, s, inside, ["src/app.py"], 1)) + """ % (repo, out)) + + +def peak_memory_mb(proc): + if WINDOWS: + import ctypes + from ctypes import wintypes + + class Counters(ctypes.Structure): + _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)] + [ + (name, ctypes.c_size_t) for name in ( + "PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage", + "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage", + "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage")] + + counters = Counters() + counters.cb = ctypes.sizeof(counters) + call = ctypes.windll.kernel32.K32GetProcessMemoryInfo + call.argtypes = [wintypes.HANDLE, ctypes.POINTER(Counters), wintypes.DWORD] + if not call(int(proc._handle), ctypes.byref(counters), counters.cb): + return -1 + return counters.PeakWorkingSetSize / 1e6 + import resource + peak = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss + return peak / (1e6 if sys.platform == "darwin" else 1e3) + + +def stop_memory(): + """Peak memory of the Stop hook's own process on a turn that adds four + 50 MB data files next to one changed source file.""" + sys.path[:0] = [HOOKS, TESTS] + import http.server + import threading + from pathlib import Path + import conftest + + for kind in ("txt", "json"): + print("\n### Stop hook memory: four 50 MB .%s files\n" % kind, flush=True) + work = Path(tempfile.mkdtemp(prefix="sg-mem-")) + repo = conftest.make_repo(work / "repo", {"app.py": "print('hi')\n"}) + state = work / "state" + state.mkdir() + server = http.server.HTTPServer(("127.0.0.1", 0), conftest._Stub) + server.calls, server.status, server.delay, server.vulns = [], 200, 0, [] + threading.Thread(target=server.serve_forever, daemon=True).start() + env = {k: v for k, v in os.environ.items() + if k not in ("ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_REMOTE", "CLAUDE_PROJECT_DIR", + "CLAUDE_CODE_REMOTE_SESSION_ID", "HTTP_PROXY", "HTTPS_PROXY", + "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy")} + env.update(conftest.GIT_ENV) + env.update({ + "SECURITY_WARNINGS_STATE_DIR": str(state), "ANTHROPIC_API_KEY": "test-key", + "ANTHROPIC_BASE_URL": "http://127.0.0.1:%d" % server.server_port, + "NO_PROXY": "*", "no_proxy": "*", "SG_AGENTIC_COMMIT_REVIEW": "0", + "PYTHONDONTWRITEBYTECODE": "1", + }) + + def hook(payload): + started = time.perf_counter() + proc = subprocess.Popen([sys.executable, str(conftest.HOOK_SCRIPT)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) + try: + out, err = proc.communicate(json.dumps(payload).encode(), timeout=900) + except subprocess.TimeoutExpired: + proc.kill() + out, err = proc.communicate() + print("TIMED OUT after 900 s") + return proc, time.perf_counter() - started, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") + + proc, seconds, out, err = hook(conftest.ups_payload(repo)) + print("UserPromptSubmit: exit %d in %.1f s" % (proc.returncode, seconds)) + (repo / "app.py").write_text(conftest.VULN_PY) + for index in range(4): + mark = " \U0001F600" if index == 2 else "" + if kind == "txt": + line = "line %%09d of ordinary generated text for file %d%s\n" % (index, mark) + else: + line = '{"id": %%09d, "file": %d, "note": "ordinary generated record%s"}\n' % (index, mark) + count = 50 * 1024 * 1024 // len((line % 0).encode("utf-8")) + 1 + with open(repo / ("data%d.%s" % (index, kind)), "w", encoding="utf-8", newline="\n") as handle: + for start in range(0, count, 100000): + handle.write("".join(line % n for n in range(start, min(start + 100000, count)))) + proc, seconds, out, err = hook(conftest.stop_payload(repo)) + print("Stop: exit %d in %.1f s, peak memory of the hook process %.0f MB" + % (proc.returncode, seconds, peak_memory_mb(proc))) + print("review requests at the stub API:", len(server.calls)) + print("metrics:", json.dumps(conftest.metrics_of(out), sort_keys=True)) + if err.strip(): + print("stderr (last 15 lines):\n" + "\n".join(err.strip().splitlines()[-15:])) + server.shutdown() + shutil.rmtree(work, ignore_errors=True) + + +def main(): + for check in (inflight_markers, secret_paths, patterns_files, review_scope): + try: + check() + except Exception as error: + print("CHECK FAILED TO RUN: %s: %s: %s" % (check.__name__, type(error).__name__, error), flush=True) + if "--memory" in sys.argv: + try: + stop_memory() + except Exception as error: + print("CHECK FAILED TO RUN: stop_memory: %s: %s" % (type(error).__name__, error), flush=True) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/sg_platform_sdk_bootstrap.py b/.github/scripts/sg_platform_sdk_bootstrap.py new file mode 100644 index 00000000..8ac8da52 --- /dev/null +++ b/.github/scripts/sg_platform_sdk_bootstrap.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Real agent-SDK installs with the plugin's bootstrap script, on two +checkouts of the plugin, printing the outcome code of each run. + + sg_platform_sdk_bootstrap.py <main plugin dir> <pull request plugin dir> + +Prints what each step returned next to what is expected; decides nothing.""" +import json +import os +import subprocess +import sys +import tempfile +import time + +MAIN, PR = (os.path.abspath(p) for p in sys.argv[1:3]) +WORK = tempfile.mkdtemp(prefix="sg-sdk-") + + +def bootstrap_env(state, extra=None): + env = {k: v for k, v in os.environ.items() + if k not in ("SECURITY_GUIDANCE_DISABLE", "ENABLE_CODE_SECURITY_REVIEW")} + env.update({"SECURITY_WARNINGS_STATE_DIR": state, "PYTHONDONTWRITEBYTECODE": "1"}) + env.update(extra or {}) + return env + + +def run(label, plugin, state, expect, extra=None): + started = time.perf_counter() + r = subprocess.run([sys.executable, os.path.join(plugin, "hooks", "ensure_agent_sdk.py")], + stdin=subprocess.DEVNULL, capture_output=True, text=True, + env=bootstrap_env(state, extra), timeout=1500) + metrics = {} + for line in r.stdout.splitlines(): + try: + metrics = json.loads(line).get("metrics") or metrics + except (json.JSONDecodeError, AttributeError): + pass + shown = {k: v for k, v in metrics.items() if k.startswith("sdk_")} + print("%s: sdk_bootstrap=%s (expected %s), exit %d, %.0f s, %s" + % (label, metrics.get("sdk_bootstrap"), expect, r.returncode, + time.perf_counter() - started, json.dumps(shown, sort_keys=True)), flush=True) + if r.stderr.strip(): + print(" stderr (last 8 lines):\n " + "\n ".join(r.stderr.strip().splitlines()[-8:])) + return metrics.get("sdk_bootstrap") + + +def sdk_package_dirs(state): + return [os.path.join(root, "claude_agent_sdk") for root, dirs, _ in os.walk(state) + if "claude_agent_sdk" in dirs] + + +def reviewer_import(label, plugin, state): + """Import the SDK the way the plugin's reviewer does (its own path setup, + which also handles pywin32's .pth files on Windows).""" + code = ("import sys; sys.path.insert(0, sys.argv[1]); import llm, _base; " + "llm._inject_agent_sdk_venv_into_syspath(_base.state_dir()); " + "from claude_agent_sdk import query; print('import ok')") + r = subprocess.run([sys.executable, "-c", code, os.path.join(plugin, "hooks")], + capture_output=True, text=True, env=bootstrap_env(state)) + print("%s: %s" % (label, (r.stdout + r.stderr).strip().splitlines()[-1:])) + + +print("## a. whole plugin switched off") +off = os.path.join(WORK, "off") +run("pull request, SECURITY_GUIDANCE_DISABLE=1", PR, off, 10, {"SECURITY_GUIDANCE_DISABLE": "1"}) +print("state folder created:", os.path.exists(off), "(expected False)") + +print("\n## b. first install, then a second run") +state = os.path.join(WORK, "state") +run("pull request, first run", PR, state, 2) +run("pull request, second run", PR, state, 1) + +print("\n## c. installed package emptied of its files") +packages = sdk_package_dirs(state) +print("SDK package folders:", packages) +removed = 0 +for package in packages: + for root, _, files in os.walk(package): + for name in files: + os.remove(os.path.join(root, name)) + removed += 1 +print("files removed:", removed) +run("main on the emptied install", MAIN, state, "1 (the bug)") +run("pull request on the emptied install", PR, state, "2 with sdk_venv_emptied 1") +run("pull request again", PR, state, 1) +reviewer_import("reviewer import after the rebuild", PR, state) + +print("\n## d. review switched off: is the bootstrap still started from a tool hook") +payload = json.dumps({"session_id": "s", "hook_event_name": "PostToolUse", "tool_name": "Write", + "tool_input": {"file_path": "x.txt", "content": "hi"}, "cwd": "."}) +for label, plugin, expect in (("main", MAIN, True), ("pull request", PR, False)): + folder = os.path.join(WORK, "w-" + label.replace(" ", "-")) + r = subprocess.run([sys.executable, os.path.join(plugin, "hooks", "security_reminder_hook.py")], + input=payload, capture_output=True, text=True, cwd=WORK, + env=bootstrap_env(folder, {"ENABLE_CODE_SECURITY_REVIEW": "0"}), timeout=300) + time.sleep(3) + marker = os.path.join(folder, ".sdk_bootstrap_spawned") + print("%s: hook exit %d, marker file exists: %s (expected %s)" + % (label, r.returncode, os.path.exists(marker), expect)) + +print("\n## e. install killed part way, then run again") +killed = os.path.join(WORK, "k") +proc = subprocess.Popen([sys.executable, os.path.join(PR, "hooks", "ensure_agent_sdk.py")], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=bootstrap_env(killed)) +time.sleep(5) +proc.kill() +proc.wait() +print("after the kill the state folder holds:", sorted(os.listdir(killed)) if os.path.isdir(killed) else "nothing") +time.sleep(10) +outcome = run("pull request, 10 s after the kill", PR, killed, "2, or 5 while a cooldown holds") +if outcome == 5: + print("waiting 6 minutes for the cooldown") + time.sleep(365) + # The kill ends the bootstrap script only. Killed while it creates the venv, + # the next run rebuilds (2). Killed while pip runs, pip finishes the install + # by itself and the next run finds it complete (1). + outcome = run("pull request, 6 minutes later", PR, killed, "2, or 1 when pip was already running") +run("pull request, once more", PR, killed, 1) +reviewer_import("reviewer import after the killed install", PR, killed) diff --git a/.github/scripts/sg_platform_store_cert.py b/.github/scripts/sg_platform_store_cert.py new file mode 100644 index 00000000..31191f5d --- /dev/null +++ b/.github/scripts/sg_platform_store_cert.py @@ -0,0 +1,219 @@ +"""A Windows certificate store entry that OpenSSL cannot read: does Python's default TLS context +still build, and do the plugin's API calls still connect and still verify? + +Usage: sg_platform_store_cert.py <main plugin dir> <pull request plugin dir> + +Adds test certificates, one at a time, to the current user's "CA" store (which makes nothing +trusted), runs the checks, and removes each one again. Every certificate here is a throwaway +self-signed test certificate, damaged on purpose; no private key is kept anywhere. +""" +import base64 +import hashlib +import inspect +import os +import ssl +import struct +import subprocess +import sys +import tempfile + +VALID = base64.b64decode( + "MIIDHzCCAgegAwIBAgIUOc9sRb2irMM4tVz+MQXfAetMqk0wDQYJKoZIhvcNAQELBQAwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMTEzWhcNMjYxMTIwMTYyMTEzWjAfMR0wGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJem7dZt60IjCVS8hLJFacbGIdCwitR+EwfK3RfRbtGUeR8VDfAI2uQUF9KNCQQ0jUDLAzKxTXhje5bDW4eBs/HC86uYBPRvSmSnkh0QXc9FRGsoryI5smLtr//mFoXmyCd/xdX/mThEoamP50mH+mCrwt9UuiS8uUPD0EXMsfKSyWJLx+fPzcquOClCx+RAhGqtFhUMLZvAhRAzwodJaZ+6Rmuajii9W3YuTwUASK00IVF9m+DrvdwMSZBtOC6psyli9boD908SHI1YAR0u5hAeMUVbMC/09gNXrMeuoVghygluujCxUrPfsMtxYBE3+F6S7AbXwBDXjgTfDLP6cSMCAwEAAaNTMFEwHQYDVR0OBBYEFBzXby0JI0yF361xBLC1d/uTc8NjMB8GA1UdIwQYMBaAFBzXby0JI0yF361xBLC1d/uTc8NjMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAG/cFyLiNq1wIUceHcx04Z/frqpzCk360w6HcJ4lfWEEE1Yeyt++3dnKpkvxUT6FvAa63aIXQmaZIRZNtF6bpB937ycGovbCPMIDXj0KLwxYORqQ/kCjh6o8nCMxJ6H2UJ1Wkhvy4t4d0cYKwYxwxLo8cZ+nRn5cwYWlJBTXvVMHP5+WuYYSuatvBmpgCTdR96Setu2CMF+WohyiqXIYCrZDkNyOYS0t9hhzHK9C08eCHsHqE1KaAjUomjGjGjDehtujwBqVi9saCedXFX93MRtiZhVSBC9FHkOYdYYSdmCQi/PBpfMXaPFcfvR9gNKDaxKRRQxaQfrvv+OIVKhP+Z8=") +SUBJECT_A = base64.b64decode( + "MIIBkjCCATmgAwIBAgIUbv89EXoDEbZBR6jKRVAU1V/0fGgwCgYIKoZIzj0EAwIwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMjQ1WhcNMzYxMDE4MTYyMjQ1WjAfMR0EGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPNt0cYQuFTK2120/wnrAXDuqQUE8Cu0MpykWGDKTpymrBpKT9tB3wtr6Z951brKADRTgA7sKsIRoo9WmwnJKdyjUzBRMB0GA1UdDgQWBBQbn4fFArXUPihIY/CG7IxtVswc1DAfBgNVHSMEGDAWgBQbn4fFArXUPihIY/CG7IxtVswc1DAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIDuCfFRxNvoQhAXHiaA+Pgd7nuZ7hHVE16dERXHiVT6JAiACb2vks3dsL40uUAQ7MEoy37JzJExADeVOBhztTqTkkw==") +SUBJECT_B = base64.b64decode( + "MIIBkjCCATmgAwIBAgIUbv89EXoDEbZBR6jKRVAU1V/0fGgwCgYIKoZIzj0EAwIwHzEdMBsGA1UEAwwUc2cgdGVzdCB1bnJlbGF0ZWQgQ0EwHhcNMjYxMDIxMTYyMjQ1WhcNMzYxMDE4MTYyMjQ1WjAfMB0wGwYDVQQDDBRzZyB0ZXN0IHVucmVsYXRlZCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPNt0cYQuFTK2120/wnrAXDuqQUE8Cu0MpykWGDKTpymrBpKT9tB3wtr6Z951brKADRTgA7sKsIRoo9WmwnJKdyjUzBRMB0GA1UdDgQWBBQbn4fFArXUPihIY/CG7IxtVswc1DAfBgNVHSMEGDAWgBQbn4fFArXUPihIY/CG7IxtVswc1DAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0cAMEQCIDuCfFRxNvoQhAXHiaA+Pgd7nuZ7hHVE16dERXHiVT6JAiACb2vks3dsL40uUAQ7MEoy37JzJExADeVOBhztTqTkkw==") +CN = b"sg test unrelated CA" + +REPORT = [] + + +def say(line=""): + print(line, flush=True) + REPORT.append(line) + + +def _tlv(data, at): + length, header = data[at + 1], 2 + if length & 0x80: + n = length & 0x7F + length, header = int.from_bytes(data[at + 2:at + 2 + n], "big"), 2 + n + return header, length + + +def _der(tag, body): + n = len(body) + if n < 0x80: + return bytes([tag, n]) + body + size = n.to_bytes((n.bit_length() + 7) // 8, "big") + return bytes([tag, 0x80 | len(size)]) + size + body + + +def candidates(): + # A subject name that is not valid UTF-8. + name = bytearray(VALID) + name[VALID.find(CN, VALID.find(CN) + 1) + 3] = 0xFF + # A serial number with a leading zero byte it must not have. + h, n = _tlv(VALID, 0) + outer = VALID[h:h + n] + h, n = _tlv(outer, 0) + tbs, rest = outer[h:h + n], outer[h + n:] + h, n = _tlv(tbs, 0) + version, at = tbs[:h + n], h + n + h, n = _tlv(tbs, at) + serial, tail = tbs[at + h:at + h + n], tbs[at + h + n:] + padded = _der(0x30, _der(0x30, version + _der(0x02, b"\x00" + serial) + tail) + rest) + # A serial number under the wrong type. + tag = bytearray(VALID) + tag[13] = 0x04 + return [ + ("name not UTF-8", bytes(name)), + ("serial with illegal padding", padded), + ("subject name wrongly nested (1)", SUBJECT_A), + ("subject name wrongly nested (2)", SUBJECT_B), + ("serial under the wrong type", bytes(tag)), + ] + + +def run(cmd, **kw): + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + errors="replace", timeout=300, **kw) + return p.returncode, p.stdout.strip() + + +def last(text, n=1): + return " | ".join(text.splitlines()[-n:]) if text else "" + + +def context_builds(): + code, out = run([sys.executable, "-c", "import ssl; ssl.create_default_context(); print('builds')"]) + return "builds" if code == 0 else "FAILS: " + last(out) + + +def in_store(der): + return any(cert == der for cert, _, _ in ssl.enum_certificates("CA")) + + +REG_KEY = r"Software\Microsoft\SystemCertificates\CA\Certificates" + + +def add(der, path): + code, out = run(["certutil", "-user", "-addstore", "CA", path]) + if in_store(der): + return "certutil" + say(f" certutil: exit {code}: {last(out, 2)}") + code, out = run(["powershell", "-NoProfile", "-Command", + "$s = New-Object System.Security.Cryptography.X509Certificates.X509Store('CA','CurrentUser');" + "$s.Open('ReadWrite');" + "$c = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList '%s';" + "$s.Add($c); $s.Close()" % path]) + if in_store(der): + return "X509Store" + say(f" X509Store: exit {code}: {last(out, 2)}") + import winreg + thumb = hashlib.sha1(der).hexdigest().upper() + with winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_KEY + "\\" + thumb) as key: + winreg.SetValueEx(key, "Blob", 0, winreg.REG_BINARY, struct.pack("<III", 32, 1, len(der)) + der) + if in_store(der): + return "registry" + say(" registry entry: not listed by the store") + return None + + +def remove(der): + thumb = hashlib.sha1(der).hexdigest().upper() + run(["certutil", "-user", "-delstore", "CA", thumb]) + if in_store(der): + run(["powershell", "-NoProfile", "-Command", + "Remove-Item -Path 'Cert:\\CurrentUser\\CA\\%s' -ErrorAction SilentlyContinue" % thumb]) + try: + import winreg + winreg.DeleteKey(winreg.HKEY_CURRENT_USER, REG_KEY + "\\" + thumb) + except OSError: + pass + return not in_store(der) + + +CONNECT = r""" +import sys, urllib.request, urllib.error +import llm +op = getattr(llm, "_urlopen", None) or (lambda r, t: urllib.request.urlopen(r, timeout=t)) +for url in sys.argv[1:]: + try: + op(urllib.request.Request(url, method="HEAD"), 20) + print(url, "-> connected") + except urllib.error.HTTPError as e: + print(url, "-> connected, HTTP", e.code) + except urllib.error.URLError as e: + print(url, "-> refused:", type(e.reason).__name__, str(e.reason)[:110]) + except Exception as e: + print(url, "-> FAILED before a request:", type(e).__name__, str(e)[:110]) +print("store entries left out:", getattr(llm, "_store_certs_skipped", "n/a")) +""" + +API = "https://api.anthropic.com/" +MUST_REFUSE = ["https://wrong.host.badssl.com/", "https://self-signed.badssl.com/", + "https://untrusted-root.badssl.com/", "https://expired.badssl.com/"] + + +def connect(plugin, urls): + env = {k: v for k, v in os.environ.items() if not k.startswith(("ANTHROPIC_", "SSL_CERT"))} + code, out = run([sys.executable, "-c", CONNECT] + urls, cwd=os.path.join(plugin, "hooks"), env=env) + return out if code == 0 else f"exit {code}: {last(out, 3)}" + + +def main(): + main_plugin, pr_plugin = (os.path.abspath(p) for p in sys.argv[1:3]) + say(f"Python {sys.version.split()[0]} {os.environ.get('PROCESSOR_ARCHITECTURE', '')}, {ssl.OPENSSL_VERSION}") + source = inspect.getsource(ssl.SSLContext._load_windows_store_certs) + say("this Python loads the store: " + + ("one certificate at a time" if "for cert" in source and "except" in source else "in one call")) + say(f"store before: CA {len(ssl.enum_certificates('CA'))} entries, ROOT {len(ssl.enum_certificates('ROOT'))}; " + f"default context {context_builds()}") + say("pull request has the change: " + str(os.path.exists( + os.path.join(pr_plugin, "tests", "test_tls_store_unreadable_cert.py")))) + say("clean store, main: " + connect(main_plugin, [API]).replace("\n", " ; ")) + say("clean store, pull request: " + connect(pr_plugin, [API]).replace("\n", " ; ")) + refusals_done = suite_done = False + work = tempfile.mkdtemp(prefix="sg-store-cert-") + for number, (label, der) in enumerate(candidates(), 1): + say() + say(f"== candidate {number}: {label}") + path = os.path.join(work, f"candidate{number}.cer") + with open(path, "wb") as f: + f.write(der) + try: + how = add(der, path) + if how is None: + say(" Windows did not take it into the store") + continue + builds = context_builds() + say(f" in the store (through {how}); default context {builds}") + say(" main: " + connect(main_plugin, [API]).replace("\n", " ; ")) + say(" pull request: " + connect(pr_plugin, [API]).replace("\n", " ; ")) + if builds != "builds" and not refusals_done: + refusals_done = True + for line in connect(pr_plugin, MUST_REFUSE).splitlines(): + say(" pull request, must be refused: " + line) + if builds != "builds" and not suite_done: + suite_done = True + code, out = run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", + "tests/test_tls_store_unreadable_cert.py"], cwd=pr_plugin) + say(f" new test file with this store: exit {code}: {last(out)}") + if code: + say(" " + last(out, 25)) + finally: + say(" removed: " + str(remove(der)) + f"; default context {context_builds()}") + say() + say(f"store after: CA {len(ssl.enum_certificates('CA'))} entries; default context {context_builds()}") + # The report again as annotations, for reading through the API. + text, part = "\n".join(REPORT), 0 + while text and part < 9: + chunk, text = text[:3000], text[3000:] + part += 1 + chunk = chunk.replace("%", "%25").replace("\r", "").replace("\n", "%0A") + print(f"::notice title=store cert {sys.version.split()[0]} part {part}::{chunk}") + + +if __name__ == "__main__": + main() |
