diffguard-ai 0.1.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.
- diffguard/__init__.py +39 -0
- diffguard/__main__.py +4 -0
- diffguard/baselines/__init__.py +0 -0
- diffguard/baselines/manager.py +97 -0
- diffguard/cli/__init__.py +1 -0
- diffguard/cli/main.py +323 -0
- diffguard/core/__init__.py +0 -0
- diffguard/core/enums.py +103 -0
- diffguard/core/exceptions.py +57 -0
- diffguard/core/interfaces.py +20 -0
- diffguard/core/models.py +301 -0
- diffguard/engine/__init__.py +0 -0
- diffguard/engine/evaluator.py +42 -0
- diffguard/engine/orchestrator.py +74 -0
- diffguard/engine/registry.py +142 -0
- diffguard/engine/scanner.py +141 -0
- diffguard/git/__init__.py +0 -0
- diffguard/git/client.py +179 -0
- diffguard/git/diff_parser.py +298 -0
- diffguard/git/repository.py +174 -0
- diffguard/policies/__init__.py +0 -0
- diffguard/policies/loader.py +75 -0
- diffguard/policies/schema.py +292 -0
- diffguard/py.typed +0 -0
- diffguard/reporting/__init__.py +0 -0
- diffguard/reporting/json_report.py +104 -0
- diffguard/reporting/markdown_report.py +96 -0
- diffguard/reporting/text_report.py +43 -0
- diffguard/rules/__init__.py +0 -0
- diffguard/rules/base.py +248 -0
- diffguard/rules/configuration.py +98 -0
- diffguard/rules/dangerous_patterns.py +290 -0
- diffguard/rules/dependencies.py +375 -0
- diffguard/rules/filetypes.py +49 -0
- diffguard/rules/scope.py +108 -0
- diffguard/rules/secret_patterns.py +195 -0
- diffguard/rules/secrets.py +118 -0
- diffguard/rules/test_removal.py +253 -0
- diffguard/suppressions/__init__.py +0 -0
- diffguard/suppressions/manager.py +81 -0
- diffguard/utils/__init__.py +0 -0
- diffguard/utils/logging.py +23 -0
- diffguard/utils/paths.py +131 -0
- diffguard/version.py +1 -0
- diffguard_ai-0.1.0.dist-info/METADATA +141 -0
- diffguard_ai-0.1.0.dist-info/RECORD +49 -0
- diffguard_ai-0.1.0.dist-info/WHEEL +4 -0
- diffguard_ai-0.1.0.dist-info/entry_points.txt +2 -0
- diffguard_ai-0.1.0.dist-info/licenses/LICENSE +202 -0
diffguard/core/models.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""Immutable domain models.
|
|
2
|
+
|
|
3
|
+
These types have no dependency on Git, YAML, the CLI, or any rule.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Iterator, Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
from os import PathLike
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from diffguard.core.enums import (
|
|
15
|
+
Category,
|
|
16
|
+
ChangeType,
|
|
17
|
+
Confidence,
|
|
18
|
+
Decision,
|
|
19
|
+
ExitCode,
|
|
20
|
+
FindingStatus,
|
|
21
|
+
LineKind,
|
|
22
|
+
ScanMode,
|
|
23
|
+
ScanStatus,
|
|
24
|
+
Severity,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# --------------------------------------------------------------------------- diff
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class ChangedLine:
|
|
32
|
+
kind: LineKind
|
|
33
|
+
content: str
|
|
34
|
+
old_lineno: int | None
|
|
35
|
+
new_lineno: int | None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class DiffHunk:
|
|
40
|
+
old_start: int
|
|
41
|
+
old_count: int
|
|
42
|
+
new_start: int
|
|
43
|
+
new_count: int
|
|
44
|
+
section: str
|
|
45
|
+
lines: tuple[ChangedLine, ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True)
|
|
49
|
+
class FileChange:
|
|
50
|
+
change_type: ChangeType
|
|
51
|
+
old_path: str | None
|
|
52
|
+
new_path: str | None
|
|
53
|
+
hunks: tuple[DiffHunk, ...] = ()
|
|
54
|
+
is_binary: bool = False
|
|
55
|
+
old_mode: str | None = None
|
|
56
|
+
new_mode: str | None = None
|
|
57
|
+
similarity: int | None = None
|
|
58
|
+
|
|
59
|
+
def __post_init__(self) -> None:
|
|
60
|
+
if self.old_path is None and self.new_path is None:
|
|
61
|
+
raise ValueError("a FileChange needs at least one path")
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def path(self) -> str:
|
|
65
|
+
"""The path after the change (or before it, for deletions)."""
|
|
66
|
+
path = self.new_path if self.new_path is not None else self.old_path
|
|
67
|
+
assert path is not None
|
|
68
|
+
return path
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def touched_paths(self) -> tuple[str, ...]:
|
|
72
|
+
"""Paths whose content is modified, created or removed by this change.
|
|
73
|
+
|
|
74
|
+
A rename touches both its source and destination; a copy only touches its
|
|
75
|
+
destination because the source is merely read.
|
|
76
|
+
"""
|
|
77
|
+
if (
|
|
78
|
+
self.change_type is ChangeType.RENAMED
|
|
79
|
+
and self.old_path is not None
|
|
80
|
+
and self.new_path is not None
|
|
81
|
+
and self.old_path != self.new_path
|
|
82
|
+
):
|
|
83
|
+
return (self.old_path, self.new_path)
|
|
84
|
+
return (self.path,)
|
|
85
|
+
|
|
86
|
+
def lines(self, kind: LineKind) -> Iterator[ChangedLine]:
|
|
87
|
+
for hunk in self.hunks:
|
|
88
|
+
for line in hunk.lines:
|
|
89
|
+
if line.kind is kind:
|
|
90
|
+
yield line
|
|
91
|
+
|
|
92
|
+
def added_lines(self) -> Iterator[ChangedLine]:
|
|
93
|
+
return self.lines(LineKind.ADDED)
|
|
94
|
+
|
|
95
|
+
def removed_lines(self) -> Iterator[ChangedLine]:
|
|
96
|
+
return self.lines(LineKind.REMOVED)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def added_count(self) -> int:
|
|
100
|
+
return sum(1 for _ in self.added_lines())
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def removed_count(self) -> int:
|
|
104
|
+
return sum(1 for _ in self.removed_lines())
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True, slots=True)
|
|
108
|
+
class DiffDocument:
|
|
109
|
+
files: tuple[FileChange, ...] = ()
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def lines_added(self) -> int:
|
|
113
|
+
return sum(f.added_count for f in self.files)
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def lines_removed(self) -> int:
|
|
117
|
+
return sum(f.removed_count for f in self.files)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ------------------------------------------------------------------------ findings
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True, slots=True)
|
|
124
|
+
class RuleMetadata:
|
|
125
|
+
"""Static description of a rule and the checks (finding IDs) it can emit."""
|
|
126
|
+
|
|
127
|
+
name: str
|
|
128
|
+
description: str
|
|
129
|
+
category: Category
|
|
130
|
+
default_severity: Severity
|
|
131
|
+
checks: Mapping[str, str]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass(frozen=True, slots=True)
|
|
135
|
+
class SuppressionInfo:
|
|
136
|
+
source: str # "policy" or "inline"
|
|
137
|
+
reason: str | None = None
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True, slots=True)
|
|
141
|
+
class Finding:
|
|
142
|
+
rule_id: str
|
|
143
|
+
rule_name: str
|
|
144
|
+
severity: Severity
|
|
145
|
+
category: Category
|
|
146
|
+
message: str
|
|
147
|
+
explanation: str
|
|
148
|
+
remediation: str
|
|
149
|
+
fingerprint: str
|
|
150
|
+
file_path: str | None = None
|
|
151
|
+
line: int | None = None
|
|
152
|
+
line_side: str = "new"
|
|
153
|
+
evidence: str | None = None
|
|
154
|
+
confidence: Confidence | None = None
|
|
155
|
+
status: FindingStatus = FindingStatus.ACTIVE
|
|
156
|
+
suppression: SuppressionInfo | None = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# -------------------------------------------------------------------------- policy
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@dataclass(frozen=True, slots=True)
|
|
163
|
+
class TaskContext:
|
|
164
|
+
id: str | None = None
|
|
165
|
+
description: str | None = None
|
|
166
|
+
allowed_paths: tuple[str, ...] = ()
|
|
167
|
+
protected_paths: tuple[str, ...] = ()
|
|
168
|
+
max_changed_lines: int | None = None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass(frozen=True, slots=True)
|
|
172
|
+
class RuleConfig:
|
|
173
|
+
enabled: bool = True
|
|
174
|
+
severity: Severity | None = None
|
|
175
|
+
options: Mapping[str, Any] = field(default_factory=dict)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True, slots=True)
|
|
179
|
+
class SuppressionRule:
|
|
180
|
+
rule: str
|
|
181
|
+
reason: str
|
|
182
|
+
path: str | None = None
|
|
183
|
+
fingerprint: str | None = None
|
|
184
|
+
expires: date | None = None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@dataclass(frozen=True, slots=True)
|
|
188
|
+
class Policy:
|
|
189
|
+
version: int = 1
|
|
190
|
+
task: TaskContext = field(default_factory=TaskContext)
|
|
191
|
+
rules: Mapping[str, RuleConfig] = field(default_factory=dict)
|
|
192
|
+
fail_on: frozenset[Severity] = frozenset({Severity.ERROR})
|
|
193
|
+
exclude_paths: tuple[str, ...] = ()
|
|
194
|
+
suppressions: tuple[SuppressionRule, ...] = ()
|
|
195
|
+
baseline_path: str | None = None
|
|
196
|
+
allow_inline_suppressions: bool = False
|
|
197
|
+
source_path: str | None = None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# --------------------------------------------------------------------------- scans
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass(frozen=True, slots=True)
|
|
204
|
+
class ScanRequest:
|
|
205
|
+
"""What to scan.
|
|
206
|
+
|
|
207
|
+
* default: working tree (staged + unstaged + untracked) against ``HEAD``
|
|
208
|
+
* ``staged=True``: the index against ``HEAD``
|
|
209
|
+
* ``base`` (+ optional ``head``, default ``HEAD``): merge-base of the two
|
|
210
|
+
revisions against ``head``
|
|
211
|
+
* ``diff_text``: an already-produced Git-style unified diff
|
|
212
|
+
"""
|
|
213
|
+
|
|
214
|
+
repository: str | PathLike[str] = "."
|
|
215
|
+
base: str | None = None
|
|
216
|
+
head: str | None = None
|
|
217
|
+
staged: bool = False
|
|
218
|
+
diff_text: str | None = None
|
|
219
|
+
include_untracked: bool = True
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True, slots=True)
|
|
223
|
+
class RepositoryInfo:
|
|
224
|
+
mode: ScanMode
|
|
225
|
+
root_name: str | None = None
|
|
226
|
+
head_commit: str | None = None
|
|
227
|
+
branch: str | None = None
|
|
228
|
+
base: str | None = None
|
|
229
|
+
head: str | None = None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@dataclass(frozen=True, slots=True)
|
|
233
|
+
class EnforcementDecision:
|
|
234
|
+
outcome: Decision
|
|
235
|
+
blocking_findings: int
|
|
236
|
+
fail_on: tuple[Severity, ...]
|
|
237
|
+
reason: str
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(frozen=True, slots=True)
|
|
241
|
+
class ExecutionError:
|
|
242
|
+
"""A rule (or stage) failed to run. Never silently treated as success."""
|
|
243
|
+
|
|
244
|
+
source: str
|
|
245
|
+
error_type: str
|
|
246
|
+
message: str
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@dataclass(frozen=True, slots=True)
|
|
250
|
+
class RuleSummary:
|
|
251
|
+
name: str
|
|
252
|
+
description: str
|
|
253
|
+
category: Category
|
|
254
|
+
enabled: bool
|
|
255
|
+
severity: Severity
|
|
256
|
+
checks: Mapping[str, str]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@dataclass(frozen=True, slots=True)
|
|
260
|
+
class ScanStats:
|
|
261
|
+
files_changed: int = 0
|
|
262
|
+
lines_added: int = 0
|
|
263
|
+
lines_removed: int = 0
|
|
264
|
+
files_excluded: int = 0
|
|
265
|
+
binary_files: int = 0
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
_EXIT_CODES: dict[Decision, ExitCode] = {
|
|
269
|
+
Decision.PASS: ExitCode.OK,
|
|
270
|
+
Decision.WARN: ExitCode.OK,
|
|
271
|
+
Decision.FAIL: ExitCode.POLICY_VIOLATION,
|
|
272
|
+
Decision.ERROR: ExitCode.INTERNAL_ERROR,
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@dataclass(frozen=True, slots=True)
|
|
277
|
+
class ScanResult:
|
|
278
|
+
scanner_version: str
|
|
279
|
+
timestamp: datetime
|
|
280
|
+
repository: RepositoryInfo
|
|
281
|
+
policy_version: int
|
|
282
|
+
policy_source: str | None
|
|
283
|
+
task_id: str | None
|
|
284
|
+
status: ScanStatus
|
|
285
|
+
decision: EnforcementDecision
|
|
286
|
+
stats: ScanStats
|
|
287
|
+
findings: tuple[Finding, ...]
|
|
288
|
+
rules: tuple[RuleSummary, ...]
|
|
289
|
+
execution_errors: tuple[ExecutionError, ...] = ()
|
|
290
|
+
warnings: tuple[str, ...] = ()
|
|
291
|
+
|
|
292
|
+
@property
|
|
293
|
+
def exit_code(self) -> ExitCode:
|
|
294
|
+
return _EXIT_CODES[self.decision.outcome]
|
|
295
|
+
|
|
296
|
+
def findings_with_status(self, status: FindingStatus) -> tuple[Finding, ...]:
|
|
297
|
+
return tuple(f for f in self.findings if f.status is status)
|
|
298
|
+
|
|
299
|
+
@property
|
|
300
|
+
def active_findings(self) -> tuple[Finding, ...]:
|
|
301
|
+
return self.findings_with_status(FindingStatus.ACTIVE)
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Enforcement decision logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Collection, Iterable
|
|
6
|
+
|
|
7
|
+
from diffguard.core.enums import Decision, FindingStatus, Severity
|
|
8
|
+
from diffguard.core.models import EnforcementDecision, ExecutionError, Finding
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def decide(
|
|
12
|
+
findings: Iterable[Finding],
|
|
13
|
+
fail_on: Collection[Severity],
|
|
14
|
+
errors: Collection[ExecutionError] = (),
|
|
15
|
+
) -> EnforcementDecision:
|
|
16
|
+
"""Compute the outcome.
|
|
17
|
+
|
|
18
|
+
* FAIL - an active finding has a severity listed in ``fail_on``.
|
|
19
|
+
* ERROR - no blocking finding, but a rule failed to run (scan incomplete).
|
|
20
|
+
An incomplete scan never reports success.
|
|
21
|
+
* WARN - active findings of warning/error severity that are not blocking.
|
|
22
|
+
* PASS - nothing actionable.
|
|
23
|
+
Suppressed and baselined findings never count.
|
|
24
|
+
"""
|
|
25
|
+
active = [f for f in findings if f.status is FindingStatus.ACTIVE]
|
|
26
|
+
fail_set = tuple(sorted(fail_on, key=lambda s: s.rank))
|
|
27
|
+
blocking = [f for f in active if f.severity in fail_on]
|
|
28
|
+
if blocking:
|
|
29
|
+
names = "/".join(s.value for s in fail_set)
|
|
30
|
+
return EnforcementDecision(
|
|
31
|
+
Decision.FAIL,
|
|
32
|
+
len(blocking),
|
|
33
|
+
fail_set,
|
|
34
|
+
f"{len(blocking)} blocking finding(s) at severity {names}",
|
|
35
|
+
)
|
|
36
|
+
if errors:
|
|
37
|
+
failed = ", ".join(sorted({e.source for e in errors}))
|
|
38
|
+
return EnforcementDecision(Decision.ERROR, 0, fail_set, f"scan incomplete: could not run {failed}")
|
|
39
|
+
notable = [f for f in active if f.severity.rank >= Severity.WARNING.rank]
|
|
40
|
+
if notable:
|
|
41
|
+
return EnforcementDecision(Decision.WARN, 0, fail_set, f"{len(notable)} non-blocking finding(s)")
|
|
42
|
+
return EnforcementDecision(Decision.PASS, 0, fail_set, "no actionable findings")
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Independently testable pipeline stages used by :class:`Scanner`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from diffguard.core.enums import LineKind
|
|
8
|
+
from diffguard.core.models import (
|
|
9
|
+
DiffDocument,
|
|
10
|
+
ExecutionError,
|
|
11
|
+
Finding,
|
|
12
|
+
ScanStats,
|
|
13
|
+
)
|
|
14
|
+
from diffguard.engine.registry import ResolvedRule
|
|
15
|
+
from diffguard.rules.base import RuleContext
|
|
16
|
+
from diffguard.utils.logging import get_logger
|
|
17
|
+
from diffguard.utils.paths import matches_any
|
|
18
|
+
|
|
19
|
+
log = get_logger("engine")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def filter_excluded(diff: DiffDocument, patterns: Sequence[str]) -> tuple[DiffDocument, int]:
|
|
23
|
+
"""Drop files whose every touched path matches an ``exclude_paths`` pattern."""
|
|
24
|
+
if not patterns:
|
|
25
|
+
return diff, 0
|
|
26
|
+
kept = tuple(f for f in diff.files if not all(matches_any(p, patterns) for p in f.touched_paths))
|
|
27
|
+
return DiffDocument(kept), len(diff.files) - len(kept)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def compute_stats(diff: DiffDocument, excluded: int) -> ScanStats:
|
|
31
|
+
return ScanStats(
|
|
32
|
+
files_changed=len(diff.files),
|
|
33
|
+
lines_added=diff.lines_added,
|
|
34
|
+
lines_removed=diff.lines_removed,
|
|
35
|
+
files_excluded=excluded,
|
|
36
|
+
binary_files=sum(1 for f in diff.files if f.is_binary),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def execute_rules(
|
|
41
|
+
rules: Sequence[ResolvedRule], ctx: RuleContext
|
|
42
|
+
) -> tuple[list[Finding], list[ExecutionError]]:
|
|
43
|
+
"""Run each rule in isolation. A crashing rule is recorded, never swallowed."""
|
|
44
|
+
findings: list[Finding] = []
|
|
45
|
+
errors: list[ExecutionError] = []
|
|
46
|
+
for resolved in rules:
|
|
47
|
+
name = resolved.rule.metadata.name
|
|
48
|
+
try:
|
|
49
|
+
findings.extend(resolved.rule.evaluate(ctx, resolved.settings))
|
|
50
|
+
except Exception as exc: # noqa: BLE001 - isolation boundary, recorded in the result
|
|
51
|
+
log.debug("rule %s failed", name, exc_info=True)
|
|
52
|
+
errors.append(ExecutionError(name, type(exc).__name__, str(exc)[:500]))
|
|
53
|
+
return findings, errors
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def dedupe_and_sort(findings: Sequence[Finding]) -> list[Finding]:
|
|
57
|
+
unique: dict[tuple[object, ...], Finding] = {}
|
|
58
|
+
for f in findings:
|
|
59
|
+
unique.setdefault((f.rule_id, f.file_path, f.line, f.line_side, f.fingerprint, f.message), f)
|
|
60
|
+
return sorted(
|
|
61
|
+
unique.values(),
|
|
62
|
+
key=lambda f: (f.file_path or "", f.line or 0, f.rule_id, f.fingerprint, f.message),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def inline_lookup(diff: DiffDocument) -> dict[tuple[str, int], str]:
|
|
67
|
+
"""Map ``(path, new_line_number)`` to the content of each added line."""
|
|
68
|
+
lookup: dict[tuple[str, int], str] = {}
|
|
69
|
+
for change in diff.files:
|
|
70
|
+
for hunk in change.hunks:
|
|
71
|
+
for line in hunk.lines:
|
|
72
|
+
if line.kind is LineKind.ADDED and line.new_lineno is not None:
|
|
73
|
+
lookup[(change.path, line.new_lineno)] = line.content
|
|
74
|
+
return lookup
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Rule registry and resolution of policy configuration into runnable rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Collection, Iterable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from importlib.metadata import entry_points
|
|
9
|
+
|
|
10
|
+
from diffguard.core.exceptions import PluginError, PolicyError, ScanInputError
|
|
11
|
+
from diffguard.core.models import Policy, RuleConfig, RuleSummary
|
|
12
|
+
from diffguard.rules.base import OptionsError, Rule, RuleSettings
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class ResolvedRule:
|
|
17
|
+
rule: Rule
|
|
18
|
+
settings: RuleSettings
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RuleRegistry:
|
|
22
|
+
def __init__(self, rules: Iterable[Rule] = ()) -> None:
|
|
23
|
+
self._rules: dict[str, Rule] = {}
|
|
24
|
+
for rule in rules:
|
|
25
|
+
self.register(rule)
|
|
26
|
+
|
|
27
|
+
def register(self, rule: Rule) -> None:
|
|
28
|
+
name = rule.metadata.name
|
|
29
|
+
if name in self._rules:
|
|
30
|
+
raise ValueError(f"rule {name!r} is already registered")
|
|
31
|
+
self._rules[name] = rule
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def rules(self) -> list[Rule]:
|
|
35
|
+
return list(self._rules.values())
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def names(self) -> frozenset[str]:
|
|
39
|
+
return frozenset(self._rules)
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def check_ids(self) -> frozenset[str]:
|
|
43
|
+
return frozenset(cid for r in self._rules.values() for cid in r.metadata.checks)
|
|
44
|
+
|
|
45
|
+
def get(self, name: str) -> Rule:
|
|
46
|
+
return self._rules[name]
|
|
47
|
+
|
|
48
|
+
def resolve(self, policy: Policy, only: Collection[str] | None = None) -> list[ResolvedRule]:
|
|
49
|
+
"""Validate every configured rule's options and return the enabled rules."""
|
|
50
|
+
if only is not None:
|
|
51
|
+
unknown = sorted(set(only) - self.names)
|
|
52
|
+
if unknown:
|
|
53
|
+
raise ScanInputError(
|
|
54
|
+
f"unknown rule(s): {', '.join(unknown)}; known: {', '.join(sorted(self.names))}"
|
|
55
|
+
)
|
|
56
|
+
errors: list[str] = []
|
|
57
|
+
resolved: list[ResolvedRule] = []
|
|
58
|
+
for name, rule in self._rules.items():
|
|
59
|
+
config = policy.rules.get(name, RuleConfig())
|
|
60
|
+
try:
|
|
61
|
+
options = rule.validate_options(config.options)
|
|
62
|
+
except OptionsError as exc:
|
|
63
|
+
errors.extend(f"rules.{name}.options: {e}" for e in exc.errors)
|
|
64
|
+
continue
|
|
65
|
+
if not config.enabled or (only is not None and name not in only):
|
|
66
|
+
continue
|
|
67
|
+
severity = config.severity or rule.metadata.default_severity
|
|
68
|
+
resolved.append(ResolvedRule(rule, RuleSettings(severity, options)))
|
|
69
|
+
if errors:
|
|
70
|
+
raise PolicyError(errors)
|
|
71
|
+
return resolved
|
|
72
|
+
|
|
73
|
+
def summaries(self, policy: Policy, only: Collection[str] | None = None) -> tuple[RuleSummary, ...]:
|
|
74
|
+
out: list[RuleSummary] = []
|
|
75
|
+
for name, rule in self._rules.items():
|
|
76
|
+
config = policy.rules.get(name, RuleConfig())
|
|
77
|
+
meta = rule.metadata
|
|
78
|
+
enabled = config.enabled and (only is None or name in only)
|
|
79
|
+
out.append(
|
|
80
|
+
RuleSummary(
|
|
81
|
+
name=name,
|
|
82
|
+
description=meta.description,
|
|
83
|
+
category=meta.category,
|
|
84
|
+
enabled=enabled,
|
|
85
|
+
severity=config.severity or meta.default_severity,
|
|
86
|
+
checks=dict(meta.checks),
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
return tuple(out)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
PLUGIN_ENTRY_POINT_GROUP = "diffguard.rules"
|
|
93
|
+
PLUGINS_DISABLED_ENV = "DIFFGUARD_NO_PLUGINS"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def load_plugins(registry: RuleRegistry) -> None:
|
|
97
|
+
"""Register rules from installed packages exposing the ``diffguard.rules`` entry-point group.
|
|
98
|
+
|
|
99
|
+
Each entry point must resolve to a :class:`Rule` subclass (instantiated with no arguments) or
|
|
100
|
+
a zero-argument callable returning a ``Rule``. Plugins run arbitrary code in-process: they are
|
|
101
|
+
only loaded from the Python environment (never from the scanned repository or the policy).
|
|
102
|
+
Any failure raises :class:`PluginError`; a broken plugin is never silently skipped.
|
|
103
|
+
"""
|
|
104
|
+
for ep in sorted(entry_points(group=PLUGIN_ENTRY_POINT_GROUP), key=lambda e: e.name):
|
|
105
|
+
try:
|
|
106
|
+
factory = ep.load()
|
|
107
|
+
rule = factory()
|
|
108
|
+
except Exception as exc: # noqa: BLE001 - third-party code
|
|
109
|
+
raise PluginError(f"plugin {ep.name!r} failed to load: {type(exc).__name__}: {exc}") from exc
|
|
110
|
+
if not isinstance(rule, Rule):
|
|
111
|
+
raise PluginError(f"plugin {ep.name!r} did not provide a diffguard Rule")
|
|
112
|
+
try:
|
|
113
|
+
registry.register(rule)
|
|
114
|
+
except ValueError as exc:
|
|
115
|
+
raise PluginError(f"plugin {ep.name!r}: {exc}") from exc
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def default_registry(*, plugins: bool | None = None) -> RuleRegistry:
|
|
119
|
+
"""Built-in rules plus installed plugins (disable with ``plugins=False`` or
|
|
120
|
+
the ``DIFFGUARD_NO_PLUGINS=1`` environment variable)."""
|
|
121
|
+
from diffguard.rules.configuration import ConfigurationRule
|
|
122
|
+
from diffguard.rules.dangerous_patterns import DangerousPatternsRule
|
|
123
|
+
from diffguard.rules.dependencies import DependenciesRule
|
|
124
|
+
from diffguard.rules.scope import ScopeRule
|
|
125
|
+
from diffguard.rules.secrets import SecretsRule
|
|
126
|
+
from diffguard.rules.test_removal import TestRemovalRule
|
|
127
|
+
|
|
128
|
+
registry = RuleRegistry(
|
|
129
|
+
[
|
|
130
|
+
ScopeRule(),
|
|
131
|
+
SecretsRule(),
|
|
132
|
+
DangerousPatternsRule(),
|
|
133
|
+
DependenciesRule(),
|
|
134
|
+
TestRemovalRule(),
|
|
135
|
+
ConfigurationRule(),
|
|
136
|
+
]
|
|
137
|
+
)
|
|
138
|
+
if plugins is None:
|
|
139
|
+
plugins = os.environ.get(PLUGINS_DISABLED_ENV, "").lower() not in ("1", "true", "yes")
|
|
140
|
+
if plugins:
|
|
141
|
+
load_plugins(registry)
|
|
142
|
+
return registry
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Public scanner facade: runs the scan lifecycle."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Callable, Collection
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from diffguard.baselines.manager import Baseline, apply_baseline, load_baseline
|
|
11
|
+
from diffguard.core.enums import ScanStatus
|
|
12
|
+
from diffguard.core.exceptions import PolicyError
|
|
13
|
+
from diffguard.core.models import Policy, ScanRequest, ScanResult
|
|
14
|
+
from diffguard.engine import orchestrator
|
|
15
|
+
from diffguard.engine.evaluator import decide
|
|
16
|
+
from diffguard.engine.registry import ResolvedRule, RuleRegistry, default_registry
|
|
17
|
+
from diffguard.git.client import GitClient
|
|
18
|
+
from diffguard.git.diff_parser import parse_diff
|
|
19
|
+
from diffguard.git.repository import resolve_diff
|
|
20
|
+
from diffguard.policies.loader import DEFAULT_POLICY_FILENAME, load_policy
|
|
21
|
+
from diffguard.rules.base import RuleContext
|
|
22
|
+
from diffguard.suppressions.manager import apply_suppressions
|
|
23
|
+
from diffguard.utils.logging import get_logger
|
|
24
|
+
from diffguard.utils.paths import relative_posix
|
|
25
|
+
from diffguard.version import __version__
|
|
26
|
+
|
|
27
|
+
log = get_logger("scanner")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Scanner:
|
|
31
|
+
"""Runs scans for a validated :class:`Policy`.
|
|
32
|
+
|
|
33
|
+
Lifecycle of :meth:`scan`: validate request -> resolve repository and diff ->
|
|
34
|
+
parse -> normalize/exclude paths -> build context -> run rules -> aggregate ->
|
|
35
|
+
suppressions -> baseline -> decision -> result. Policy loading and rule option
|
|
36
|
+
validation happen at construction, so a ``Scanner`` is always valid.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
policy: Policy,
|
|
42
|
+
*,
|
|
43
|
+
registry: RuleRegistry | None = None,
|
|
44
|
+
git_client: GitClient | None = None,
|
|
45
|
+
baseline: Baseline | None = None,
|
|
46
|
+
only_rules: Collection[str] | None = None,
|
|
47
|
+
warnings: Collection[str] = (),
|
|
48
|
+
clock: Callable[[], datetime] | None = None,
|
|
49
|
+
) -> None:
|
|
50
|
+
self._policy = policy
|
|
51
|
+
self._registry = registry or default_registry()
|
|
52
|
+
self._git = git_client or GitClient()
|
|
53
|
+
self._only = frozenset(only_rules) if only_rules is not None else None
|
|
54
|
+
self._rules: list[ResolvedRule] = self._registry.resolve(policy, self._only)
|
|
55
|
+
self._summaries = self._registry.summaries(policy, self._only)
|
|
56
|
+
self._warnings = tuple(warnings)
|
|
57
|
+
self._clock = clock or (lambda: datetime.now(UTC))
|
|
58
|
+
self._baseline_file: Path | None = None
|
|
59
|
+
if baseline is None and policy.baseline_path:
|
|
60
|
+
base_dir = Path(policy.source_path).resolve().parent if policy.source_path else Path.cwd()
|
|
61
|
+
self._baseline_file = base_dir / policy.baseline_path
|
|
62
|
+
baseline = load_baseline(self._baseline_file)
|
|
63
|
+
self._baseline = baseline
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_policy(cls, policy: Policy | None = None, **kwargs: object) -> Scanner:
|
|
67
|
+
return cls(policy or Policy(), **kwargs) # type: ignore[arg-type]
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def from_config(
|
|
71
|
+
cls,
|
|
72
|
+
path: str | os.PathLike[str] | None = DEFAULT_POLICY_FILENAME,
|
|
73
|
+
*,
|
|
74
|
+
registry: RuleRegistry | None = None,
|
|
75
|
+
**kwargs: object,
|
|
76
|
+
) -> Scanner:
|
|
77
|
+
"""Load ``path`` (``None`` means built-in defaults) and build a scanner."""
|
|
78
|
+
reg = registry or default_registry()
|
|
79
|
+
if path is None:
|
|
80
|
+
return cls(Policy(), registry=reg, **kwargs) # type: ignore[arg-type]
|
|
81
|
+
policy = load_policy(path, rule_names=reg.names, check_ids=reg.check_ids)
|
|
82
|
+
return cls(policy, registry=reg, **kwargs) # type: ignore[arg-type]
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def policy(self) -> Policy:
|
|
86
|
+
return self._policy
|
|
87
|
+
|
|
88
|
+
def _protected_files(self, root: Path) -> frozenset[str]:
|
|
89
|
+
files: set[str] = set()
|
|
90
|
+
for candidate in (self._policy.source_path, self._baseline_file):
|
|
91
|
+
if candidate:
|
|
92
|
+
rel = relative_posix(Path(candidate), root)
|
|
93
|
+
if rel:
|
|
94
|
+
files.add(rel)
|
|
95
|
+
return frozenset(files)
|
|
96
|
+
|
|
97
|
+
def scan(self, request: ScanRequest) -> ScanResult:
|
|
98
|
+
policy = self._policy
|
|
99
|
+
resolved = resolve_diff(request, self._git)
|
|
100
|
+
diff = parse_diff(resolved.text)
|
|
101
|
+
diff, excluded = orchestrator.filter_excluded(diff, policy.exclude_paths)
|
|
102
|
+
ctx = RuleContext(
|
|
103
|
+
diff=diff,
|
|
104
|
+
task=policy.task,
|
|
105
|
+
policy=policy,
|
|
106
|
+
reader=resolved.reader,
|
|
107
|
+
protected_files=self._protected_files(resolved.root),
|
|
108
|
+
)
|
|
109
|
+
findings, errors = orchestrator.execute_rules(self._rules, ctx)
|
|
110
|
+
findings = orchestrator.dedupe_and_sort(findings)
|
|
111
|
+
|
|
112
|
+
now = self._clock()
|
|
113
|
+
warnings = [*self._warnings, *resolved.warnings]
|
|
114
|
+
lookup = orchestrator.inline_lookup(diff) if policy.allow_inline_suppressions else None
|
|
115
|
+
findings, suppression_warnings = apply_suppressions(
|
|
116
|
+
findings, policy.suppressions, today=now.date(), inline_lookup=lookup
|
|
117
|
+
)
|
|
118
|
+
warnings.extend(suppression_warnings)
|
|
119
|
+
findings = apply_baseline(findings, self._baseline)
|
|
120
|
+
if not diff.files and not excluded:
|
|
121
|
+
warnings.append("the diff contains no changes")
|
|
122
|
+
|
|
123
|
+
decision = decide(findings, policy.fail_on, errors)
|
|
124
|
+
return ScanResult(
|
|
125
|
+
scanner_version=__version__,
|
|
126
|
+
timestamp=now,
|
|
127
|
+
repository=resolved.info,
|
|
128
|
+
policy_version=policy.version,
|
|
129
|
+
policy_source=policy.source_path,
|
|
130
|
+
task_id=policy.task.id,
|
|
131
|
+
status=ScanStatus.INCOMPLETE if errors else ScanStatus.COMPLETE,
|
|
132
|
+
decision=decision,
|
|
133
|
+
stats=orchestrator.compute_stats(diff, excluded),
|
|
134
|
+
findings=tuple(findings),
|
|
135
|
+
rules=self._summaries,
|
|
136
|
+
execution_errors=tuple(errors),
|
|
137
|
+
warnings=tuple(warnings),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
__all__ = ["PolicyError", "Scanner"]
|
|
File without changes
|