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,16 @@
1
+ """
2
+ Git Security Sentinel - Configuration Package.
3
+ Provides zero-dependency YAML and TOML configuration loaders.
4
+ """
5
+
6
+ from git_security_sentinel.config.loader import (
7
+ load_config,
8
+ parse_scalar,
9
+ parse_simple_yaml,
10
+ )
11
+
12
+ __all__ = [
13
+ "load_config",
14
+ "parse_scalar",
15
+ "parse_simple_yaml",
16
+ ]
@@ -0,0 +1,245 @@
1
+ """
2
+ Git Security Sentinel - Zero-Dependency Configuration Loader.
3
+ Parses .sentinel.yaml and .sentinel.toml strictly using the Python standard library.
4
+ Zero third-party dependencies (no PyYAML).
5
+ """
6
+
7
+ from pathlib import Path
8
+ import re
9
+ import sys
10
+ import textwrap
11
+ from typing import Any, Dict, List, Optional, Tuple
12
+
13
+
14
+ def _strip_inline_comment(line: str) -> str:
15
+ """Strips comments from line while preserving hash characters inside quotes."""
16
+ in_single = False
17
+ in_double = False
18
+ for i, c in enumerate(line):
19
+ if c == "'" and not in_double:
20
+ in_single = not in_single
21
+ elif c == '"' and not in_single:
22
+ in_double = not in_double
23
+ elif c == "#" and not in_single and not in_double:
24
+ if i == 0 or line[i - 1].isspace():
25
+ return line[:i].rstrip()
26
+ return line
27
+
28
+
29
+ def parse_scalar(val: str) -> Any:
30
+ """Parses a raw YAML scalar string into a Python typed value."""
31
+ v = val.strip()
32
+ if not v:
33
+ return None
34
+
35
+ lower = v.lower()
36
+ if lower in ("true", "yes", "on"):
37
+ return True
38
+ if lower in ("false", "no", "off"):
39
+ return False
40
+ if lower in ("null", "none", "~"):
41
+ return None
42
+
43
+ # Quoted string
44
+ if (v.startswith('"') and v.endswith('"')) or (v.startswith("'") and v.endswith("'")):
45
+ return v[1:-1]
46
+
47
+ # Inline list: [a, b, c]
48
+ if v.startswith("[") and v.endswith("]"):
49
+ inner = v[1:-1].strip()
50
+ if not inner:
51
+ return []
52
+ tokens = [t.strip() for t in inner.split(",") if t.strip()]
53
+ return [parse_scalar(t) for t in tokens]
54
+
55
+ # Numbers
56
+ try:
57
+ return int(v)
58
+ except ValueError:
59
+ pass
60
+ try:
61
+ return float(v)
62
+ except ValueError:
63
+ pass
64
+
65
+ return v
66
+
67
+
68
+ def parse_simple_yaml(text: str) -> Dict[str, Any]:
69
+ """
70
+ Pure Python standard library YAML parser supporting key-value pairs,
71
+ nested dictionaries (2-space indents), lists (- item), inline lists,
72
+ booleans, numbers, quoted strings, nulls, and comments.
73
+ """
74
+ if not text or not text.strip():
75
+ return {}
76
+
77
+ dedented = textwrap.dedent(text)
78
+ raw_lines = dedented.splitlines()
79
+
80
+ active_lines: List[Tuple[int, str]] = []
81
+ for raw in raw_lines:
82
+ stripped_comment = _strip_inline_comment(raw)
83
+ if not stripped_comment.strip():
84
+ continue
85
+ indent = len(stripped_comment) - len(stripped_comment.lstrip(" "))
86
+ content = stripped_comment.strip()
87
+ active_lines.append((indent, content))
88
+
89
+ if not active_lines:
90
+ return {}
91
+
92
+ def _parse_mapping(lines: List[Tuple[int, str]], start_idx: int, cur_indent: int) -> Tuple[Dict[str, Any], int]:
93
+ result: Dict[str, Any] = {}
94
+ i = start_idx
95
+ while i < len(lines):
96
+ indent, text = lines[i]
97
+ if indent < cur_indent:
98
+ break
99
+ if indent > cur_indent:
100
+ # Belonged to previous block; break out
101
+ break
102
+
103
+ if ":" not in text:
104
+ i += 1
105
+ continue
106
+
107
+ key_part, _, val_part = text.partition(":")
108
+ key = key_part.strip()
109
+ # Unquote key if quoted
110
+ if (key.startswith('"') and key.endswith('"')) or (key.startswith("'") and key.endswith("'")):
111
+ key = key[1:-1]
112
+ val = val_part.strip()
113
+ i += 1
114
+
115
+ if val:
116
+ result[key] = parse_scalar(val)
117
+ else:
118
+ # Check next line for nested block
119
+ if i < len(lines) and lines[i][0] > cur_indent:
120
+ child_indent = lines[i][0]
121
+ if lines[i][1].startswith("- "):
122
+ child_list, i = _parse_sequence(lines, i, child_indent)
123
+ result[key] = child_list
124
+ else:
125
+ child_dict, i = _parse_mapping(lines, i, child_indent)
126
+ result[key] = child_dict
127
+ else:
128
+ result[key] = None
129
+
130
+ return result, i
131
+
132
+ def _parse_sequence(lines: List[Tuple[int, str]], start_idx: int, cur_indent: int) -> Tuple[List[Any], int]:
133
+ result: List[Any] = []
134
+ i = start_idx
135
+ while i < len(lines):
136
+ indent, text = lines[i]
137
+ if indent < cur_indent:
138
+ break
139
+ if indent > cur_indent:
140
+ break
141
+
142
+ if not text.startswith("- "):
143
+ break
144
+
145
+ item_text = text[2:].strip()
146
+ i += 1
147
+
148
+ if not item_text:
149
+ if i < len(lines) and lines[i][0] > cur_indent:
150
+ child_indent = lines[i][0]
151
+ if lines[i][1].startswith("- "):
152
+ child_list, i = _parse_sequence(lines, i, child_indent)
153
+ result.append(child_list)
154
+ else:
155
+ child_dict, i = _parse_mapping(lines, i, child_indent)
156
+ result.append(child_dict)
157
+ else:
158
+ result.append(None)
159
+ else:
160
+ if ":" in item_text and not (item_text.startswith('"') or item_text.startswith("'")):
161
+ k, _, v = item_text.partition(":")
162
+ k = k.strip()
163
+ v = v.strip()
164
+ sub_map: Dict[str, Any] = {k: parse_scalar(v) if v else None}
165
+ if i < len(lines) and lines[i][0] > cur_indent and not lines[i][1].startswith("- "):
166
+ extra_map, i = _parse_mapping(lines, i, lines[i][0])
167
+ sub_map.update(extra_map)
168
+ result.append(sub_map)
169
+ else:
170
+ result.append(parse_scalar(item_text))
171
+
172
+ return result, i
173
+
174
+ # Top-level parsing
175
+ if active_lines[0][1].startswith("- "):
176
+ parsed_res, _ = _parse_sequence(active_lines, 0, active_lines[0][0])
177
+ return {"items": parsed_res}
178
+ else:
179
+ parsed_map, _ = _parse_mapping(active_lines, 0, active_lines[0][0])
180
+ return parsed_map
181
+
182
+
183
+ def _parse_simple_toml(text: str) -> Dict[str, Any]:
184
+ """Lightweight fallback TOML parser for simple key-value and tables."""
185
+ root: Dict[str, Any] = {}
186
+ current_section: Dict[str, Any] = root
187
+
188
+ for raw_line in text.splitlines():
189
+ line = _strip_inline_comment(raw_line).strip()
190
+ if not line:
191
+ continue
192
+ if line.startswith("[") and line.endswith("]"):
193
+ sec_name = line[1:-1].strip()
194
+ parts = [p.strip() for p in sec_name.split(".")]
195
+ curr = root
196
+ for p in parts:
197
+ if p not in curr or not isinstance(curr[p], dict):
198
+ curr[p] = {}
199
+ curr = curr[p]
200
+ current_section = curr
201
+ elif "=" in line:
202
+ key, _, val = line.partition("=")
203
+ key = key.strip()
204
+ val = val.strip()
205
+ current_section[key] = parse_scalar(val)
206
+
207
+ return root
208
+
209
+
210
+ def load_config(repo_root: Path, config_path: Optional[Path] = None) -> Dict[str, Any]:
211
+ """
212
+ Finds and parses project configuration (.sentinel.yaml, .sentinel.yml, or .sentinel.toml).
213
+ Uses stdlib only.
214
+ """
215
+ root = Path(repo_root)
216
+
217
+ if config_path:
218
+ target = Path(config_path)
219
+ if not target.is_absolute():
220
+ target = root / target
221
+ if not target.is_file():
222
+ raise FileNotFoundError(f"Configuration file not found: {config_path}")
223
+ else:
224
+ candidates = [
225
+ root / ".sentinel.yaml",
226
+ root / ".sentinel.yml",
227
+ root / ".sentinel.toml",
228
+ ]
229
+ target = next((c for c in candidates if c.is_file()), None)
230
+
231
+ if not target:
232
+ return {}
233
+
234
+ try:
235
+ content = target.read_text(encoding="utf-8", errors="replace")
236
+ except Exception as e:
237
+ raise RuntimeError(f"Failed to read configuration file '{target}': {e}")
238
+
239
+ if target.suffix == ".toml":
240
+ if sys.version_info >= (3, 11):
241
+ import tomllib
242
+ return tomllib.loads(content)
243
+ return _parse_simple_toml(content)
244
+
245
+ return parse_simple_yaml(content)
@@ -0,0 +1,42 @@
1
+ """
2
+ Git Security Sentinel - Core Module.
3
+ Exposes data models, unified diff parser, and git scanner.
4
+ """
5
+
6
+ from git_security_sentinel.core.models import (
7
+ ACCEPTED_LICENSE_NAMES,
8
+ Finding,
9
+ LicenseStatus,
10
+ Rule,
11
+ SCANNER_NAME,
12
+ ScanReport,
13
+ ScanSummary,
14
+ SEVERITY_ORDER,
15
+ VERSION,
16
+ )
17
+ from git_security_sentinel.core.diff_parser import UnifiedDiffParser
18
+ from git_security_sentinel.core.scanner import (
19
+ DETECTION_RULES,
20
+ GitSecurityScanner,
21
+ IGNORE_PLACEHOLDERS,
22
+ is_benign_generic_value,
23
+ redact_text,
24
+ )
25
+
26
+ __all__ = [
27
+ "ACCEPTED_LICENSE_NAMES",
28
+ "DETECTION_RULES",
29
+ "Finding",
30
+ "GitSecurityScanner",
31
+ "IGNORE_PLACEHOLDERS",
32
+ "LicenseStatus",
33
+ "Rule",
34
+ "SCANNER_NAME",
35
+ "ScanReport",
36
+ "ScanSummary",
37
+ "SEVERITY_ORDER",
38
+ "UnifiedDiffParser",
39
+ "VERSION",
40
+ "is_benign_generic_value",
41
+ "redact_text",
42
+ ]
@@ -0,0 +1,93 @@
1
+ """
2
+ Git Security Sentinel - Unified Diff Parser.
3
+ Extracts added lines, target file paths, and accurate line numbers from git diffs.
4
+ """
5
+
6
+ import re
7
+ from typing import Any, Dict, List, Optional
8
+
9
+
10
+ class UnifiedDiffParser:
11
+ """
12
+ Parses unified diff output to extract added lines, their target filenames,
13
+ and accurate line numbers in the modified file.
14
+ """
15
+
16
+ @staticmethod
17
+ def parse(diff_content: str) -> List[Dict[str, Any]]:
18
+ """
19
+ Returns a list of added line objects:
20
+ [
21
+ {
22
+ "file": "path/to/file.py",
23
+ "line": 42,
24
+ "content": "new line content without leading '+'"
25
+ }
26
+ ]
27
+ """
28
+ added_lines: List[Dict[str, Any]] = []
29
+ current_file: Optional[str] = None
30
+ new_line_num: int = 0
31
+ in_hunk: bool = False
32
+
33
+ diff_file_pattern = re.compile(r"^diff --git a/(.*) b/(.*)$")
34
+ hunk_header_pattern = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
35
+
36
+ for raw_line in diff_content.splitlines():
37
+ # Check for new file diff header
38
+ diff_match = diff_file_pattern.match(raw_line)
39
+ if diff_match:
40
+ # b/ filename (spaces in filenames supported)
41
+ current_file = diff_match.group(2)
42
+ in_hunk = False
43
+ continue
44
+
45
+ if raw_line.startswith("+++ "):
46
+ # Handle newly created files where diff --git may be followed by +++ b/filename
47
+ plus_path = raw_line[4:].strip()
48
+ if plus_path == "/dev/null":
49
+ current_file = None # file deleted
50
+ elif plus_path.startswith("b/"):
51
+ current_file = plus_path[2:]
52
+ continue
53
+
54
+ if raw_line.startswith("--- "):
55
+ continue
56
+
57
+ # Check for binary files
58
+ if raw_line.startswith("Binary files "):
59
+ in_hunk = False
60
+ continue
61
+
62
+ # Check for hunk header
63
+ hunk_match = hunk_header_pattern.match(raw_line)
64
+ if hunk_match:
65
+ in_hunk = True
66
+ new_line_num = int(hunk_match.group(1))
67
+ continue
68
+
69
+ if not in_hunk or not current_file:
70
+ continue
71
+
72
+ # Process hunk content
73
+ if raw_line.startswith("+"):
74
+ # Added line
75
+ content = raw_line[1:]
76
+ added_lines.append(
77
+ {
78
+ "file": current_file,
79
+ "line": new_line_num,
80
+ "content": content,
81
+ }
82
+ )
83
+ new_line_num += 1
84
+ elif raw_line.startswith("-"):
85
+ # Removed line - ignore for security scanning added changes
86
+ pass
87
+ elif raw_line.startswith(" "):
88
+ # Context line
89
+ new_line_num += 1
90
+ elif raw_line.startswith("\"):
91
+ pass
92
+
93
+ return added_lines
@@ -0,0 +1,111 @@
1
+ """
2
+ Git Security Sentinel - Core Data Models and Constants.
3
+ """
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ import re
7
+ from typing import Any, Callable, Dict, List, Optional, Pattern
8
+
9
+ VERSION = "1.2.0"
10
+ SCANNER_NAME = "git-security-sentinel"
11
+
12
+ # Accepted root license filenames
13
+ ACCEPTED_LICENSE_NAMES = ["LICENSE", "LICENSE.md", "LICENSE.txt", "COPYING"]
14
+
15
+ # Severity ranking for exit-code threshold comparisons
16
+ SEVERITY_ORDER = {
17
+ "critical": 4,
18
+ "high": 3,
19
+ "medium": 2,
20
+ "low": 1,
21
+ "info": 0,
22
+ }
23
+
24
+
25
+ @dataclass
26
+ class Finding:
27
+ """Represents a single detected security or compliance finding."""
28
+
29
+ rule_id: str
30
+ category: str
31
+ severity: str
32
+ confidence: str
33
+ file: str
34
+ line: int
35
+ message: str
36
+ evidence: str
37
+ recommendation: str
38
+ suppressed: bool = False
39
+ suppression_reason: Optional[str] = None
40
+ fingerprint: Optional[str] = None
41
+
42
+ def to_dict(self) -> Dict[str, Any]:
43
+ return asdict(self)
44
+
45
+
46
+ @dataclass
47
+ class LicenseStatus:
48
+ """Represents the status of repository root license compliance."""
49
+
50
+ root_license_present: bool
51
+ license_file: Optional[str] = None
52
+
53
+ def to_dict(self) -> Dict[str, Any]:
54
+ return asdict(self)
55
+
56
+
57
+ @dataclass
58
+ class ScanSummary:
59
+ """Statistical summary of findings broken down by severity level."""
60
+
61
+ total: int = 0
62
+ critical: int = 0
63
+ high: int = 0
64
+ medium: int = 0
65
+ low: int = 0
66
+ suppressed: int = 0
67
+
68
+ def to_dict(self) -> Dict[str, int]:
69
+ return asdict(self)
70
+
71
+
72
+ @dataclass
73
+ class ScanReport:
74
+ """Complete structured security scan report."""
75
+
76
+ scanner: str = SCANNER_NAME
77
+ version: str = VERSION
78
+ status: str = "completed"
79
+ scan_mode: str = "all"
80
+ findings: List[Finding] = field(default_factory=list)
81
+ license: LicenseStatus = field(default_factory=lambda: LicenseStatus(False))
82
+ summary: ScanSummary = field(default_factory=ScanSummary)
83
+ errors: List[str] = field(default_factory=list)
84
+ suppressed_findings: List[Finding] = field(default_factory=list)
85
+
86
+ def to_dict(self) -> Dict[str, Any]:
87
+ return {
88
+ "scanner": self.scanner,
89
+ "version": self.version,
90
+ "status": self.status,
91
+ "scan_mode": self.scan_mode,
92
+ "findings": [f.to_dict() for f in self.findings],
93
+ "license": self.license.to_dict(),
94
+ "summary": self.summary.to_dict(),
95
+ "errors": self.errors,
96
+ "suppressed_findings": [f.to_dict() for f in self.suppressed_findings],
97
+ }
98
+
99
+
100
+ @dataclass
101
+ class Rule:
102
+ """Rule definition for secret and code pattern scanning."""
103
+
104
+ rule_id: str
105
+ category: str
106
+ severity: str
107
+ confidence: str
108
+ pattern: Pattern[str]
109
+ message: str
110
+ recommendation: str
111
+ validator: Optional[Callable[[re.Match, str], bool]] = None