tui/github_runner.py
217 lines · 6662 bytes
1"""
2Drive the existing GitHub audit collectors from the TUI.
3
4This module reuses the collectors and CSV reporter under
5``applications/github`` unchanged. It exposes:
6
7- ``CHECKS``: the list of available audit checks the UI presents.
8- ``run_audit``: run the selected checks, write the same output package
9 ``audit.py`` produces, and report progress through a callback.
10"""
11
12import os
13import sys
14from collections.abc import Iterable
15from dataclasses import dataclass
16from datetime import date
17
18from tui.common import Check, ProgressCallback, ProgressEvent
19
20# Import the GitHub collectors as a namespaced package so the GitHub and GitLab
21# collector packages (both named ``collectors`` on disk) can coexist in one
22# process. Requires the repo root on sys.path.
23_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24if _REPO_ROOT not in sys.path:
25 sys.path.insert(0, _REPO_ROOT)
26
27from applications.github.collectors import (
28 audit_log,
29 branch_protections,
30 commits,
31 deploy_keys,
32 members,
33 org_settings,
34 security_alerts,
35 webhooks,
36)
37from applications.github.reporters import csv_reporter
38
39# --- Check registry ---------------------------------------------------------
40
41# For GitHub, ``arg`` is "base" -> fn(org, cfg), "collabs" -> fn(org, cfg,
42# repo_collabs), or "branch" -> fn(org, cfg, branch).
43
44CHECKS: list[Check] = [
45 Check("member_roster", "Member roster", members.member_roster, "member_roster.csv"),
46 Check(
47 "two_factor",
48 "2FA disabled",
49 members.two_factor_disabled,
50 "two_factor_disabled.csv",
51 note="requires org owner token",
52 ),
53 Check(
54 "outside_collaborators",
55 "Outside collaborators",
56 members.outside_collaborators,
57 "outside_collaborators.csv",
58 arg="collabs",
59 ),
60 Check(
61 "privileged_access",
62 "Privileged access",
63 members.privileged_access,
64 "privileged_access.csv",
65 arg="collabs",
66 ),
67 Check(
68 "pending_invitations",
69 "Pending invitations",
70 members.pending_invitations,
71 "pending_invitations.csv",
72 ),
73 Check(
74 "team_permissions",
75 "Team permissions",
76 members.team_permissions,
77 "team_permissions.csv",
78 ),
79 Check(
80 "permission_matrix",
81 "Permission matrix",
82 members.permission_matrix,
83 "permission_matrix.csv",
84 arg="collabs",
85 ),
86 Check(
87 "branch_protections",
88 "Branch protections",
89 branch_protections.branch_protections,
90 "branch_protections.csv",
91 ),
92 Check("commits", "Commits", commits.commits, "commits.csv", arg="branch"),
93 Check(
94 "org_security",
95 "Org security settings",
96 org_settings.org_security,
97 "org_security.csv",
98 ),
99 Check("webhooks", "Webhooks", webhooks.webhooks, "webhooks.csv"),
100 Check("deploy_keys", "Deploy keys", deploy_keys.deploy_keys, "deploy_keys.csv"),
101 Check(
102 "secret_scanning",
103 "Secret scanning alerts",
104 security_alerts.secret_scanning,
105 "secret_scanning.csv",
106 note="requires GitHub Advanced Security",
107 ),
108 Check(
109 "dependabot_alerts",
110 "Dependabot alerts",
111 security_alerts.dependabot_alerts,
112 "dependabot_alerts.csv",
113 note="requires GitHub Advanced Security",
114 ),
115 Check(
116 "audit_log",
117 "Audit log (branch/ruleset changes)",
118 audit_log.audit_log,
119 "audit_log.csv",
120 note="requires GitHub Enterprise Cloud",
121 ),
122]
123
124# Off by default: checks needing Advanced Security or Enterprise Cloud.
125_OFF_BY_DEFAULT = {"secret_scanning", "dependabot_alerts", "audit_log"}
126DEFAULT_SELECTION = [c.key for c in CHECKS if c.key not in _OFF_BY_DEFAULT]
127
128
129# --- Config + output helpers ------------------------------------------------
130
131
132def build_cfg(token: str) -> dict:
133 """Build the config dict the collectors expect (mirrors config.load())."""
134 return {
135 "token": token,
136 "headers": {
137 "Authorization": f"token {token}",
138 "Accept": "application/vnd.github.v3+json",
139 },
140 "timeout": 30,
141 }
142
143
144def default_output_dir(out: str, org: str) -> str:
145 """Match the folder naming used by audit.py."""
146 return os.path.join(out, f"github_audit_{org}_{date.today().isoformat()}")
147
148
149@dataclass(frozen=True)
150class GitHubTarget:
151 """An organization to audit and the token and default branch to audit it with."""
152
153 org: str
154 token: str
155 branch: str
156
157
158# --- Runner -----------------------------------------------------------------
159
160
161def run_audit(
162 target: GitHubTarget,
163 *,
164 output_dir: str,
165 selected_keys: Iterable[str],
166 on_event: ProgressCallback,
167) -> list[tuple[str, int]]:
168 """
169 Run the selected checks and write the audit package to ``output_dir``.
170
171 A collector that raises is reported as an error and recorded with a count
172 of 0, matching audit.py's behavior of never aborting the whole run.
173
174 Returns the list of (label, row_count) sections that was written to the
175 summary file.
176 """
177 org, token, branch = target.org, target.token, target.branch
178 cfg = build_cfg(token)
179 selected = set(selected_keys)
180 checks = [c for c in CHECKS if c.key in selected]
181
182 repo_collabs: list | None = None
183 if any(c.arg == "collabs" for c in checks):
184 on_event(ProgressEvent("fetch", "Repo collaborators (shared cache)"))
185 try:
186 repo_collabs = members.fetch_repo_collaborators(org, cfg)
187 except Exception as e:
188 on_event(
189 ProgressEvent(
190 "error", "Repo collaborators (shared cache)", message=str(e)
191 )
192 )
193 repo_collabs = []
194
195 sections: list[tuple[str, int]] = []
196 for c in checks:
197 on_event(ProgressEvent("start", c.label))
198 try:
199 if c.arg == "collabs":
200 rows = c.fn(org, cfg, repo_collabs or [])
201 elif c.arg == "branch":
202 rows = c.fn(org, cfg, branch)
203 else:
204 rows = c.fn(org, cfg)
205 except Exception as e:
206 on_event(ProgressEvent("error", c.label, message=str(e)))
207 sections.append((c.label, 0))
208 continue
209
210 csv_reporter.write(output_dir, c.filename, rows)
211 sections.append((c.label, len(rows)))
212 on_event(ProgressEvent("done", c.label, count=len(rows)))
213
214 csv_reporter.write_summary(output_dir, org, sections)
215 total = sum(n for _, n in sections)
216 on_event(ProgressEvent("summary", output_dir, count=total))
217 return sections