git-security-sentinel 1.2.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.
- git_security_sentinel/__init__.py +74 -0
- git_security_sentinel/__main__.py +9 -0
- git_security_sentinel/ai/__init__.py +17 -0
- git_security_sentinel/ai/cost.py +34 -0
- git_security_sentinel/ai/prompts.py +81 -0
- git_security_sentinel/ai_cli.py +884 -0
- git_security_sentinel/cli.py +937 -0
- git_security_sentinel/config/__init__.py +16 -0
- git_security_sentinel/config/loader.py +245 -0
- git_security_sentinel/core/__init__.py +42 -0
- git_security_sentinel/core/diff_parser.py +93 -0
- git_security_sentinel/core/models.py +111 -0
- git_security_sentinel/core/scanner.py +360 -0
- git_security_sentinel/hooks/__init__.py +8 -0
- git_security_sentinel/hooks/bootstrap.py +84 -0
- git_security_sentinel/hooks/installer.py +103 -0
- git_security_sentinel/output/__init__.py +18 -0
- git_security_sentinel/output/sarif.py +179 -0
- git_security_sentinel/py.typed +0 -0
- git_security_sentinel/redaction/__init__.py +15 -0
- git_security_sentinel/redaction/redactor.py +313 -0
- git_security_sentinel/rules/__init__.py +29 -0
- git_security_sentinel/rules/auth.py +103 -0
- git_security_sentinel/rules/catalog.py +63 -0
- git_security_sentinel/rules/cloud.py +132 -0
- git_security_sentinel/rules/compliance.py +54 -0
- git_security_sentinel/rules/database.py +87 -0
- git_security_sentinel/rules/insecure_code.py +130 -0
- git_security_sentinel/rules/sensitive_files.py +48 -0
- git_security_sentinel/suppression/__init__.py +31 -0
- git_security_sentinel/suppression/baseline.py +133 -0
- git_security_sentinel/suppression/comment_filter.py +99 -0
- git_security_sentinel/suppression/ignore_filter.py +154 -0
- git_security_sentinel/update/__init__.py +27 -0
- git_security_sentinel/update/checker.py +189 -0
- git_security_sentinel-1.2.0.dist-info/METADATA +583 -0
- git_security_sentinel-1.2.0.dist-info/RECORD +41 -0
- git_security_sentinel-1.2.0.dist-info/WHEEL +5 -0
- git_security_sentinel-1.2.0.dist-info/entry_points.txt +4 -0
- git_security_sentinel-1.2.0.dist-info/licenses/LICENSE +21 -0
- git_security_sentinel-1.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - Core Git Diff Security Scanner.
|
|
3
|
+
Deterministic diff analysis, secret detection, evidence redaction, and reporting.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
10
|
+
|
|
11
|
+
from git_security_sentinel.core.models import (
|
|
12
|
+
ACCEPTED_LICENSE_NAMES,
|
|
13
|
+
Finding,
|
|
14
|
+
LicenseStatus,
|
|
15
|
+
Rule,
|
|
16
|
+
SCANNER_NAME,
|
|
17
|
+
ScanReport,
|
|
18
|
+
ScanSummary,
|
|
19
|
+
VERSION,
|
|
20
|
+
)
|
|
21
|
+
from git_security_sentinel.core.diff_parser import UnifiedDiffParser
|
|
22
|
+
from git_security_sentinel.redaction.redactor import (
|
|
23
|
+
IGNORE_PLACEHOLDERS,
|
|
24
|
+
is_benign_generic_value,
|
|
25
|
+
redact_text,
|
|
26
|
+
)
|
|
27
|
+
from git_security_sentinel.rules.catalog import (
|
|
28
|
+
ALL_RULES,
|
|
29
|
+
get_all_rules,
|
|
30
|
+
get_rule_by_id,
|
|
31
|
+
)
|
|
32
|
+
from git_security_sentinel.suppression.comment_filter import (
|
|
33
|
+
is_rule_suppressed,
|
|
34
|
+
parse_inline_suppression,
|
|
35
|
+
)
|
|
36
|
+
from git_security_sentinel.suppression.ignore_filter import (
|
|
37
|
+
PathFilter,
|
|
38
|
+
load_sentinelignore,
|
|
39
|
+
)
|
|
40
|
+
from git_security_sentinel.suppression.baseline import (
|
|
41
|
+
BaselineFilter,
|
|
42
|
+
compute_fingerprint,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# Detection rules catalog
|
|
46
|
+
DETECTION_RULES: List[Rule] = get_all_rules()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class GitSecurityScanner:
|
|
50
|
+
"""
|
|
51
|
+
Deterministic static security scanner for Git diffs.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
repo_root: Optional[Path] = None,
|
|
57
|
+
rules: Optional[List[Any]] = None,
|
|
58
|
+
path_filter: Optional[PathFilter] = None,
|
|
59
|
+
baseline_filter: Optional[BaselineFilter] = None,
|
|
60
|
+
):
|
|
61
|
+
self.repo_root = Path(repo_root) if repo_root else Path.cwd()
|
|
62
|
+
self.rules = rules if rules is not None else DETECTION_RULES
|
|
63
|
+
|
|
64
|
+
if path_filter is not None:
|
|
65
|
+
self.path_filter = path_filter
|
|
66
|
+
else:
|
|
67
|
+
ignore_patterns = load_sentinelignore(self.repo_root)
|
|
68
|
+
self.path_filter = PathFilter(ignore_patterns) if ignore_patterns else None
|
|
69
|
+
|
|
70
|
+
self.baseline_filter = baseline_filter
|
|
71
|
+
|
|
72
|
+
def run_git_command(self, args: List[str], timeout_sec: int = 25) -> Tuple[int, str, str]:
|
|
73
|
+
"""
|
|
74
|
+
Executes a git command safely without shell=True.
|
|
75
|
+
Disables external diffs and color formatting.
|
|
76
|
+
"""
|
|
77
|
+
cmd = ["git"] + args
|
|
78
|
+
try:
|
|
79
|
+
res = subprocess.run(
|
|
80
|
+
cmd,
|
|
81
|
+
cwd=str(self.repo_root),
|
|
82
|
+
stdout=subprocess.PIPE,
|
|
83
|
+
stderr=subprocess.PIPE,
|
|
84
|
+
encoding="utf-8",
|
|
85
|
+
errors="replace",
|
|
86
|
+
timeout=timeout_sec,
|
|
87
|
+
check=False,
|
|
88
|
+
)
|
|
89
|
+
return res.returncode, res.stdout, res.stderr
|
|
90
|
+
except FileNotFoundError:
|
|
91
|
+
return 127, "", "Git executable not found in system PATH."
|
|
92
|
+
except subprocess.TimeoutExpired:
|
|
93
|
+
return 124, "", f"Git command timed out after {timeout_sec} seconds."
|
|
94
|
+
except Exception as e:
|
|
95
|
+
return 1, "", str(e)
|
|
96
|
+
|
|
97
|
+
def check_is_git_repository(self) -> Tuple[bool, Optional[str]]:
|
|
98
|
+
"""Verify repository status."""
|
|
99
|
+
code, out, err = self.run_git_command(["rev-parse", "--is-inside-work-tree"])
|
|
100
|
+
if code != 0 or out.strip() != "true":
|
|
101
|
+
return False, err.strip() or "Not a git repository (or any of the parent directories)."
|
|
102
|
+
return True, None
|
|
103
|
+
|
|
104
|
+
def check_license(self) -> Dict[str, Any]:
|
|
105
|
+
"""Check for root license file without modifying the repo."""
|
|
106
|
+
for name in ACCEPTED_LICENSE_NAMES:
|
|
107
|
+
candidate = self.repo_root / name
|
|
108
|
+
if candidate.is_file():
|
|
109
|
+
return {
|
|
110
|
+
"root_license_present": True,
|
|
111
|
+
"license_file": name,
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
"root_license_present": False,
|
|
115
|
+
"license_file": None,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
def get_diff(self, mode: str, base_branch: Optional[str] = None) -> Tuple[str, List[str]]:
|
|
119
|
+
"""
|
|
120
|
+
Fetch unified git diff based on scan mode:
|
|
121
|
+
- 'staged': git diff --staged --no-color --no-ext-diff
|
|
122
|
+
- 'unstaged': git diff --no-color --no-ext-diff
|
|
123
|
+
- 'all': staged + unstaged combined (git diff HEAD or unstaged + staged)
|
|
124
|
+
- 'base': git diff $(git merge-base base_branch HEAD) HEAD --no-color --no-ext-diff
|
|
125
|
+
"""
|
|
126
|
+
errors: List[str] = []
|
|
127
|
+
|
|
128
|
+
if mode == "staged":
|
|
129
|
+
code, out, err = self.run_git_command(["diff", "--staged", "--no-color", "--no-ext-diff"])
|
|
130
|
+
if code != 0:
|
|
131
|
+
errors.append(f"Failed to get staged diff: {err.strip()}")
|
|
132
|
+
return out, errors
|
|
133
|
+
|
|
134
|
+
elif mode == "unstaged":
|
|
135
|
+
code, out, err = self.run_git_command(["diff", "--no-color", "--no-ext-diff"])
|
|
136
|
+
if code != 0:
|
|
137
|
+
errors.append(f"Failed to get unstaged diff: {err.strip()}")
|
|
138
|
+
return out, errors
|
|
139
|
+
|
|
140
|
+
elif mode == "all":
|
|
141
|
+
code_head, _, _ = self.run_git_command(["rev-parse", "--verify", "HEAD"])
|
|
142
|
+
if code_head == 0:
|
|
143
|
+
code, out, err = self.run_git_command(["diff", "HEAD", "--no-color", "--no-ext-diff"])
|
|
144
|
+
if code != 0:
|
|
145
|
+
errors.append(f"Failed to get all changes against HEAD: {err.strip()}")
|
|
146
|
+
return out, errors
|
|
147
|
+
else:
|
|
148
|
+
code, out, err = self.run_git_command(["diff", "--staged", "--no-color", "--no-ext-diff"])
|
|
149
|
+
if code != 0:
|
|
150
|
+
errors.append(f"Failed to get staged diff for initial commit: {err.strip()}")
|
|
151
|
+
return out, errors
|
|
152
|
+
|
|
153
|
+
elif mode == "base":
|
|
154
|
+
if not base_branch:
|
|
155
|
+
errors.append("Base branch must be specified when using --base mode.")
|
|
156
|
+
return "", errors
|
|
157
|
+
|
|
158
|
+
code_mb, out_mb, err_mb = self.run_git_command(["merge-base", base_branch, "HEAD"])
|
|
159
|
+
if code_mb != 0 or not out_mb.strip():
|
|
160
|
+
errors.append(
|
|
161
|
+
f"Could not compute merge-base between '{base_branch}' and 'HEAD': {err_mb.strip()}"
|
|
162
|
+
)
|
|
163
|
+
return "", errors
|
|
164
|
+
|
|
165
|
+
merge_base = out_mb.strip()
|
|
166
|
+
code, out, err = self.run_git_command(
|
|
167
|
+
["diff", merge_base, "HEAD", "--no-color", "--no-ext-diff"]
|
|
168
|
+
)
|
|
169
|
+
if code != 0:
|
|
170
|
+
errors.append(f"Failed to get diff against merge-base {merge_base}: {err.strip()}")
|
|
171
|
+
return out, errors
|
|
172
|
+
|
|
173
|
+
else:
|
|
174
|
+
errors.append(f"Unknown scan mode: {mode}")
|
|
175
|
+
return "", errors
|
|
176
|
+
|
|
177
|
+
def scan_diff_report(
|
|
178
|
+
self,
|
|
179
|
+
diff_content: str,
|
|
180
|
+
scan_mode: str,
|
|
181
|
+
path_filter: Optional[PathFilter] = None,
|
|
182
|
+
baseline_filter: Optional[BaselineFilter] = None,
|
|
183
|
+
) -> ScanReport:
|
|
184
|
+
"""
|
|
185
|
+
Parse diff content, evaluate active detection rules, sanitize evidence,
|
|
186
|
+
apply path exclusions, comment suppression, and baseline filtering,
|
|
187
|
+
and assemble a typed ScanReport dataclass instance.
|
|
188
|
+
"""
|
|
189
|
+
active_path_filter = path_filter if path_filter is not None else self.path_filter
|
|
190
|
+
active_baseline_filter = baseline_filter if baseline_filter is not None else self.baseline_filter
|
|
191
|
+
|
|
192
|
+
parser = UnifiedDiffParser()
|
|
193
|
+
added_lines = parser.parse(diff_content)
|
|
194
|
+
license_info = self.check_license()
|
|
195
|
+
|
|
196
|
+
findings: List[Finding] = []
|
|
197
|
+
suppressed_findings: List[Finding] = []
|
|
198
|
+
seen_finding_keys = set()
|
|
199
|
+
|
|
200
|
+
for item in added_lines:
|
|
201
|
+
file_path = item["file"]
|
|
202
|
+
line_no = item["line"]
|
|
203
|
+
raw_content = item["content"]
|
|
204
|
+
|
|
205
|
+
if active_path_filter and active_path_filter.is_ignored(file_path):
|
|
206
|
+
continue
|
|
207
|
+
|
|
208
|
+
for rule in self.rules:
|
|
209
|
+
rule_id = rule.rule_id if hasattr(rule, "rule_id") else rule["rule_id"]
|
|
210
|
+
category = rule.category if hasattr(rule, "category") else rule["category"]
|
|
211
|
+
severity = rule.severity if hasattr(rule, "severity") else rule["severity"]
|
|
212
|
+
confidence = rule.confidence if hasattr(rule, "confidence") else rule["confidence"]
|
|
213
|
+
pattern = rule.pattern if hasattr(rule, "pattern") else rule["pattern"]
|
|
214
|
+
message = rule.message if hasattr(rule, "message") else rule["message"]
|
|
215
|
+
recommendation = rule.recommendation if hasattr(rule, "recommendation") else rule["recommendation"]
|
|
216
|
+
|
|
217
|
+
# Category: sensitive_files target file paths rather than line content
|
|
218
|
+
if category == "sensitive_files" or rule_id.startswith("file."):
|
|
219
|
+
if pattern.search(file_path):
|
|
220
|
+
dup_key = (rule_id, file_path, 1)
|
|
221
|
+
if dup_key not in seen_finding_keys:
|
|
222
|
+
seen_finding_keys.add(dup_key)
|
|
223
|
+
evidence = raw_content.strip() if raw_content.strip() else file_path
|
|
224
|
+
redacted_evidence = redact_text(evidence)
|
|
225
|
+
fp = compute_fingerprint(rule_id, file_path, redacted_evidence)
|
|
226
|
+
|
|
227
|
+
finding = Finding(
|
|
228
|
+
rule_id=rule_id,
|
|
229
|
+
category=category,
|
|
230
|
+
severity=severity,
|
|
231
|
+
confidence=confidence,
|
|
232
|
+
file=file_path,
|
|
233
|
+
line=1,
|
|
234
|
+
message=message,
|
|
235
|
+
evidence=redacted_evidence,
|
|
236
|
+
recommendation=recommendation,
|
|
237
|
+
fingerprint=fp,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
inline_supp = parse_inline_suppression(raw_content)
|
|
241
|
+
is_comment_supp = is_rule_suppressed(rule_id, inline_supp)
|
|
242
|
+
is_base_supp = active_baseline_filter.is_suppressed(finding) if active_baseline_filter else False
|
|
243
|
+
|
|
244
|
+
if is_comment_supp or is_base_supp:
|
|
245
|
+
finding.suppressed = True
|
|
246
|
+
finding.suppression_reason = "inline_comment" if is_comment_supp else "baseline"
|
|
247
|
+
suppressed_findings.append(finding)
|
|
248
|
+
else:
|
|
249
|
+
findings.append(finding)
|
|
250
|
+
else:
|
|
251
|
+
match = pattern.search(raw_content)
|
|
252
|
+
if not match:
|
|
253
|
+
continue
|
|
254
|
+
|
|
255
|
+
# Filter common benign placeholders and templates
|
|
256
|
+
if rule_id in (
|
|
257
|
+
"secret.generic_credential",
|
|
258
|
+
"insecure_code.temp_credential",
|
|
259
|
+
"secret.datadog_key",
|
|
260
|
+
"secret.aws_secret_key",
|
|
261
|
+
):
|
|
262
|
+
matched_val = match.group(1) if match.groups() else match.group(0)
|
|
263
|
+
if is_benign_generic_value(matched_val):
|
|
264
|
+
continue
|
|
265
|
+
|
|
266
|
+
validator = getattr(rule, "validator", None) if hasattr(rule, "validator") else rule.get("validator")
|
|
267
|
+
if validator and callable(validator) and not validator(match, raw_content):
|
|
268
|
+
continue
|
|
269
|
+
|
|
270
|
+
dup_key = (rule_id, file_path, line_no)
|
|
271
|
+
if dup_key in seen_finding_keys:
|
|
272
|
+
continue
|
|
273
|
+
seen_finding_keys.add(dup_key)
|
|
274
|
+
|
|
275
|
+
redacted_evidence = redact_text(raw_content.strip())
|
|
276
|
+
if rule_id.startswith("secret.") and match.group(0) in redacted_evidence:
|
|
277
|
+
redacted_evidence = "[REDACTED]"
|
|
278
|
+
|
|
279
|
+
fp = compute_fingerprint(rule_id, file_path, redacted_evidence)
|
|
280
|
+
|
|
281
|
+
finding = Finding(
|
|
282
|
+
rule_id=rule_id,
|
|
283
|
+
category=category,
|
|
284
|
+
severity=severity,
|
|
285
|
+
confidence=confidence,
|
|
286
|
+
file=file_path,
|
|
287
|
+
line=line_no,
|
|
288
|
+
message=message,
|
|
289
|
+
evidence=redacted_evidence,
|
|
290
|
+
recommendation=recommendation,
|
|
291
|
+
fingerprint=fp,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
inline_supp = parse_inline_suppression(raw_content)
|
|
295
|
+
is_comment_supp = is_rule_suppressed(rule_id, inline_supp)
|
|
296
|
+
is_base_supp = active_baseline_filter.is_suppressed(finding) if active_baseline_filter else False
|
|
297
|
+
|
|
298
|
+
if is_comment_supp or is_base_supp:
|
|
299
|
+
finding.suppressed = True
|
|
300
|
+
finding.suppression_reason = "inline_comment" if is_comment_supp else "baseline"
|
|
301
|
+
suppressed_findings.append(finding)
|
|
302
|
+
else:
|
|
303
|
+
findings.append(finding)
|
|
304
|
+
|
|
305
|
+
summary = ScanSummary(
|
|
306
|
+
total=len(findings),
|
|
307
|
+
critical=sum(1 for f in findings if f.severity == "critical"),
|
|
308
|
+
high=sum(1 for f in findings if f.severity == "high"),
|
|
309
|
+
medium=sum(1 for f in findings if f.severity == "medium"),
|
|
310
|
+
low=sum(1 for f in findings if f.severity == "low"),
|
|
311
|
+
suppressed=len(suppressed_findings),
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
lic_status = LicenseStatus(
|
|
315
|
+
root_license_present=license_info.get("root_license_present", False),
|
|
316
|
+
license_file=license_info.get("license_file"),
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
return ScanReport(
|
|
320
|
+
scanner=SCANNER_NAME,
|
|
321
|
+
version=VERSION,
|
|
322
|
+
status="completed",
|
|
323
|
+
scan_mode=scan_mode,
|
|
324
|
+
findings=findings,
|
|
325
|
+
license=lic_status,
|
|
326
|
+
summary=summary,
|
|
327
|
+
errors=[],
|
|
328
|
+
suppressed_findings=suppressed_findings,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def scan_diff_content(
|
|
332
|
+
self,
|
|
333
|
+
diff_content: str,
|
|
334
|
+
scan_mode: str,
|
|
335
|
+
path_filter: Optional[PathFilter] = None,
|
|
336
|
+
baseline_filter: Optional[BaselineFilter] = None,
|
|
337
|
+
) -> Dict[str, Any]:
|
|
338
|
+
"""
|
|
339
|
+
Parse diff content, run rules, sanitize evidence, and assemble structured report dict.
|
|
340
|
+
"""
|
|
341
|
+
return self.scan_diff_report(
|
|
342
|
+
diff_content,
|
|
343
|
+
scan_mode,
|
|
344
|
+
path_filter=path_filter,
|
|
345
|
+
baseline_filter=baseline_filter,
|
|
346
|
+
).to_dict()
|
|
347
|
+
|
|
348
|
+
def generate_sanitized_diff(self, diff_content: str) -> str:
|
|
349
|
+
"""
|
|
350
|
+
Generates a sanitized unified diff with all detected secret values redacted.
|
|
351
|
+
"""
|
|
352
|
+
lines = diff_content.splitlines()
|
|
353
|
+
sanitized_lines = []
|
|
354
|
+
for line in lines:
|
|
355
|
+
if line.startswith("+") and not line.startswith("+++"):
|
|
356
|
+
# Redact added lines
|
|
357
|
+
sanitized_lines.append("+" + redact_text(line[1:]))
|
|
358
|
+
else:
|
|
359
|
+
sanitized_lines.append(line)
|
|
360
|
+
return "\n".join(sanitized_lines) + ("\n" if diff_content.endswith("\n") else "")
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - Git Hooks Integration.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from git_security_sentinel.hooks.bootstrap import bootstrap_project
|
|
6
|
+
from git_security_sentinel.hooks.installer import install_pre_commit_hook
|
|
7
|
+
|
|
8
|
+
__all__ = ["bootstrap_project", "install_pre_commit_hook"]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - One-Command Project Bootstrap.
|
|
3
|
+
|
|
4
|
+
Creates the minimal starter files and installs the pre-commit hook so a
|
|
5
|
+
developer can go from clone to protected repository with a single command:
|
|
6
|
+
`git-scan --init`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import List, Optional, Tuple
|
|
11
|
+
|
|
12
|
+
from git_security_sentinel.hooks.installer import install_pre_commit_hook
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
CONFIG_TEMPLATE = """# Git Security Sentinel configuration
|
|
16
|
+
# AI defaults live here so `git scan --ai` needs no extra flags.
|
|
17
|
+
severity_threshold: high
|
|
18
|
+
|
|
19
|
+
ai:
|
|
20
|
+
provider: auto # auto, ollama, gemini, openai, or groq
|
|
21
|
+
# model: gemma3:4b # override the provider default model
|
|
22
|
+
# allow_remote: false # only for non-loopback Ollama endpoints
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
IGNORE_TEMPLATE = """# Paths excluded from Git Security Sentinel scans
|
|
26
|
+
tests/fixtures/**
|
|
27
|
+
**/*.generated.py
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
ENV_TEMPLATE = """# Add only the keys you actually use. Never commit real credentials.
|
|
31
|
+
# GEMINI_API_KEY=your-key
|
|
32
|
+
# OPENAI_API_KEY=your-key
|
|
33
|
+
# GROQ_API_KEY=your-key
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
STARTER_FILES = (
|
|
37
|
+
(".sentinel.yaml", CONFIG_TEMPLATE),
|
|
38
|
+
(".sentinelignore", IGNORE_TEMPLATE),
|
|
39
|
+
(".env.example", ENV_TEMPLATE),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def bootstrap_project(
|
|
44
|
+
repo_root: Optional[Path] = None,
|
|
45
|
+
force: bool = False,
|
|
46
|
+
) -> Tuple[bool, List[str]]:
|
|
47
|
+
"""
|
|
48
|
+
Bootstrap a repository with starter config files and a pre-commit hook.
|
|
49
|
+
|
|
50
|
+
Existing files are never overwritten unless `force` is True.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
(success, messages): success is False only if a write or hook install
|
|
54
|
+
actually failed; skipped files are reported but are not an error.
|
|
55
|
+
"""
|
|
56
|
+
root = (Path(repo_root) if repo_root else Path.cwd()).resolve()
|
|
57
|
+
messages: List[str] = []
|
|
58
|
+
ok = True
|
|
59
|
+
|
|
60
|
+
for name, template in STARTER_FILES:
|
|
61
|
+
target = root / name
|
|
62
|
+
if target.exists() and not force:
|
|
63
|
+
messages.append(f"[skip] {name} already exists (use --force to overwrite)")
|
|
64
|
+
continue
|
|
65
|
+
try:
|
|
66
|
+
target.write_text(template, encoding="utf-8")
|
|
67
|
+
messages.append(f"[ok] created {name}")
|
|
68
|
+
except Exception as e:
|
|
69
|
+
ok = False
|
|
70
|
+
messages.append(f"[fail] could not write {name}: {e}")
|
|
71
|
+
|
|
72
|
+
hook_ok, hook_msg = install_pre_commit_hook(repo_root=root, force=force)
|
|
73
|
+
if hook_ok:
|
|
74
|
+
messages.append("[ok] installed .git/hooks/pre-commit")
|
|
75
|
+
elif "already exists" in hook_msg:
|
|
76
|
+
messages.append(f"[skip] {hook_msg}")
|
|
77
|
+
else:
|
|
78
|
+
ok = False
|
|
79
|
+
messages.append(f"[fail] {hook_msg}")
|
|
80
|
+
|
|
81
|
+
if ok:
|
|
82
|
+
messages.append("")
|
|
83
|
+
messages.append("Done. Next: git add . && git scan --ai")
|
|
84
|
+
return ok, messages
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - Pre-Commit Hook Installer.
|
|
3
|
+
Installs executable pre-commit hook into .git/hooks/pre-commit.
|
|
4
|
+
Zero third-party dependencies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import subprocess
|
|
10
|
+
from typing import Optional, Tuple
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def install_pre_commit_hook(
|
|
14
|
+
repo_root: Optional[Path] = None,
|
|
15
|
+
force: bool = False,
|
|
16
|
+
) -> Tuple[bool, str]:
|
|
17
|
+
"""
|
|
18
|
+
Installs Git Security Sentinel pre-commit hook into repository .git/hooks/pre-commit.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
repo_root: Optional path to repository root. Defaults to current working directory.
|
|
22
|
+
force: If True, overwrites existing pre-commit hook if not a sentinel hook.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Tuple[bool, str]: (success, status_message)
|
|
26
|
+
"""
|
|
27
|
+
root = (Path(repo_root) if repo_root else Path.cwd()).resolve()
|
|
28
|
+
|
|
29
|
+
# Discover .git directory
|
|
30
|
+
git_dir: Optional[Path] = None
|
|
31
|
+
dot_git = root / ".git"
|
|
32
|
+
if dot_git.is_dir():
|
|
33
|
+
git_dir = dot_git
|
|
34
|
+
elif dot_git.is_file():
|
|
35
|
+
try:
|
|
36
|
+
content = dot_git.read_text(encoding="utf-8", errors="replace").strip()
|
|
37
|
+
if content.startswith("gitdir:"):
|
|
38
|
+
target = content.split(":", 1)[1].strip()
|
|
39
|
+
git_dir = (root / target).resolve()
|
|
40
|
+
except Exception:
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
if git_dir is None:
|
|
44
|
+
try:
|
|
45
|
+
res = subprocess.run(
|
|
46
|
+
["git", "rev-parse", "--show-toplevel"],
|
|
47
|
+
cwd=str(root),
|
|
48
|
+
capture_output=True,
|
|
49
|
+
encoding="utf-8",
|
|
50
|
+
errors="replace",
|
|
51
|
+
check=False,
|
|
52
|
+
)
|
|
53
|
+
if res.returncode != 0 or not res.stdout.strip():
|
|
54
|
+
return False, f"Directory is not a Git repository: {root}"
|
|
55
|
+
if Path(res.stdout.strip()).resolve() != root:
|
|
56
|
+
return False, f"Directory is not a Git repository: {root}"
|
|
57
|
+
|
|
58
|
+
res_dir = subprocess.run(
|
|
59
|
+
["git", "rev-parse", "--git-dir"],
|
|
60
|
+
cwd=str(root),
|
|
61
|
+
capture_output=True,
|
|
62
|
+
encoding="utf-8",
|
|
63
|
+
errors="replace",
|
|
64
|
+
check=False,
|
|
65
|
+
)
|
|
66
|
+
if res_dir.returncode == 0 and res_dir.stdout.strip():
|
|
67
|
+
cand = Path(res_dir.stdout.strip())
|
|
68
|
+
git_dir = cand if cand.is_absolute() else (root / cand).resolve()
|
|
69
|
+
except Exception:
|
|
70
|
+
return False, f"Directory is not a Git repository: {root}"
|
|
71
|
+
|
|
72
|
+
if git_dir is None or not git_dir.exists():
|
|
73
|
+
return False, f"Directory is not a Git repository: {root}"
|
|
74
|
+
|
|
75
|
+
hooks_dir = git_dir / "hooks"
|
|
76
|
+
hook_file = hooks_dir / "pre-commit"
|
|
77
|
+
|
|
78
|
+
if hook_file.is_file():
|
|
79
|
+
try:
|
|
80
|
+
existing_content = hook_file.read_text(encoding="utf-8", errors="replace")
|
|
81
|
+
except Exception as e:
|
|
82
|
+
return False, f"Failed to read existing pre-commit hook: {e}"
|
|
83
|
+
|
|
84
|
+
if "git-scan" not in existing_content:
|
|
85
|
+
if not force:
|
|
86
|
+
return (
|
|
87
|
+
False,
|
|
88
|
+
f"A pre-commit hook already exists at {hook_file}. Use --force to overwrite it.",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
hooks_dir.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
hook_script = "#!/bin/sh\n# Git Security Sentinel pre-commit hook\nexec git-scan --staged\n"
|
|
93
|
+
|
|
94
|
+
try:
|
|
95
|
+
hook_file.write_text(hook_script, encoding="utf-8")
|
|
96
|
+
try:
|
|
97
|
+
os.chmod(hook_file, 0o755)
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
100
|
+
except Exception as e:
|
|
101
|
+
return False, f"Failed to write pre-commit hook: {e}"
|
|
102
|
+
|
|
103
|
+
return True, "Hook installed successfully."
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Git Security Sentinel - Output Formatters.
|
|
3
|
+
Includes Text, JSON, and SARIF 2.1.0 report generators.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from git_security_sentinel.output.sarif import (
|
|
7
|
+
SARIF_SCHEMA_URI,
|
|
8
|
+
SARIF_VERSION,
|
|
9
|
+
SEVERITY_LEVEL_MAP,
|
|
10
|
+
generate_sarif_report,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"SARIF_SCHEMA_URI",
|
|
15
|
+
"SARIF_VERSION",
|
|
16
|
+
"SEVERITY_LEVEL_MAP",
|
|
17
|
+
"generate_sarif_report",
|
|
18
|
+
]
|