suite-gate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
suite_gate/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """suite-gate: a shared result format for audit tools, and an MCP server over them."""
3
+
4
+ __version__ = "0.1.0"
suite_gate/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
suite_gate/action.py ADDED
@@ -0,0 +1,148 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """suite-gate action: the gate as a GitHub Actions step.
3
+
4
+ Reads its inputs from the environment (GATE_* set by action.yml, GITHUB_* set by Actions), runs
5
+ the gate, prints the text report, annotates each finding on its file and line, writes a job
6
+ summary, sets the outputs `verdict` and `result`, and exits with the gate's exit status.
7
+ """
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+
14
+ from . import gate, mcp
15
+
16
+ SEVERITY_ORDER = {"high": 0, "medium": 1, "low": 2}
17
+
18
+
19
+ def _escape_data(text):
20
+ """Escape a workflow command's message (GitHub's %, CR and LF rules)."""
21
+ return text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
22
+
23
+
24
+ def _escape_property(text):
25
+ """Escape a workflow command's property value (also : and ,)."""
26
+ return _escape_data(text).replace(":", "%3A").replace(",", "%2C")
27
+
28
+
29
+ def annotations(result, rules):
30
+ """One ::error or ::warning line per finding with a fail or warn severity."""
31
+ fail = set(rules["verdict"]["fail"])
32
+ warn = set(rules["verdict"]["warn"])
33
+ lines = []
34
+ for check in result["checks"]:
35
+ for f in check.get("result", {}).get("findings", []):
36
+ level = "error" if f["severity"] in fail else "warning" if f["severity"] in warn else None
37
+ if level is None:
38
+ continue
39
+ props = ["title=%s" % _escape_property("%s (%s)" % (f["rule"], f["severity"]))]
40
+ evidence = f["evidence"]
41
+ if "path" in check:
42
+ # release-drift's paths are inside a downloaded package: point at the lockfile.
43
+ props.insert(0, "file=%s" % _escape_property(check["path"]))
44
+ elif "path" in evidence and not evidence["path"].startswith(("~", "/")):
45
+ props.insert(0, "file=%s" % _escape_property(evidence["path"]))
46
+ if "line" in evidence:
47
+ props.insert(1, "line=%d" % evidence["line"])
48
+ lines.append("::%s %s::%s" % (level, ",".join(props), _escape_data(f["message"])))
49
+ for check in result["checks"]:
50
+ if check["status"] == "error":
51
+ lines.append("::error title=%s::%s" % (_escape_property(check["tool"] + " did not run"),
52
+ _escape_data(check["error"])))
53
+ return lines
54
+
55
+
56
+ def _cell(text):
57
+ """Text for one Markdown table cell."""
58
+ return str(text).replace("|", "\\|").replace("\n", " ")
59
+
60
+
61
+ def summary(result):
62
+ """The job summary, in Markdown: verdict, checks, findings with evidence."""
63
+ out = ["## suite-gate: %s" % result["verdict"].upper(), "",
64
+ "`%s` (%s) into `%s` (%s), rules `%s` version %d." % (
65
+ result["ref"]["name"], result["ref"]["commit"][:12], result["base"]["name"],
66
+ result["base"]["commit"][:12], result["rules"]["name"], result["rules"]["version"]),
67
+ "", "| Check | Status | Result |", "| --- | --- | --- |"]
68
+ findings = []
69
+ for check in result["checks"]:
70
+ if check["status"] == "ran":
71
+ found = [f for f in check["result"]["findings"] if f["severity"] != "info"]
72
+ findings.extend(found)
73
+ text = ", ".join("%d %s" % (sum(f["severity"] == s for f in found), s)
74
+ for s in ("high", "medium", "low")
75
+ if any(f["severity"] == s for f in found)) or "nothing found"
76
+ if check["result"]["errors"]:
77
+ text = "; ".join(e["message"] for e in check["result"]["errors"])
78
+ elif check["status"] == "skipped":
79
+ text = check["reason"]
80
+ else:
81
+ text = check["error"]
82
+ status = check["status"] + ("" if check["status"] != "ran" else " (%s)" % check["reason"])
83
+ out.append("| %s | %s | %s |" % (_cell(check["tool"]), _cell(status), _cell(text)))
84
+ if findings:
85
+ out += ["", "| Severity | Rule | Finding | Evidence |", "| --- | --- | --- | --- |"]
86
+ for f in sorted(findings, key=lambda f: SEVERITY_ORDER[f["severity"]]):
87
+ ev = f["evidence"]
88
+ where = ev.get("path", "")
89
+ if "line" in ev:
90
+ where += ":%d" % ev["line"]
91
+ if "commit" in ev:
92
+ where += " @ %s" % ev["commit"][:12]
93
+ if "url" in ev:
94
+ where += " %s" % ev["url"]
95
+ out.append("| %s | `%s` | %s | %s |" % (f["severity"], _cell(f["rule"]),
96
+ _cell(f["message"]), _cell(where.strip())))
97
+ return "\n".join(out) + "\n"
98
+
99
+
100
+ def _shallow(repo):
101
+ proc = subprocess.run(["git", "-C", repo, "rev-parse", "--is-shallow-repository"],
102
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
103
+ return proc.stdout.strip() == "true"
104
+
105
+
106
+ def _append(path, text):
107
+ with open(path, "a", encoding="utf-8") as handle:
108
+ handle.write(text)
109
+
110
+
111
+ def main(env=None, out=sys.stdout):
112
+ """Run the gate from environment variables; return the exit status."""
113
+ env = os.environ if env is None else env
114
+ repo = env.get("GITHUB_WORKSPACE") or "."
115
+ base = env.get("GATE_BASE") or (
116
+ "origin/" + env["GITHUB_BASE_REF"] if env.get("GITHUB_BASE_REF") else "")
117
+ ref = env.get("GATE_REF") or "HEAD"
118
+ rules = env.get("GATE_RULES") or "ci"
119
+ exclude = ["origin/" + env["GITHUB_HEAD_REF"]] if env.get("GITHUB_HEAD_REF") else []
120
+
121
+ def fail(message):
122
+ out.write("::error title=suite-gate::%s\n" % _escape_data(message))
123
+ return 2
124
+ if not base:
125
+ return fail("no base: set the base input, or run on a pull_request event")
126
+ if _shallow(repo):
127
+ return fail("the checkout is shallow; check out with fetch-depth: 0 so the merge base "
128
+ "and the other branches are there")
129
+ try:
130
+ loaded = gate.load_rules(rules)[0]
131
+ result = gate.gate(repo, base, ref, rules, mcp.Runner(int(env.get("GATE_TIMEOUT") or 600)),
132
+ env.get("GATE_LOCKFILE_CACHE") or None, exclude)
133
+ except (gate.GateError, mcp.ToolError, ValueError) as exc:
134
+ return fail(str(exc))
135
+ out.write(gate.render(result))
136
+ for line in annotations(result, loaded):
137
+ out.write(line + "\n")
138
+ directory = env.get("RUNNER_TEMP") or tempfile.gettempdir()
139
+ path = os.path.join(directory, "suite-gate-result.json")
140
+ with open(path, "w", encoding="utf-8") as handle:
141
+ json.dump(result, handle, indent=2, sort_keys=True)
142
+ handle.write("\n")
143
+ if env.get("GITHUB_STEP_SUMMARY"):
144
+ _append(env["GITHUB_STEP_SUMMARY"], summary(result))
145
+ if env.get("GITHUB_OUTPUT"):
146
+ _append(env["GITHUB_OUTPUT"], "verdict=%s\nresult=%s\n" % (result["verdict"], path))
147
+ out.flush()
148
+ return result["exit"]
suite_gate/cli.py ADDED
@@ -0,0 +1,93 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Command line: suite-gate gate | mcp | validate."""
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from . import __version__, action, gate, mcp, session
8
+ from .envelope import validate
9
+
10
+
11
+ def main(argv=None):
12
+ p = argparse.ArgumentParser(prog="suite-gate",
13
+ description="A shared result format for audit tools, and an MCP "
14
+ "server that runs them.")
15
+ p.add_argument("--version", action="version", version="suite-gate " + __version__)
16
+ sub = p.add_subparsers(dest="command", metavar="COMMAND")
17
+ sub.required = True
18
+ m = sub.add_parser("mcp", help="serve the installed audit tools over MCP (stdio)")
19
+ m.add_argument("--timeout", type=int, default=600, metavar="SECONDS",
20
+ help="longest one tool may run (default 600)")
21
+ g = sub.add_parser("gate", help="one verdict for REF against BASE, from the rules file")
22
+ g.add_argument("base", metavar="BASE")
23
+ g.add_argument("ref", metavar="REF")
24
+ g.add_argument("--repo", default=".", metavar="DIR", help="repository (default: .)")
25
+ g.add_argument("--rules", metavar="FILE",
26
+ help="rules file, or a built-in name: default (local branches) or ci "
27
+ "(branches under origin/, for a CI checkout)")
28
+ g.add_argument("--exclude", action="append", default=[], metavar="BRANCH",
29
+ help="leave BRANCH out of the overlap check (repeatable)")
30
+ g.add_argument("--json", action="store_true", help="print the gate result object")
31
+ g.add_argument("--lockfile-cache", metavar="DIR",
32
+ help="release-drift: read packages from DIR and query no registry")
33
+ g.add_argument("--timeout", type=int, default=600, metavar="SECONDS",
34
+ help="longest one tool may run (default 600)")
35
+ s = sub.add_parser("session", help="what an agent session left behind that runs later "
36
+ "(glassbox persist before and after)")
37
+ ss = s.add_subparsers(dest="action", metavar="ACTION")
38
+ ss.required = True
39
+ for name, text in (("save", "snapshot the persistence points before a session"),
40
+ ("check", "compare with the snapshot after a session"),
41
+ ("run", "snapshot, run COMMAND, compare")):
42
+ p_ = ss.add_parser(name, help=text)
43
+ where = p_.add_mutually_exclusive_group()
44
+ where.add_argument("--state", metavar="FILE",
45
+ help="snapshot file (default: $XDG_STATE_HOME/suite-gate/session.snapshot)")
46
+ where.add_argument("--hook", action="store_true",
47
+ help="read a Claude Code hook's JSON on standard input and keep one "
48
+ "snapshot per session_id")
49
+ p_.add_argument("--home", metavar="DIR", help="glassbox: use DIR instead of $HOME")
50
+ p_.add_argument("--repo", action="append", default=[], metavar="DIR",
51
+ help="glassbox: also watch DIR's git hooks, config and agent configs")
52
+ p_.add_argument("--timeout", type=int, default=600, metavar="SECONDS")
53
+ if name != "save":
54
+ p_.add_argument("--json", action="store_true", help="print the audit result object")
55
+ if name == "run":
56
+ p_.add_argument("argv", nargs=argparse.REMAINDER, metavar="-- COMMAND")
57
+ sub.add_parser("action", help="run the gate as a GitHub Actions step (reads GATE_* and "
58
+ "GITHUB_* from the environment)")
59
+ v = sub.add_parser("validate", help="check an audit result object (FILE or standard input)")
60
+ v.add_argument("file", nargs="?", metavar="FILE")
61
+ args = p.parse_args(argv)
62
+ if args.command == "gate":
63
+ try:
64
+ result = gate.gate(args.repo, args.base, args.ref, args.rules,
65
+ mcp.Runner(args.timeout), args.lockfile_cache, args.exclude)
66
+ except (gate.GateError, mcp.ToolError) as exc:
67
+ sys.stderr.write("suite-gate: %s\n" % exc)
68
+ return 2
69
+ sys.stdout.write(json.dumps(result, indent=2, sort_keys=True) + "\n" if args.json
70
+ else gate.render(result))
71
+ return result["exit"]
72
+ if args.command == "session":
73
+ return session.main(args)
74
+ if args.command == "action":
75
+ return action.main()
76
+ if args.command == "mcp":
77
+ if args.timeout < 1:
78
+ p.error("--timeout must be at least 1")
79
+ mcp.serve(mcp.Runner(args.timeout), sys.stdin, sys.stdout)
80
+ return 0
81
+ try:
82
+ text = open(args.file, encoding="utf-8").read() if args.file else sys.stdin.read()
83
+ problems = validate(json.loads(text))
84
+ except (OSError, ValueError) as exc:
85
+ sys.stderr.write("suite-gate: %s\n" % exc)
86
+ return 2
87
+ for problem in problems:
88
+ sys.stdout.write(problem + "\n")
89
+ return 1 if problems else 0
90
+
91
+
92
+ if __name__ == "__main__":
93
+ sys.exit(main())
suite_gate/envelope.py ADDED
@@ -0,0 +1,123 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Check an audit result against format audit-result/1 (docs/format.md).
3
+
4
+ validate() applies every rule in schema/audit-result-1.schema.json and the rules
5
+ the schema cannot express: exit 2 exactly when there are errors, otherwise exit 1
6
+ exactly when a finding is not "info". It returns a list of problems; empty means valid.
7
+ """
8
+ import re
9
+
10
+ FORMAT = "audit-result/1"
11
+ SEVERITIES = ("high", "medium", "low", "info")
12
+ TARGET_KINDS = ("repository", "artifact", "package", "host")
13
+ _NAME = re.compile(r"^[a-z0-9][a-z0-9-]*$")
14
+ _RULE = re.compile(r"^[a-z0-9][a-z0-9.-]*$")
15
+ _COMMIT = re.compile(r"^([0-9a-f]{40}|[0-9a-f]{64})$")
16
+
17
+
18
+ def _text(v):
19
+ return isinstance(v, str) and v != ""
20
+
21
+
22
+ def _keys(obj, where, required, allowed, out):
23
+ if not isinstance(obj, dict):
24
+ out.append(f"{where}: not an object")
25
+ return False
26
+ out.extend(f"{where}: missing {k}" for k in required if k not in obj)
27
+ out.extend(f"{where}: unknown key {k}" for k in sorted(obj) if k not in allowed)
28
+ return True
29
+
30
+
31
+ def _evidence(ev, where, out):
32
+ if not _keys(ev, where, (), ("path", "line", "commit", "ref", "url"), out):
33
+ return
34
+ if not ev:
35
+ out.append(f"{where}: empty")
36
+ for k in ("path", "ref"):
37
+ if k in ev and not _text(ev[k]):
38
+ out.append(f"{where}.{k}: not a non-empty string")
39
+ if "line" in ev:
40
+ line = ev["line"]
41
+ if type(line) is not int or line < 1:
42
+ out.append(f"{where}.line: not an integer >= 1")
43
+ if "path" not in ev:
44
+ out.append(f"{where}.line: needs path")
45
+ if "commit" in ev and not (isinstance(ev["commit"], str) and _COMMIT.match(ev["commit"])):
46
+ out.append(f"{where}.commit: not a full hex object id")
47
+ if "url" in ev and not (isinstance(ev["url"], str) and ev["url"].startswith("https://")):
48
+ out.append(f"{where}.url: not an https URL")
49
+
50
+
51
+ def _finding(f, where, out):
52
+ if not _keys(f, where, ("rule", "severity", "message", "evidence", "record"),
53
+ ("rule", "severity", "message", "evidence", "record"), out):
54
+ return
55
+ if "rule" in f and not (isinstance(f["rule"], str) and _RULE.match(f["rule"])):
56
+ out.append(f"{where}.rule: not a rule id")
57
+ if "severity" in f and f["severity"] not in SEVERITIES:
58
+ out.append(f"{where}.severity: not one of {', '.join(SEVERITIES)}")
59
+ if "message" in f and not _text(f["message"]):
60
+ out.append(f"{where}.message: not a non-empty string")
61
+ if "evidence" in f:
62
+ _evidence(f["evidence"], f"{where}.evidence", out)
63
+ if "record" in f and not isinstance(f["record"], dict):
64
+ out.append(f"{where}.record: not an object")
65
+
66
+
67
+ def _error(e, where, out):
68
+ if not _keys(e, where, ("message",), ("message", "path"), out):
69
+ return
70
+ for k in ("message", "path"):
71
+ if k in e and not _text(e[k]):
72
+ out.append(f"{where}.{k}: not a non-empty string")
73
+
74
+
75
+ def validate(doc):
76
+ """Return the problems in doc as a list of strings; [] when doc is a valid result."""
77
+ out = []
78
+ top = ("format", "tool", "target", "exit", "findings", "errors")
79
+ if not _keys(doc, "result", top, top, out):
80
+ return out
81
+ if "format" in doc and doc["format"] != FORMAT:
82
+ out.append(f"result.format: not {FORMAT}")
83
+ tool = doc.get("tool")
84
+ if "tool" in doc and _keys(tool, "tool", ("name", "version"), ("name", "version"), out):
85
+ if "name" in tool and not (isinstance(tool["name"], str) and _NAME.match(tool["name"])):
86
+ out.append("tool.name: not a tool name")
87
+ if "version" in tool and not _text(tool["version"]):
88
+ out.append("tool.version: not a non-empty string")
89
+ target = doc.get("target")
90
+ if "target" in doc and _keys(target, "target", ("kind", "name"),
91
+ ("kind", "name", "ref", "base"), out):
92
+ if "kind" in target and target["kind"] not in TARGET_KINDS:
93
+ out.append(f"target.kind: not one of {', '.join(TARGET_KINDS)}")
94
+ for k in ("name", "ref", "base"):
95
+ if k in target and not _text(target[k]):
96
+ out.append(f"target.{k}: not a non-empty string")
97
+ lists_ok = True
98
+ for key, check in (("findings", _finding), ("errors", _error)):
99
+ if key not in doc:
100
+ lists_ok = False
101
+ elif not isinstance(doc[key], list):
102
+ out.append(f"result.{key}: not an array")
103
+ lists_ok = False
104
+ else:
105
+ for i, item in enumerate(doc[key]):
106
+ check(item, f"{key}[{i}]", out)
107
+ code = doc.get("exit")
108
+ if "exit" in doc and (type(code) is not int or code not in (0, 1, 2)):
109
+ out.append("result.exit: not 0, 1 or 2")
110
+ elif "exit" in doc and lists_ok and not out:
111
+ out.extend(_exit_rules(doc))
112
+ return out
113
+
114
+
115
+ def _exit_rules(doc):
116
+ errors = len(doc["errors"])
117
+ found = sum(1 for f in doc["findings"] if f["severity"] != "info")
118
+ want = 2 if errors else (1 if found else 0)
119
+ if doc["exit"] == want:
120
+ return []
121
+ why = {2: f"{errors} error(s)", 1: f"{found} finding(s) above info",
122
+ 0: "no errors and no finding above info"}[want]
123
+ return [f"result.exit: is {doc['exit']}, must be {want} with {why}"]