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.
Files changed (41) hide show
  1. git_security_sentinel/__init__.py +74 -0
  2. git_security_sentinel/__main__.py +9 -0
  3. git_security_sentinel/ai/__init__.py +17 -0
  4. git_security_sentinel/ai/cost.py +34 -0
  5. git_security_sentinel/ai/prompts.py +81 -0
  6. git_security_sentinel/ai_cli.py +884 -0
  7. git_security_sentinel/cli.py +937 -0
  8. git_security_sentinel/config/__init__.py +16 -0
  9. git_security_sentinel/config/loader.py +245 -0
  10. git_security_sentinel/core/__init__.py +42 -0
  11. git_security_sentinel/core/diff_parser.py +93 -0
  12. git_security_sentinel/core/models.py +111 -0
  13. git_security_sentinel/core/scanner.py +360 -0
  14. git_security_sentinel/hooks/__init__.py +8 -0
  15. git_security_sentinel/hooks/bootstrap.py +84 -0
  16. git_security_sentinel/hooks/installer.py +103 -0
  17. git_security_sentinel/output/__init__.py +18 -0
  18. git_security_sentinel/output/sarif.py +179 -0
  19. git_security_sentinel/py.typed +0 -0
  20. git_security_sentinel/redaction/__init__.py +15 -0
  21. git_security_sentinel/redaction/redactor.py +313 -0
  22. git_security_sentinel/rules/__init__.py +29 -0
  23. git_security_sentinel/rules/auth.py +103 -0
  24. git_security_sentinel/rules/catalog.py +63 -0
  25. git_security_sentinel/rules/cloud.py +132 -0
  26. git_security_sentinel/rules/compliance.py +54 -0
  27. git_security_sentinel/rules/database.py +87 -0
  28. git_security_sentinel/rules/insecure_code.py +130 -0
  29. git_security_sentinel/rules/sensitive_files.py +48 -0
  30. git_security_sentinel/suppression/__init__.py +31 -0
  31. git_security_sentinel/suppression/baseline.py +133 -0
  32. git_security_sentinel/suppression/comment_filter.py +99 -0
  33. git_security_sentinel/suppression/ignore_filter.py +154 -0
  34. git_security_sentinel/update/__init__.py +27 -0
  35. git_security_sentinel/update/checker.py +189 -0
  36. git_security_sentinel-1.2.0.dist-info/METADATA +583 -0
  37. git_security_sentinel-1.2.0.dist-info/RECORD +41 -0
  38. git_security_sentinel-1.2.0.dist-info/WHEEL +5 -0
  39. git_security_sentinel-1.2.0.dist-info/entry_points.txt +4 -0
  40. git_security_sentinel-1.2.0.dist-info/licenses/LICENSE +21 -0
  41. git_security_sentinel-1.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,937 @@
1
+ """
2
+ Git Security Sentinel - CLI Entry Point.
3
+ Provides git-scan, git-security-sentinel, and python -m git_security_sentinel interfaces.
4
+ """
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import sys
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from git_security_sentinel.core.models import (
14
+ SCANNER_NAME,
15
+ SEVERITY_ORDER,
16
+ VERSION,
17
+ )
18
+ from git_security_sentinel.core.scanner import GitSecurityScanner
19
+ from git_security_sentinel.config.loader import load_config
20
+ from git_security_sentinel.hooks.bootstrap import bootstrap_project
21
+ from git_security_sentinel.hooks.installer import install_pre_commit_hook
22
+ from git_security_sentinel.output.sarif import generate_sarif_report
23
+ from git_security_sentinel.rules.catalog import get_all_rules, get_rule_by_id
24
+ from git_security_sentinel.suppression.baseline import BaselineFilter
25
+ from git_security_sentinel.suppression.ignore_filter import (
26
+ PathFilter,
27
+ load_sentinelignore,
28
+ )
29
+ from git_security_sentinel.update.checker import (
30
+ check_for_pypi_update,
31
+ print_update_banner,
32
+ run_self_upgrade,
33
+ )
34
+
35
+
36
+ def format_text_report(
37
+ report: Dict[str, Any],
38
+ color: bool = False,
39
+ verbose: bool = False,
40
+ ) -> str:
41
+ """Format human-readable CLI summary with optional ANSI color and verbosity."""
42
+ if color:
43
+ c_red = "\033[91m"
44
+ c_yellow = "\033[93m"
45
+ c_green = "\033[92m"
46
+ c_cyan = "\033[96m"
47
+ c_bold = "\033[1m"
48
+ c_reset = "\033[0m"
49
+ else:
50
+ c_red = c_yellow = c_green = c_cyan = c_bold = c_reset = ""
51
+
52
+ lines = []
53
+ lines.append("=" * 68)
54
+ lines.append(f" {c_bold}GIT SECURITY SENTINEL v{report.get('version', VERSION)}{c_reset}")
55
+ lines.append(" Privacy-First Git Security Scanner")
56
+ lines.append("=" * 68)
57
+ lines.append(f"Status : {report.get('status', 'unknown').upper()}")
58
+ lines.append(f"Scan Mode : {report.get('scan_mode', 'all')}")
59
+
60
+ lic = report.get("license", {})
61
+ lic_present = lic.get("root_license_present", False)
62
+ lic_file = lic.get("license_file") or "None"
63
+ lic_desc = f"{c_green}Found ({lic_file}){c_reset}" if lic_present else f"{c_yellow}MISSING{c_reset}"
64
+ lines.append(f"Root License : {lic_desc}")
65
+
66
+ summary = report.get("summary", {})
67
+ supp_count = summary.get("suppressed", 0)
68
+ supp_part = f" | Suppressed: {supp_count}" if (supp_count or verbose) else ""
69
+ lines.append(
70
+ f"Findings : Total: {summary.get('total', 0)} | "
71
+ f"Critical: {summary.get('critical', 0)} | "
72
+ f"High: {summary.get('high', 0)} | "
73
+ f"Medium: {summary.get('medium', 0)} | "
74
+ f"Low: {summary.get('low', 0)}"
75
+ f"{supp_part}"
76
+ )
77
+ lines.append("-" * 68)
78
+
79
+ errors = report.get("errors", [])
80
+ if errors:
81
+ lines.append(f"{c_red}ERRORS ENCOUNTERED:{c_reset}")
82
+ for err in errors:
83
+ lines.append(f" [!] {err}")
84
+ lines.append("-" * 68)
85
+
86
+ findings = report.get("findings", [])
87
+ if not findings:
88
+ lines.append(f"{c_green}No security issues detected in the inspected diff.{c_reset}")
89
+ else:
90
+ for idx, f in enumerate(findings, start=1):
91
+ sev = f["severity"].upper()
92
+ c_sev = c_red if sev in ("CRITICAL", "HIGH") else (c_yellow if sev == "MEDIUM" else c_cyan)
93
+ lines.append(f"[{idx}] [{c_sev}{sev}{c_reset}] {c_bold}{f['rule_id']}{c_reset} ({f['category']})")
94
+ lines.append(f" Location : {f['file']}:{f['line']}")
95
+ lines.append(f" Message : {f['message']}")
96
+ lines.append(f" Evidence : {f['evidence']}")
97
+ lines.append(f" Remediation: {f['recommendation']}")
98
+ lines.append("")
99
+
100
+ lines.append("=" * 68)
101
+ return "\n".join(lines)
102
+
103
+
104
+ def evaluate_exit_code(report: Dict[str, Any], threshold: str) -> int:
105
+ """
106
+ Determine exit code:
107
+ 0: Scan completed, no findings exceed severity threshold.
108
+ 1: Scan completed, findings meet or exceed severity threshold.
109
+ 2: Scan execution or configuration error.
110
+ """
111
+ if report.get("status") == "failed" or report.get("errors"):
112
+ return 2
113
+
114
+ threshold_level = SEVERITY_ORDER.get(threshold.lower(), 3)
115
+ findings = report.get("findings", [])
116
+
117
+ for f in findings:
118
+ sev = f.get("severity", "low").lower()
119
+ if SEVERITY_ORDER.get(sev, 0) >= threshold_level:
120
+ return 1
121
+
122
+ return 0
123
+
124
+
125
+ def format_oneline_report(report: Dict[str, Any]) -> str:
126
+ """Concise one-line-per-finding output for daily developer use."""
127
+ lines: List[str] = []
128
+ for err in report.get("errors", []):
129
+ lines.append(f"[!] ERROR: {err}")
130
+ for f in report.get("findings", []):
131
+ severity = str(f.get("severity", "low")).upper()
132
+ lines.append(
133
+ f"{f.get('file')}:{f.get('line')} [{severity}] "
134
+ f"{f.get('rule_id')} - {f.get('message')}"
135
+ )
136
+ if not lines:
137
+ return "OK: no security issues detected"
138
+ summary = report.get("summary", {})
139
+ lines.append(
140
+ f"Summary: {summary.get('total', 0)} finding(s) "
141
+ f"(critical {summary.get('critical', 0)}, high {summary.get('high', 0)}, "
142
+ f"medium {summary.get('medium', 0)}, low {summary.get('low', 0)})"
143
+ )
144
+ return "\n".join(lines)
145
+
146
+
147
+ def format_github_report(report: Dict[str, Any]) -> str:
148
+ """GitHub Actions workflow commands that annotate changed lines in a PR."""
149
+ def escape(text: Any) -> str:
150
+ return (
151
+ str(text)
152
+ .replace("%", "%25")
153
+ .replace("\r", "%0D")
154
+ .replace("\n", "%0A")
155
+ )
156
+
157
+ levels = {"critical": "error", "high": "error", "medium": "warning", "low": "notice"}
158
+ lines: List[str] = []
159
+ for err in report.get("errors", []):
160
+ lines.append(f"::error::{escape(err)}")
161
+ for f in report.get("findings", []):
162
+ level = levels.get(str(f.get("severity", "low")).lower(), "warning")
163
+ location = f"file={escape(f.get('file', ''))},line={f.get('line', 0)}"
164
+ message = f"{f.get('message', '')} [{f.get('rule_id', '')}]"
165
+ lines.append(f"::{level} {location}::{escape(message)}")
166
+ return "\n".join(lines)
167
+
168
+
169
+ def explain_rule(rule_id: str, json_mode: bool = False) -> int:
170
+ """Print human- or machine-readable guidance for a single detection rule."""
171
+ rule = get_rule_by_id(rule_id)
172
+ if rule is None:
173
+ sys.stderr.write(f"Unknown rule: {rule_id}\n")
174
+ return 2
175
+ data = {
176
+ "rule_id": rule.rule_id,
177
+ "category": rule.category,
178
+ "severity": rule.severity,
179
+ "confidence": rule.confidence,
180
+ "detects": rule.pattern.pattern,
181
+ "message": rule.message,
182
+ "remediation": rule.recommendation,
183
+ "docs": "references/detection-rules.md",
184
+ }
185
+ if json_mode:
186
+ print(json.dumps(data, indent=2))
187
+ return 0
188
+ print(f"Rule : {data['rule_id']}")
189
+ print(f"Category : {data['category']} | Severity: {data['severity']} | Confidence: {data['confidence']}")
190
+ print(f"Detects : {data['detects']}")
191
+ print(f"Message : {data['message']}")
192
+ print(f"Remediation : {data['remediation']}")
193
+ print(f"Docs : {data['docs']}")
194
+ print("Suppress : add '# nosec' to the line if it is a confirmed false positive")
195
+ return 0
196
+
197
+
198
+ def generate_completion(parser: argparse.ArgumentParser, shell: str, prog: str) -> str:
199
+ """Generate a small shell-completion script for the scanner CLI."""
200
+ options = sorted(
201
+ opt for action in parser._actions for opt in action.option_strings if opt.startswith("-")
202
+ )
203
+ words = " ".join(options + ["scan", "--help"])
204
+ if shell == "powershell":
205
+ choices = ", ".join(f"'{w}'" for w in options + ["scan", "--help"])
206
+ return (
207
+ "Register-ArgumentCompleter -Native -CommandName 'git-scan' -ScriptBlock {\n"
208
+ " param($wordToComplete, $commandAst, $cursorPosition)\n"
209
+ f" @({choices}) | Where-Object {{ $_ -like \"$wordToComplete*\" }} |\n"
210
+ " ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }\n"
211
+ "}\n"
212
+ )
213
+ if shell == "bash":
214
+ return (
215
+ f"_{prog.replace('-', '_')}_completion() {{\n"
216
+ ' local cur="${COMP_WORDS[COMP_CWORD]}"\n'
217
+ f' COMPREPLY=( $(compgen -W "{words}" -- "$cur") )\n'
218
+ "}\n"
219
+ f"complete -F _{prog.replace('-', '_')}_completion {prog}\n"
220
+ )
221
+ if shell == "zsh":
222
+ return (
223
+ f"#compdef {prog}\n"
224
+ f"_arguments '*: :(({words}))'\n"
225
+ )
226
+ return (
227
+ f"complete -c {prog} -f -a '{words}'\n"
228
+ )
229
+
230
+
231
+ def resolve_ai_settings(args: argparse.Namespace, config_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
232
+ """
233
+ Resolve AI settings with precedence: CLI flags > config file > env vars > defaults.
234
+ This lets a developer set the provider once and simply run `git scan --ai`.
235
+ """
236
+ cfg = (config_data or {}).get("ai", {})
237
+ if not isinstance(cfg, dict):
238
+ cfg = {}
239
+
240
+ def env_flag(name: str) -> bool:
241
+ return str(os.environ.get(name, "")).strip().lower() in {"1", "true", "yes", "on"}
242
+
243
+ provider = args.provider or cfg.get("provider") or os.environ.get("SENTINEL_AI_PROVIDER") or "auto"
244
+ model = args.model or cfg.get("model") or os.environ.get("SENTINEL_AI_MODEL") or None
245
+ endpoint = args.ai_endpoint or cfg.get("endpoint") or os.environ.get("SENTINEL_AI_ENDPOINT") or None
246
+ allow_remote = bool(
247
+ args.allow_remote or cfg.get("allow_remote") or env_flag("SENTINEL_AI_ALLOW_REMOTE")
248
+ )
249
+ timeout_raw = args.ai_timeout
250
+ if timeout_raw == 120:
251
+ timeout_raw = cfg.get("timeout") or os.environ.get("SENTINEL_AI_TIMEOUT") or 120
252
+ try:
253
+ timeout = int(timeout_raw)
254
+ except (TypeError, ValueError):
255
+ timeout = 120
256
+ return {
257
+ "provider": str(provider),
258
+ "model": str(model) if model else None,
259
+ "endpoint": str(endpoint) if endpoint else None,
260
+ "allow_remote": allow_remote,
261
+ "timeout": timeout,
262
+ }
263
+
264
+
265
+ def build_arg_parser(prog: Optional[str] = None) -> argparse.ArgumentParser:
266
+ parser = argparse.ArgumentParser(
267
+ prog=prog or "git-scan",
268
+ description="Git Security Sentinel: Privacy-first Git diff security scanner.",
269
+ formatter_class=argparse.RawDescriptionHelpFormatter,
270
+ epilog="""Examples:
271
+ git scan --init
272
+ git scan --ai
273
+ git scan --oneline
274
+ git scan --explain secret.aws_access_key
275
+ git scan --update
276
+ git scan --staged
277
+ git scan --all --format json
278
+ git scan --all --format github
279
+ git scan --base main --format sarif --output results.sarif
280
+ git scan --ai --fix --cost-estimate
281
+ git scan --exclude "tests/**" --baseline .sentinel.baseline
282
+ """,
283
+ )
284
+
285
+ # Git dispatches `git scan ...` to the `git-scan` executable as
286
+ # `git-scan scan ...`. Accept the optional leading token so both
287
+ # `git scan --ai` and `git-scan --ai` work identically.
288
+ parser.add_argument(
289
+ "git_command",
290
+ nargs="?",
291
+ choices=["scan"],
292
+ default=None,
293
+ help=argparse.SUPPRESS,
294
+ )
295
+
296
+ mode_group = parser.add_mutually_exclusive_group()
297
+ mode_group.add_argument(
298
+ "--staged",
299
+ action="store_true",
300
+ help="Scan git staged (cached) changes only.",
301
+ )
302
+ mode_group.add_argument(
303
+ "--unstaged",
304
+ action="store_true",
305
+ help="Scan git unstaged working tree changes only.",
306
+ )
307
+ mode_group.add_argument(
308
+ "--all",
309
+ action="store_true",
310
+ help="Scan both staged and unstaged working changes.",
311
+ )
312
+ mode_group.add_argument(
313
+ "--base",
314
+ metavar="BRANCH",
315
+ help="Scan changes against merge-base of current branch and specified base branch.",
316
+ )
317
+ mode_group.add_argument(
318
+ "--diff-file",
319
+ metavar="FILE",
320
+ help="Scan diff from a file, or '-' to read from standard input.",
321
+ )
322
+
323
+ parser.add_argument(
324
+ "--version",
325
+ action="store_true",
326
+ help="Show version (and any available update) and exit.",
327
+ )
328
+ parser.add_argument(
329
+ "--repo-root",
330
+ metavar="PATH",
331
+ default=".",
332
+ help="Path to repository root (defaults to current working directory).",
333
+ )
334
+ parser.add_argument(
335
+ "--format",
336
+ choices=["text", "json", "sarif", "github"],
337
+ default="text",
338
+ help="Console output format (github emits inline PR annotations).",
339
+ )
340
+ parser.add_argument(
341
+ "--init",
342
+ action="store_true",
343
+ help="Set up this repository: starter config, ignore file, .env.example, and pre-commit hook.",
344
+ )
345
+ parser.add_argument(
346
+ "--explain",
347
+ metavar="RULE_ID",
348
+ help="Explain a detection rule and how to fix or suppress it, then exit.",
349
+ )
350
+ parser.add_argument(
351
+ "--completion",
352
+ choices=["powershell", "bash", "zsh", "fish"],
353
+ help="Print a shell completion script for the given shell, then exit.",
354
+ )
355
+ parser.add_argument(
356
+ "--oneline",
357
+ action="store_true",
358
+ help="Concise one-line-per-finding output.",
359
+ )
360
+ parser.add_argument(
361
+ "--key",
362
+ metavar="NAME=VALUE",
363
+ action="append",
364
+ default=[],
365
+ help="With --init, write an API key into the local gitignored .env file (repeatable).",
366
+ )
367
+ parser.add_argument(
368
+ "--install-hook",
369
+ action="store_true",
370
+ help="Install pre-commit hook into repository .git/hooks/pre-commit.",
371
+ )
372
+ parser.add_argument(
373
+ "--force",
374
+ action="store_true",
375
+ help="Overwrite existing starter files or pre-commit hook during --init/--install-hook.",
376
+ )
377
+ parser.add_argument(
378
+ "--update",
379
+ action="store_true",
380
+ help="Update to the latest release (alias of --upgrade).",
381
+ )
382
+ parser.add_argument(
383
+ "--upgrade",
384
+ action="store_true",
385
+ help="Upgrade to the latest release from the package index.",
386
+ )
387
+ parser.add_argument(
388
+ "--index-url",
389
+ metavar="URL",
390
+ help="Package index base URL for update checks and upgrades (e.g. TestPyPI or a private mirror).",
391
+ )
392
+ parser.add_argument(
393
+ "--no-update-check",
394
+ action="store_true",
395
+ help="Disable automatic 24-hour background update check.",
396
+ )
397
+ parser.add_argument(
398
+ "--output",
399
+ metavar="FILE",
400
+ help="Save structured JSON scan report to specified file.",
401
+ )
402
+ parser.add_argument(
403
+ "--redacted-diff-out",
404
+ metavar="FILE",
405
+ help="Save sanitized diff with detected secrets redacted to specified file.",
406
+ )
407
+ parser.add_argument(
408
+ "--severity-threshold",
409
+ choices=["critical", "high", "medium", "low"],
410
+ default=None,
411
+ help="Minimum severity level that triggers an exit code of 1 (default: high).",
412
+ )
413
+ parser.add_argument(
414
+ "--exclude",
415
+ action="append",
416
+ metavar="PATTERN",
417
+ help="Glob pattern to exclude from scanning (can be repeated or comma-separated).",
418
+ )
419
+ parser.add_argument(
420
+ "--baseline",
421
+ metavar="FILE",
422
+ help="Path to baseline file containing suppressed finding fingerprints.",
423
+ )
424
+ parser.add_argument(
425
+ "--create-baseline",
426
+ action="store_true",
427
+ help="Generate a baseline file from scan findings and exit with code 0.",
428
+ )
429
+ parser.add_argument(
430
+ "--config",
431
+ metavar="FILE",
432
+ help="Path to project configuration file (.sentinel.yaml or .sentinel.toml).",
433
+ )
434
+ parser.add_argument(
435
+ "--no-color",
436
+ action="store_true",
437
+ help="Disable ANSI color codes in console output.",
438
+ )
439
+ parser.add_argument(
440
+ "--color",
441
+ action="store_true",
442
+ help="Force ANSI color codes in console output.",
443
+ )
444
+ parser.add_argument(
445
+ "--verbose",
446
+ "-v",
447
+ action="store_true",
448
+ help="Enable verbose diagnostic output.",
449
+ )
450
+ parser.add_argument(
451
+ "--quiet",
452
+ "-q",
453
+ action="store_true",
454
+ help="Suppress banner and clean scan output; print nothing on clean scans.",
455
+ )
456
+
457
+ ai_group = parser.add_argument_group("AI Security Review Options")
458
+ ai_group.add_argument(
459
+ "--ai",
460
+ action="store_true",
461
+ help="Run contextual AI review on findings using local Gemma (Ollama) or configured cloud provider.",
462
+ )
463
+ ai_group.add_argument(
464
+ "--provider",
465
+ choices=["auto", "ollama", "gemini", "openai", "groq"],
466
+ default=None,
467
+ help="AI provider override. Default: .sentinel.yaml ai.provider, then SENTINEL_AI_PROVIDER, then auto-detect (Gemini/Groq/OpenAI keys, else Ollama).",
468
+ )
469
+ ai_group.add_argument(
470
+ "--model",
471
+ metavar="MODEL_NAME",
472
+ help="AI model name override (default: gemma3:4b for Ollama, gemma-4-26b-a4b-it for Google AI Studio).",
473
+ )
474
+ ai_group.add_argument(
475
+ "--ai-endpoint",
476
+ metavar="URL",
477
+ help="Custom API endpoint URL for AI inference.",
478
+ )
479
+ ai_group.add_argument(
480
+ "--allow-remote",
481
+ action="store_true",
482
+ help="Permit non-loopback endpoints for Ollama (disabled by default for privacy).",
483
+ )
484
+ ai_group.add_argument(
485
+ "--ai-timeout",
486
+ type=int,
487
+ default=120,
488
+ metavar="SECONDS",
489
+ help="HTTP request timeout for AI inference in seconds (default: 120).",
490
+ )
491
+ ai_group.add_argument(
492
+ "--fix",
493
+ action="store_true",
494
+ help="Generate and display suggested remediation diffs without auto-applying to files on disk (used with --ai).",
495
+ )
496
+ ai_group.add_argument(
497
+ "--cost-estimate",
498
+ action="store_true",
499
+ help="Display token count estimation and estimated query cost banner for AI review (used with --ai).",
500
+ )
501
+
502
+ return parser
503
+
504
+
505
+ def main(argv: Optional[List[str]] = None, prog: Optional[str] = None) -> int:
506
+ parser = build_arg_parser(prog=prog)
507
+ args = parser.parse_args(argv)
508
+
509
+ repo_path = Path(args.repo_root).resolve()
510
+
511
+ if args.version:
512
+ print(f"git-security-sentinel {VERSION}")
513
+ if not args.no_update_check:
514
+ try:
515
+ latest = check_for_pypi_update(VERSION, no_check=False, index_url=args.index_url)
516
+ if latest:
517
+ print(f"Update available: {VERSION} -> {latest} (run 'git scan --update')")
518
+ except Exception:
519
+ pass
520
+ return 0
521
+
522
+ if args.explain:
523
+ return explain_rule(args.explain, json_mode=(args.format == "json"))
524
+
525
+ if args.completion:
526
+ print(generate_completion(parser, args.completion, prog or "git-scan"))
527
+ return 0
528
+
529
+ if args.init:
530
+ messages: List[str] = []
531
+ if args.key:
532
+ env_path = repo_path / ".env"
533
+ existing_lines = (
534
+ env_path.read_text(encoding="utf-8", errors="replace").splitlines()
535
+ if env_path.is_file() else []
536
+ )
537
+ new_keys: Dict[str, str] = {}
538
+ for item in args.key:
539
+ if "=" not in item:
540
+ sys.stderr.write(f"Invalid --key format: {item} (expected NAME=VALUE)\n")
541
+ return 2
542
+ name, value = item.split("=", 1)
543
+ name, value = name.strip(), value.strip()
544
+ if name and value:
545
+ new_keys[name] = value
546
+ kept = [
547
+ line for line in existing_lines
548
+ if not any(line.strip().startswith(f"{name}=") for name in new_keys)
549
+ ]
550
+ kept.extend(f"{name}={value}" for name, value in new_keys.items())
551
+ try:
552
+ env_path.write_text("\n".join(kept) + "\n", encoding="utf-8")
553
+ messages.append("[ok] wrote local .env (gitignored)")
554
+ except Exception as e:
555
+ sys.stderr.write(f"Failed to write .env: {e}\n")
556
+ return 1
557
+ ok, init_messages = bootstrap_project(repo_path, force=args.force)
558
+ for line in messages:
559
+ print(line)
560
+ print("\n".join(init_messages))
561
+ return 0 if ok else 1
562
+
563
+ if args.install_hook:
564
+ success, msg = install_pre_commit_hook(repo_root=repo_path, force=args.force)
565
+ if success:
566
+ print(f"[OK] {msg}")
567
+ return 0
568
+ else:
569
+ sys.stderr.write(f"[ERROR] {msg}\n")
570
+ return 1
571
+
572
+ if args.upgrade or args.update:
573
+ return run_self_upgrade(index_url=args.index_url)
574
+
575
+ # Load configuration (.sentinel.yaml / .sentinel.toml)
576
+ config_data: Dict[str, Any] = {}
577
+ if args.config:
578
+ cfg_file = Path(args.config)
579
+ if not cfg_file.is_absolute():
580
+ cfg_file = repo_path / cfg_file
581
+ if not cfg_file.is_file():
582
+ sys.stderr.write(f"Configuration file not found: {args.config}\n")
583
+ return 2
584
+ try:
585
+ config_data = load_config(repo_path, config_path=cfg_file)
586
+ except Exception as e:
587
+ sys.stderr.write(f"Failed to load configuration file '{args.config}': {e}\n")
588
+ return 2
589
+ else:
590
+ try:
591
+ config_data = load_config(repo_path)
592
+ except Exception:
593
+ config_data = {}
594
+
595
+ # Configuration precedence: CLI args > Config file > Defaults
596
+ # 1. Severity threshold
597
+ if args.severity_threshold:
598
+ threshold = args.severity_threshold
599
+ elif "severity_threshold" in config_data:
600
+ threshold = str(config_data["severity_threshold"]).lower()
601
+ else:
602
+ threshold = "high"
603
+
604
+ # 2. Exclude patterns
605
+ exclude_patterns: List[str] = []
606
+ cfg_excludes = config_data.get("exclude", [])
607
+ if isinstance(cfg_excludes, list):
608
+ exclude_patterns.extend(cfg_excludes)
609
+
610
+ if args.exclude:
611
+ for item in args.exclude:
612
+ for part in item.split(","):
613
+ p_str = part.strip()
614
+ if p_str:
615
+ exclude_patterns.append(p_str)
616
+
617
+ sentinelignore_patterns = load_sentinelignore(repo_path)
618
+ exclude_patterns.extend(sentinelignore_patterns)
619
+
620
+ path_filter = PathFilter(exclude_patterns) if exclude_patterns else None
621
+
622
+ # 3. Baseline filter
623
+ baseline_path_str = args.baseline or config_data.get("baseline")
624
+ baseline_file: Optional[Path] = None
625
+ baseline_filter: Optional[BaselineFilter] = None
626
+ if baseline_path_str:
627
+ baseline_file = Path(baseline_path_str)
628
+ if not baseline_file.is_absolute():
629
+ baseline_file = repo_path / baseline_file
630
+ baseline_filter = BaselineFilter(baseline_file)
631
+
632
+ # 4. Color formatting
633
+ if args.no_color:
634
+ color_enabled = False
635
+ elif args.color:
636
+ color_enabled = True
637
+ elif "no_color" in config_data and config_data["no_color"]:
638
+ color_enabled = False
639
+ elif "color" in config_data and config_data["color"]:
640
+ color_enabled = True
641
+ elif os.environ.get("NO_COLOR"):
642
+ color_enabled = False
643
+ else:
644
+ color_enabled = sys.stdout.isatty()
645
+
646
+ # 5. Quiet and Verbose
647
+ is_quiet = args.quiet or bool(config_data.get("quiet", False))
648
+ is_verbose = args.verbose or bool(config_data.get("verbose", False))
649
+
650
+ # 6. Disabled rules
651
+ rules_cfg = config_data.get("rules", {})
652
+ disabled_ids = set()
653
+ if isinstance(rules_cfg, dict):
654
+ dis_list = rules_cfg.get("disable", [])
655
+ if isinstance(dis_list, list):
656
+ disabled_ids = set(dis_list)
657
+
658
+ all_rules = get_all_rules()
659
+ active_rules = [r for r in all_rules if r.rule_id not in disabled_ids]
660
+
661
+ scanner = GitSecurityScanner(
662
+ repo_root=repo_path,
663
+ rules=active_rules,
664
+ path_filter=path_filter,
665
+ baseline_filter=baseline_filter,
666
+ )
667
+
668
+ # Determine scan mode and diff content
669
+ diff_content = ""
670
+ scan_mode = "all"
671
+ auto_diff: Optional[str] = None
672
+ errors: List[str] = []
673
+
674
+ if args.diff_file:
675
+ scan_mode = "file"
676
+ if args.diff_file == "-":
677
+ try:
678
+ diff_content = sys.stdin.read()
679
+ except Exception as e:
680
+ errors.append(f"Failed to read diff from stdin: {e}")
681
+ else:
682
+ diff_path = Path(args.diff_file)
683
+ if not diff_path.is_file():
684
+ errors.append(f"Diff file not found: {args.diff_file}")
685
+ else:
686
+ try:
687
+ diff_content = diff_path.read_text(encoding="utf-8", errors="replace")
688
+ except Exception as e:
689
+ errors.append(f"Failed to read diff file '{args.diff_file}': {e}")
690
+ else:
691
+ is_git, git_err = scanner.check_is_git_repository()
692
+ if not is_git:
693
+ report = {
694
+ "scanner": SCANNER_NAME,
695
+ "version": VERSION,
696
+ "status": "failed",
697
+ "scan_mode": "unknown",
698
+ "findings": [],
699
+ "license": {"root_license_present": False, "license_file": None},
700
+ "summary": {"total": 0, "critical": 0, "high": 0, "medium": 0, "low": 0, "suppressed": 0},
701
+ "errors": [git_err or "Directory is not a valid Git repository."],
702
+ }
703
+ if args.format == "sarif":
704
+ sarif_data = generate_sarif_report(report, active_rules)
705
+ sarif_json = json.dumps(sarif_data, indent=2)
706
+ print(sarif_json)
707
+ if args.output:
708
+ Path(args.output).write_text(sarif_json, encoding="utf-8")
709
+ elif args.format == "json":
710
+ print(json.dumps(report, indent=2))
711
+ if args.output:
712
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
713
+ elif args.format == "github":
714
+ print(format_github_report(report))
715
+ elif not is_quiet:
716
+ print(format_text_report(report, color=color_enabled, verbose=is_verbose))
717
+ if args.output:
718
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
719
+ return 2
720
+
721
+ if args.staged:
722
+ scan_mode = "staged"
723
+ elif args.unstaged:
724
+ scan_mode = "unstaged"
725
+ elif args.base:
726
+ scan_mode = f"base:{args.base}"
727
+ elif args.all:
728
+ scan_mode = "all"
729
+ else:
730
+ # Smart default: review staged work first when the developer has
731
+ # staged something, otherwise fall back to all uncommitted changes.
732
+ candidate, candidate_errors = scanner.get_diff("staged")
733
+ if candidate.strip() and not candidate_errors:
734
+ scan_mode = "staged"
735
+ auto_diff = candidate
736
+ errors.extend(candidate_errors)
737
+ else:
738
+ scan_mode = "all"
739
+
740
+ branch_arg = args.base if args.base else None
741
+ mode_key = "base" if args.base else scan_mode
742
+ if auto_diff is None:
743
+ diff_content, git_errors = scanner.get_diff(mode_key, base_branch=branch_arg)
744
+ errors.extend(git_errors)
745
+ else:
746
+ diff_content = auto_diff
747
+
748
+ if errors:
749
+ report = {
750
+ "scanner": SCANNER_NAME,
751
+ "version": VERSION,
752
+ "status": "failed",
753
+ "scan_mode": scan_mode,
754
+ "findings": [],
755
+ "license": scanner.check_license(),
756
+ "summary": {"total": 0, "critical": 0, "high": 0, "medium": 0, "low": 0, "suppressed": 0},
757
+ "errors": errors,
758
+ }
759
+ if args.format == "sarif":
760
+ sarif_data = generate_sarif_report(report, active_rules)
761
+ sarif_json = json.dumps(sarif_data, indent=2)
762
+ print(sarif_json)
763
+ if args.output:
764
+ Path(args.output).write_text(sarif_json, encoding="utf-8")
765
+ elif args.format == "json":
766
+ print(json.dumps(report, indent=2))
767
+ if args.output:
768
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
769
+ elif args.format == "github":
770
+ print(format_github_report(report))
771
+ elif not is_quiet:
772
+ print(format_text_report(report, color=color_enabled, verbose=is_verbose))
773
+ if args.output:
774
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
775
+ return 2
776
+
777
+ # Baseline creation flag
778
+ if args.create_baseline:
779
+ target_baseline = baseline_file or (repo_path / ".sentinel.baseline")
780
+ # Run report without baseline filter to collect all detected findings
781
+ scan_rep = scanner.scan_diff_report(
782
+ diff_content,
783
+ scan_mode=scan_mode,
784
+ baseline_filter=None,
785
+ )
786
+ all_findings = scan_rep.findings + scan_rep.suppressed_findings
787
+ BaselineFilter.create_baseline(target_baseline, all_findings)
788
+ if not is_quiet:
789
+ print(f"Created baseline at {target_baseline} with {len(all_findings)} finding(s).")
790
+ return 0
791
+
792
+ scan_report = scanner.scan_diff_report(diff_content, scan_mode=scan_mode)
793
+ report = scan_report.to_dict()
794
+ ai_settings = resolve_ai_settings(args, config_data)
795
+
796
+ # AI Contextual Review
797
+ ai_text_output = ""
798
+ if args.ai and not errors:
799
+ findings_count = report.get("summary", {}).get("total", 0)
800
+ if findings_count == 0:
801
+ if args.format != "json":
802
+ ai_text_output = (
803
+ "====================================================================\n"
804
+ " GIT SECURITY SENTINEL - AI SECURITY REVIEW\n"
805
+ "====================================================================\n"
806
+ "Status: SKIPPED (Diff is clean - zero findings require remediation)\n"
807
+ "===================================================================="
808
+ )
809
+ else:
810
+ report["ai_review"] = {
811
+ "status": "skipped",
812
+ "reason": "Diff is clean; no findings to triage.",
813
+ }
814
+ else:
815
+ sanitized_diff = scanner.generate_sanitized_diff(diff_content)
816
+ try:
817
+ try:
818
+ from git_security_sentinel.ai_cli import run_ai_review
819
+ except ImportError:
820
+ try:
821
+ from scripts.ai_review import run_ai_review
822
+ except ImportError:
823
+ from ai_review import run_ai_review
824
+
825
+ success, ai_result, ai_formatted = run_ai_review(
826
+ report_data=report,
827
+ sanitized_diff=sanitized_diff,
828
+ provider=ai_settings["provider"],
829
+ model=ai_settings["model"],
830
+ endpoint=ai_settings["endpoint"],
831
+ allow_remote=ai_settings["allow_remote"],
832
+ timeout_sec=ai_settings["timeout"],
833
+ format_mode="json" if args.format == "json" else "text",
834
+ fix_mode=getattr(args, "fix", False),
835
+ cost_estimate=getattr(args, "cost_estimate", False),
836
+ )
837
+ if args.format == "json":
838
+ report["ai_review"] = ai_result
839
+ else:
840
+ ai_text_output = ai_formatted
841
+ except Exception as e:
842
+ err_msg = f"Failed to execute AI contextual reviewer: {e}"
843
+ if args.format == "json":
844
+ report["ai_review"] = {"status": "error", "error": err_msg}
845
+ else:
846
+ ai_text_output = (
847
+ "====================================================================\n"
848
+ " GIT SECURITY SENTINEL - AI REVIEWER ERROR\n"
849
+ "====================================================================\n"
850
+ f"{err_msg}\n"
851
+ "===================================================================="
852
+ )
853
+
854
+ # Output sanitized diff if requested
855
+ if args.redacted_diff_out:
856
+ out_patch_path = args.redacted_diff_out
857
+ sanitized = scanner.generate_sanitized_diff(diff_content)
858
+ try:
859
+ Path(out_patch_path).write_text(sanitized, encoding="utf-8")
860
+ except Exception as e:
861
+ report.setdefault("errors", []).append(f"Failed to write redacted diff: {e}")
862
+
863
+ # Generate SARIF structure if SARIF format requested or output path ends with .sarif
864
+ sarif_data = None
865
+ if args.format == "sarif" or (args.output and args.output.endswith(".sarif")):
866
+ sarif_data = generate_sarif_report(report, active_rules)
867
+
868
+ # Output report file if requested
869
+ if args.output:
870
+ try:
871
+ if args.format == "sarif" or args.output.endswith(".sarif"):
872
+ if sarif_data is None:
873
+ sarif_data = generate_sarif_report(report, active_rules)
874
+ Path(args.output).write_text(json.dumps(sarif_data, indent=2), encoding="utf-8")
875
+ else:
876
+ Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8")
877
+ except Exception as e:
878
+ report.setdefault("errors", []).append(f"Failed to write report output: {e}")
879
+
880
+ # Console output
881
+ if is_quiet:
882
+ if args.format == "sarif":
883
+ if sarif_data is None:
884
+ sarif_data = generate_sarif_report(report, active_rules)
885
+ print(json.dumps(sarif_data, indent=2))
886
+ elif args.format == "json":
887
+ print(json.dumps(report, indent=2))
888
+ elif args.format == "github":
889
+ print(format_github_report(report))
890
+ else:
891
+ findings_list = report.get("findings", [])
892
+ errors_list = report.get("errors", [])
893
+ # Clean scan prints nothing
894
+ if findings_list or errors_list:
895
+ for idx, f in enumerate(findings_list, start=1):
896
+ sev = f.get("severity", "UNKNOWN").upper()
897
+ print(f"[{idx}] [{sev}] {f.get('rule_id')} ({f.get('category')}) - {f.get('file')}:{f.get('line')}")
898
+ for err in errors_list:
899
+ sys.stderr.write(f"[!] {err}\n")
900
+ else:
901
+ if args.format == "sarif":
902
+ if sarif_data is None:
903
+ sarif_data = generate_sarif_report(report, active_rules)
904
+ print(json.dumps(sarif_data, indent=2))
905
+ elif args.format == "json":
906
+ print(json.dumps(report, indent=2))
907
+ elif args.format == "github":
908
+ print(format_github_report(report))
909
+ elif args.oneline:
910
+ print(format_oneline_report(report))
911
+ if ai_text_output:
912
+ print()
913
+ print(ai_text_output)
914
+ else:
915
+ print(format_text_report(report, color=color_enabled, verbose=is_verbose))
916
+ if ai_text_output:
917
+ print()
918
+ print(ai_text_output)
919
+
920
+ # PyPI background update check in non-quiet modes
921
+ if not is_quiet and not args.no_update_check and config_data.get("update_check", True) is not False:
922
+ try:
923
+ latest_ver = check_for_pypi_update(
924
+ VERSION,
925
+ no_check=args.no_update_check,
926
+ index_url=args.index_url,
927
+ )
928
+ if latest_ver:
929
+ print_update_banner(VERSION, latest_ver)
930
+ except Exception:
931
+ pass
932
+
933
+ return evaluate_exit_code(report, threshold)
934
+
935
+
936
+ if __name__ == "__main__":
937
+ sys.exit(main())