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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/preloop-publication-key.pub
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIGwADnzwC1gPuLFSk95mciTQXl3Hcnb+tHzD5F13WzgcAAAAHnNzaDpjb2RleC1yb3V0aW5lLWFjdGlvbi1ib3VuZA== alex-yk5c-routine-action-sn38907480-20260909
878 changes: 878 additions & 0 deletions .github/preloop-publisher.py

Large diffs are not rendered by default.

198 changes: 198 additions & 0 deletions .github/preloop-trigger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Start one principal-owned review from trusted GitHub Actions code."""
import importlib.util
import json
import os
import sys
import urllib.parse
from pathlib import Path

SPEC = importlib.util.spec_from_file_location("publisher", ".github/preloop-publisher.py")
assert SPEC is not None
assert SPEC.loader is not None
publisher = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(publisher)


def select_owned_execution(rows, expected, execution_id=None):
"""Choose an explicitly named owned retry; never launch from an unknown ID."""
owned = [row for row in rows if all(row.get(k) == v for k, v in expected.items())]
if execution_id is not None:
publisher.require(
isinstance(execution_id, str)
and publisher.re.fullmatch(
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", execution_id
),
"Invalid selected execution ID",
)
matches = [row for row in owned if row.get("id") == execution_id]
publisher.require(
len(matches) == 1, "Selected execution is missing, duplicated or not owned"
)
return matches[0]
publisher.require(
len(owned) <= 1, "Ambiguous existing review; select the exact owned execution"
)
return owned[0] if owned else None


def prepare():
repository = os.environ["GITHUB_REPOSITORY"]
binding = publisher.load_authority(".github", repository)
workload = publisher.verify_workload(binding, repository, workflow="preloop-review-trigger.yml")
policy = binding.get("native_ci_contract") or {}
publisher.require(
policy.get("explicit_posture_approval") is True
and policy.get("model_verification") == "approved_flow_configuration"
and policy.get("model_id") == binding["model_id"]
and publisher.re.fullmatch("[0-9a-f]{64}", policy.get("flow_config_sha256", "")),
"Incomplete approved native CI contract",
)
token = os.environ["PRELOOP_CI_TRIGGER_TOKEN"]
publisher.require(token.startswith("ci_"), "Only the bound CI trigger identity is accepted")
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
if os.environ["GITHUB_EVENT_NAME"] == "workflow_dispatch":
number = int(event["inputs"]["pr_number"])
execution_id = event["inputs"].get("execution_id") or None
else:
publisher.require(
os.environ["GITHUB_EVENT_NAME"] == "pull_request_target", "Wrong trigger event"
)
number = event["number"]
execution_id = None
publisher.require(type(number) is int and number > 0, "Invalid PR number")
github_token = os.environ["GH_TOKEN"]

def github(path):
return publisher.request("https://api.github.com", path, github_token)

# Verify every executable file against this run's trusted default-branch revision.
publisher.verify_sources(
github,
binding,
workload["workflow_sha"],
[
".github/preloop-publisher.py",
".github/preloop-trigger.py",
".github/workflows/preloop-review-trigger.yml",
],
)
pr = github("/repos/" + repository + "/pulls/" + str(number))
publisher.require(pr["state"] == "open", "PR is closed")
publisher.require(not pr.get("draft", True), "Draft PRs are not reviewed")
publisher.require(
pr.get("user", {}).get("login") != "dependabot[bot]", "Dependabot PRs are not reviewed"
)
publisher.require(
"preloop-skip-review" not in [label["name"] for label in pr.get("labels", [])],
"PR explicitly skips Preloop review",
)
publisher.require(
pr.get("author_association") in ["OWNER", "MEMBER", "COLLABORATOR"],
"PR author is not an admitted repository collaborator",
)
publisher.require(
pr["base"]["repo"]["id"] == binding["repository_id"]
and pr["head"]["repo"]["id"] == binding["repository_id"],
"Repository changed or fork refused",
)
publisher.require(pr["base"]["ref"] == binding["default_branch"], "Wrong target branch")
head, base = pr["head"]["sha"], pr["base"]["sha"]
expected = {
"flow_id": binding["flow_id"],
"project_id": binding["project_id"],
"repository_identifier": str(binding["repository_id"]),
"pr_number": number,
"head_sha": head,
}
query = urllib.parse.urlencode({"flow_id": binding["flow_id"], "limit": 100})
rows = publisher.request("https://preloop.ai", "/api/v1/flows/executions?" + query, token)
publisher.require(isinstance(rows, list), "Invalid owned review history")
selected = select_owned_execution(rows, expected, execution_id)
intent = {
**expected,
"base_sha": base,
"model_id": binding["model_id"],
"flow_config_sha256": policy["flow_config_sha256"],
"trigger_run_id": os.environ["GITHUB_RUN_ID"],
"workflow_sha": workload["workflow_sha"],
"existing_execution_id": selected["id"] if selected else None,
}
if selected is None:
name = "preloop-intent-" + str(number) + "-" + head
journal = github("/repos/" + repository + "/actions/artifacts?name=" + name + "&per_page=1")
publisher.require(
journal["total_count"] == 0,
"A prior durable trigger intent exists; reconcile it before another paid attempt",
)
Path(os.environ["RUNNER_TEMP"], "preloop-trigger-intent.json").write_text(json.dumps(intent))
with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output:
output.write("pr_number=" + str(number) + "\nhead_sha=" + head + "\n")
output.write("needs_intent=" + ("false" if selected is not None else "true") + "\n")


def start():
intent = json.loads(Path(os.environ["RUNNER_TEMP"], "preloop-trigger-intent.json").read_text())
repository = os.environ["GITHUB_REPOSITORY"]
token = os.environ["PRELOOP_CI_TRIGGER_TOKEN"]
publisher.require(token.startswith("ci_"), "Invalid native trigger credential")
number, head, base = intent["pr_number"], intent["head_sha"], intent["base_sha"]

def github(path):
return publisher.request("https://api.github.com", path, os.environ["GH_TOKEN"])

current = github("/repos/" + repository + "/pulls/" + str(number))
publisher.require(
current["state"] == "open"
and current["head"]["sha"] == head
and current["base"]["sha"] == base,
"PR changed before trigger",
)
if intent["existing_execution_id"]:
execution = publisher.request(
"https://preloop.ai",
"/api/v1/flows/executions/" + intent["existing_execution_id"],
token,
)
else:
name = "preloop-intent-" + str(number) + "-" + head
journal = github(
"/repos/" + repository + "/actions/artifacts?name=" + name + "&per_page=100"
)
publisher.require(
journal["total_count"] == 1
and str(journal["artifacts"][0]["workflow_run"]["id"]) == os.environ["GITHUB_RUN_ID"],
"Durable intent not confirmed for this run",
)
# The persisted artifact blocks a later run after an ambiguous POST failure.
execution = publisher.request(
"https://preloop.ai",
"/api/v1/flows/" + intent["flow_id"] + "/trigger",
token,
"POST",
{"pr_number": number, "head_sha": head},
)
expected = {
k: intent[k]
for k in ["flow_id", "project_id", "repository_identifier", "pr_number", "head_sha"]
}
publisher.require(
all(execution.get(k) == v for k, v in expected.items()), "Native execution binding mismatch"
)
eid = publisher.execution_id("https://preloop.ai/console/flows/executions/" + execution["id"])
current = github("/repos/" + repository + "/pulls/" + str(number))
publisher.require(
current["head"]["sha"] == head and current["base"]["sha"] == base,
"PR changed during trigger",
)
receipt = {k: v for k, v in intent.items() if k != "existing_execution_id"}
receipt["execution_id"] = eid
folder = Path(os.environ["RUNNER_TEMP"]) / "preloop-trigger-receipt"
folder.mkdir()
(folder / "receipt.json").write_text(json.dumps(receipt, sort_keys=True) + "\n")
with Path(os.environ["GITHUB_OUTPUT"]).open("a") as output:
output.write("execution_id=" + eid + "\n")
print("Started principal-owned Preloop execution " + eid)


if __name__ == "__main__":
{"--prepare": prepare, "--start": start}[sys.argv[1]]()
162 changes: 162 additions & 0 deletions .github/test_preloop_publisher_diff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# These regressions intentionally use unittest assertions.
# ruff: noqa: PT009, PT027
"""Complete-diff verification regression; no network, credentials or model calls."""
import hashlib
import importlib.util
import io
import json
import subprocess
import unittest
from pathlib import Path
from unittest.mock import patch

spec = importlib.util.spec_from_file_location(
"publisher", Path(__file__).with_name("preloop-publisher.py")
)
assert spec is not None
assert spec.loader is not None
publisher = importlib.util.module_from_spec(spec)
spec.loader.exec_module(publisher)


class CompleteDiffTests(unittest.TestCase):
def verify(self, diff, digest=None, git_failure=False, diff_failure=False, diff_timeout=False):
candidate = {
"head": "a" * 40,
"base": "b" * 40,
"diff_sha256": digest or hashlib.sha256(diff).hexdigest(),
}
calls = []

def git(argv, **kwargs):
calls.append((argv, dict(kwargs["env"])))
if "merge-base" in argv:
result = ("c" * 40 + "\n").encode()
elif "diff" in argv:
if diff_timeout:
raise subprocess.TimeoutExpired(argv, 90)
output = kwargs["stdout"]
self.assertNotEqual(output, subprocess.PIPE)
self.assertEqual(kwargs["timeout"], 90)
output.write(diff)
result = None
else:
result = b""
return subprocess.CompletedProcess(
argv, 1 if git_failure or ("diff" in argv and diff_failure) else 0, result, b""
)

with patch.object(publisher.subprocess, "run", side_effect=git):
publisher.verify_diff(
candidate, "GenMinds-UK/innovateher-lms-work", "synthetic-test-only"
)
diff_argv, diff_env = calls[-1]
self.assertEqual(diff_argv[5:], [*publisher.DIFF_ARGS, "c" * 40, "a" * 40, "--"])
self.assertNotIn("GIT_CONFIG_VALUE_0", diff_env)
self.assertEqual(diff_env["GIT_CONFIG_COUNT"], "0")

def test_complete_diff_just_above_former_cap(self):
self.verify(b"x" * 100_001)

def test_full_ih216_sized_diff_and_final_bytes_are_verified(self):
diff = b"x" * 120_240 + b"final-bytes"
self.assertEqual(len(diff), 120_251)
self.verify(diff)
with self.assertRaisesRegex(publisher.InvalidReviewError, "Diff digest mismatch"):
self.verify(diff, hashlib.sha256(diff[:-1]).hexdigest())

def test_altered_diff_is_refused(self):
with self.assertRaisesRegex(publisher.InvalidReviewError, "Diff digest mismatch"):
self.verify(b"changed", hashlib.sha256(b"original").hexdigest())

def test_git_failure_is_not_an_approval(self):
with self.assertRaisesRegex(
publisher.InvalidReviewError, "Could not verify canonical Git diff"
):
self.verify(b"diff", git_failure=True)

def test_complete_multichunk_binary_diff(self):
self.verify(bytes(range(256)) * 8192 + b"last-byte\xff")

def test_diff_process_failure_is_not_an_approval(self):
with self.assertRaisesRegex(
publisher.InvalidReviewError, "Could not verify canonical Git diff"
):
self.verify(b"partial diff", diff_failure=True)

def test_diff_timeout_is_not_an_approval(self):
with self.assertRaises(subprocess.TimeoutExpired):
self.verify(b"partial diff", diff_timeout=True)


class ReadableReviewTests(unittest.TestCase):
def candidate(self, findings):
return {
"verdict": "pass_with_findings" if findings else "pass",
"findings": findings,
"execution_id": "12345678-1234-1234-1234-123456789abc",
"pr": 235,
"head": "a" * 40,
"base": "b" * 40,
}

def finding(self, severity="MEDIUM", **overrides):
return dict(
severity=severity,
category="test-coverage",
file=".github/workflows/ci.yml",
line=49,
evidence="The new regression tests are not run in CI.",
fix="Run the complete-diff test in CI.",
**overrides,
)

def test_severities_are_readable_with_colour_and_text(self):
findings = [self.finding(severity) for severity in ["CRITICAL", "HIGH", "MEDIUM", "LOW"]]
text, marker = publisher.body(self.candidate(findings))
for label in ["🔴 Critical", "🔴 High", "🟠 Medium", "🟡 Low"]:
self.assertIn(label, text)
self.assertEqual(text.count("**Problem:**"), 4)
self.assertEqual(text.count("**Suggested fix:**"), 4)
self.assertNotIn("<pre>", text)
self.assertNotIn('"severity":', text)
self.assertIn(marker, text)
self.assertIn("a" * 40, text)
self.assertIn("b" * 40, text)

def test_untrusted_text_cannot_inject_html_links_or_mentions(self):
finding = self.finding()
finding[
"evidence"
] = "<script>alert(1)</script> [click](https://example.org) @everyone\n# heading"
text, _ = publisher.body(self.candidate([finding]))
self.assertNotIn("<script>", text)
self.assertNotIn("[click](https://example.org)", text)
self.assertNotIn("@everyone", text)
self.assertIn("&lt;script&gt;", text)
self.assertIn("\\# heading", text)

def test_large_comment_keeps_all_findings_for_github_validation(self):
finding = self.finding()
finding["evidence"] = "x" * 60000
text, marker = publisher.body(self.candidate([finding]))
self.assertIn(finding["evidence"], text)
self.assertIn(marker, text)

def test_authoritative_json_larger_than_former_client_limit_is_complete(self):
value = "x" * 2_000_000 + "final-bytes"
response = io.BytesIO(json.dumps({"result": value}).encode())
with patch.object(publisher.urllib.request, "build_opener") as opener:
opener.return_value.open.return_value = response
actual = publisher.request("https://preloop.ai", "/synthetic", "synthetic")
self.assertEqual(actual["result"], value)

def test_no_findings_keeps_publication_identity(self):
text, marker = publisher.body(self.candidate([]))
self.assertIn("**No findings.**", text)
self.assertIn(marker, text)
self.assertNotIn("**Problem:**", text)


if __name__ == "__main__":
unittest.main()
Loading
Loading