tui/gitlab_runner.py
172 lines · 5236 bytes
1"""
2Drive the GitLab audit collectors from the TUI.
3
4Reuses the collectors and CSV reporter under ``applications/gitlab`` unchanged.
5Mirrors github_runner: a ``CHECKS`` registry plus ``run_audit`` that writes the
6same package ``applications/gitlab/audit.py`` produces and reports progress
7through a callback.
8"""
9
10import os
11import sys
12from collections.abc import Iterable
13from dataclasses import dataclass
14from datetime import date
15
16from tui.common import Check, ProgressCallback, ProgressEvent
17
18# Namespaced import so the GitHub and GitLab collector packages (both named
19# ``collectors`` on disk) can coexist in one process.
20_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21if _REPO_ROOT not in sys.path:
22 sys.path.insert(0, _REPO_ROOT)
23
24from applications.gitlab.collectors import (
25 approvals,
26 audit_events,
27 branch_protections,
28 members,
29 pipelines,
30 projects,
31 settings,
32)
33from applications.gitlab.reporters import csv_reporter
34
35# --- Check registry ---------------------------------------------------------
36
37# For GitLab, ``arg`` is "base" -> fn(group, cfg) or "projects" -> fn(group,
38# cfg, projects), where the project cache is fetched once and shared.
39
40CHECKS: list[Check] = [
41 Check("group_members", "Group members", members.group_members, "group_members.csv"),
42 Check(
43 "projects", "Projects", projects.project_list, "projects.csv", arg="projects"
44 ),
45 Check(
46 "project_members",
47 "Project members",
48 members.project_members,
49 "project_members.csv",
50 arg="projects",
51 ),
52 Check(
53 "branch_protections",
54 "Branch protections",
55 branch_protections.branch_protections,
56 "branch_protections.csv",
57 arg="projects",
58 ),
59 Check(
60 "pipelines",
61 "Pipelines",
62 pipelines.pipelines,
63 "pipelines.csv",
64 arg="projects",
65 ),
66 Check(
67 "approval_rules",
68 "Approval rules",
69 approvals.approval_rules,
70 "approval_rules.csv",
71 arg="projects",
72 note="requires Premium/Ultimate",
73 ),
74 Check(
75 "audit_events",
76 "Audit events",
77 audit_events.audit_events,
78 "audit_events.csv",
79 note="requires Premium/Ultimate",
80 ),
81 Check(
82 "password_policy",
83 "Password policy",
84 settings.password_policy,
85 "password_policy.csv",
86 note="self-hosted, admin token",
87 ),
88]
89
90_PREMIUM = {"approval_rules", "audit_events", "password_policy"}
91DEFAULT_SELECTION = [c.key for c in CHECKS if c.key not in _PREMIUM]
92
93
94# --- Config + output helpers ------------------------------------------------
95
96
97def build_cfg(token: str, base_url: str) -> dict:
98 """Build the config dict the collectors expect (mirrors config.load())."""
99 return {
100 "token": token,
101 "base_url": base_url.rstrip("/"),
102 "headers": {"PRIVATE-TOKEN": token},
103 "timeout": 30,
104 }
105
106
107def default_output_dir(out: str, group: str) -> str:
108 """Match the folder naming used by applications/gitlab/audit.py."""
109 safe_group = group.replace("/", "-")
110 return os.path.join(out, f"gitlab_audit_{safe_group}_{date.today().isoformat()}")
111
112
113@dataclass(frozen=True)
114class GitLabTarget:
115 """A group to audit and the token and instance URL to audit it with."""
116
117 group: str
118 token: str
119 base_url: str
120
121
122# --- Runner -----------------------------------------------------------------
123
124
125def run_audit(
126 target: GitLabTarget,
127 *,
128 output_dir: str,
129 selected_keys: Iterable[str],
130 on_event: ProgressCallback,
131) -> list[tuple[str, int]]:
132 """
133 Run the selected checks and write the audit package to ``output_dir``.
134
135 A collector that raises is reported as an error and recorded with a count
136 of 0, so one bad check never aborts the whole run.
137 """
138 group, token, base_url = target.group, target.token, target.base_url
139 cfg = build_cfg(token, base_url)
140 selected = set(selected_keys)
141 checks = [c for c in CHECKS if c.key in selected]
142
143 project_cache: list | None = None
144 if any(c.arg == "projects" for c in checks):
145 on_event(ProgressEvent("fetch", "Projects (shared cache)"))
146 try:
147 project_cache = projects.fetch_projects(group, cfg)
148 except Exception as e:
149 on_event(ProgressEvent("error", "Projects (shared cache)", message=str(e)))
150 project_cache = []
151
152 sections: list[tuple[str, int]] = []
153 for c in checks:
154 on_event(ProgressEvent("start", c.label))
155 try:
156 if c.arg == "projects":
157 rows = c.fn(group, cfg, project_cache or [])
158 else:
159 rows = c.fn(group, cfg)
160 except Exception as e:
161 on_event(ProgressEvent("error", c.label, message=str(e)))
162 sections.append((c.label, 0))
163 continue
164
165 csv_reporter.write(output_dir, c.filename, rows)
166 sections.append((c.label, len(rows)))
167 on_event(ProgressEvent("done", c.label, count=len(rows)))
168
169 csv_reporter.write_summary(output_dir, group, sections)
170 total = sum(n for _, n in sections)
171 on_event(ProgressEvent("summary", output_dir, count=total))
172 return sections