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.
Files changed (49) hide show
  1. diffguard/__init__.py +39 -0
  2. diffguard/__main__.py +4 -0
  3. diffguard/baselines/__init__.py +0 -0
  4. diffguard/baselines/manager.py +97 -0
  5. diffguard/cli/__init__.py +1 -0
  6. diffguard/cli/main.py +323 -0
  7. diffguard/core/__init__.py +0 -0
  8. diffguard/core/enums.py +103 -0
  9. diffguard/core/exceptions.py +57 -0
  10. diffguard/core/interfaces.py +20 -0
  11. diffguard/core/models.py +301 -0
  12. diffguard/engine/__init__.py +0 -0
  13. diffguard/engine/evaluator.py +42 -0
  14. diffguard/engine/orchestrator.py +74 -0
  15. diffguard/engine/registry.py +142 -0
  16. diffguard/engine/scanner.py +141 -0
  17. diffguard/git/__init__.py +0 -0
  18. diffguard/git/client.py +179 -0
  19. diffguard/git/diff_parser.py +298 -0
  20. diffguard/git/repository.py +174 -0
  21. diffguard/policies/__init__.py +0 -0
  22. diffguard/policies/loader.py +75 -0
  23. diffguard/policies/schema.py +292 -0
  24. diffguard/py.typed +0 -0
  25. diffguard/reporting/__init__.py +0 -0
  26. diffguard/reporting/json_report.py +104 -0
  27. diffguard/reporting/markdown_report.py +96 -0
  28. diffguard/reporting/text_report.py +43 -0
  29. diffguard/rules/__init__.py +0 -0
  30. diffguard/rules/base.py +248 -0
  31. diffguard/rules/configuration.py +98 -0
  32. diffguard/rules/dangerous_patterns.py +290 -0
  33. diffguard/rules/dependencies.py +375 -0
  34. diffguard/rules/filetypes.py +49 -0
  35. diffguard/rules/scope.py +108 -0
  36. diffguard/rules/secret_patterns.py +195 -0
  37. diffguard/rules/secrets.py +118 -0
  38. diffguard/rules/test_removal.py +253 -0
  39. diffguard/suppressions/__init__.py +0 -0
  40. diffguard/suppressions/manager.py +81 -0
  41. diffguard/utils/__init__.py +0 -0
  42. diffguard/utils/logging.py +23 -0
  43. diffguard/utils/paths.py +131 -0
  44. diffguard/version.py +1 -0
  45. diffguard_ai-0.1.0.dist-info/METADATA +141 -0
  46. diffguard_ai-0.1.0.dist-info/RECORD +49 -0
  47. diffguard_ai-0.1.0.dist-info/WHEEL +4 -0
  48. diffguard_ai-0.1.0.dist-info/entry_points.txt +2 -0
  49. diffguard_ai-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,195 @@
1
+ """Built-in secret patterns, detection and redaction (shared by several rules)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import re
8
+ from collections import Counter
9
+ from dataclasses import dataclass
10
+
11
+ from diffguard.core.enums import Confidence
12
+
13
+ _CRED_WORDS = r"password|passwd|pwd|secret|api[_-]?key|access[_-]?key|auth[_-]?token|token|credentials?"
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class SecretPattern:
18
+ kind: str
19
+ regex: re.Pattern[str]
20
+ group: int
21
+ confidence: Confidence
22
+ description: str
23
+ min_entropy: float = 0.0
24
+ key_group: int | None = None
25
+ generic: bool = False
26
+ dotenv_only: bool = False
27
+ check_placeholder: bool = True
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class SecretMatch:
32
+ kind: str
33
+ start: int
34
+ end: int
35
+ confidence: Confidence
36
+ description: str
37
+ value_hash: str
38
+
39
+
40
+ BUILTIN_PATTERNS: tuple[SecretPattern, ...] = (
41
+ SecretPattern(
42
+ "private-key",
43
+ re.compile(r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----"),
44
+ 0,
45
+ Confidence.HIGH,
46
+ "private key block",
47
+ check_placeholder=False,
48
+ ),
49
+ SecretPattern(
50
+ "aws-access-key-id",
51
+ re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
52
+ 0,
53
+ Confidence.HIGH,
54
+ "AWS access key ID",
55
+ ),
56
+ SecretPattern(
57
+ "aws-secret-access-key",
58
+ re.compile(r"(?i)aws_?secret_?(?:access_?)?key[\"']?\s*[:=]\s*[\"']?([A-Za-z0-9/+=]{40})\b"),
59
+ 1,
60
+ Confidence.HIGH,
61
+ "AWS secret access key",
62
+ ),
63
+ SecretPattern(
64
+ "github-token",
65
+ re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za-z0-9_]{22,255})\b"),
66
+ 0,
67
+ Confidence.HIGH,
68
+ "GitHub token",
69
+ ),
70
+ SecretPattern(
71
+ "slack-token",
72
+ re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}"),
73
+ 0,
74
+ Confidence.HIGH,
75
+ "Slack token",
76
+ ),
77
+ SecretPattern(
78
+ "stripe-live-key",
79
+ re.compile(r"\b[sr]k_live_[A-Za-z0-9]{16,}\b"),
80
+ 0,
81
+ Confidence.HIGH,
82
+ "Stripe live API key",
83
+ ),
84
+ SecretPattern(
85
+ "google-api-key",
86
+ re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b"),
87
+ 0,
88
+ Confidence.HIGH,
89
+ "Google API key",
90
+ ),
91
+ SecretPattern(
92
+ "generic-credential",
93
+ re.compile(rf"(?i)\b([\w.-]*(?:{_CRED_WORDS})[\w.-]*)[\"']?\s*[:=]\s*[\"']([^\"'\s]{{8,}})[\"']"),
94
+ 2,
95
+ Confidence.MEDIUM,
96
+ "hard-coded credential assignment",
97
+ min_entropy=2.5,
98
+ key_group=1,
99
+ generic=True,
100
+ ),
101
+ SecretPattern(
102
+ "dotenv-credential",
103
+ re.compile(
104
+ r"(?i)^\s*(?:export\s+)?([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|API_?KEY|ACCESS_?KEY|TOKEN|CREDENTIALS?)"
105
+ r"[A-Z0-9_]*)\s*=\s*([^\s#\"']{8,})\s*$"
106
+ ),
107
+ 2,
108
+ Confidence.MEDIUM,
109
+ "credential in environment file",
110
+ min_entropy=2.5,
111
+ key_group=1,
112
+ generic=True,
113
+ dotenv_only=True,
114
+ ),
115
+ )
116
+
117
+ _PLACEHOLDER_MARKERS = (
118
+ "example", "changeme", "change_me", "change-me", "your_", "your-", "yourkey", "placeholder",
119
+ "dummy", "redacted", "xxxx", "****", "<", ">", "${", "{{", "%(", "$(", "todo", "fixme",
120
+ ) # fmt: skip
121
+ _IGNORED_KEY_SUFFIXES = ("_hash", "_file", "_path", "_url", "_env", "_name", "_header", "_type",
122
+ "_field", "_label", "_length", "_param", "_policy", "_prompt") # fmt: skip
123
+ _IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z_.:/-]*$")
124
+
125
+
126
+ def shannon_entropy(value: str) -> float:
127
+ if not value:
128
+ return 0.0
129
+ total = len(value)
130
+ return -sum((n / total) * math.log2(n / total) for n in Counter(value).values())
131
+
132
+
133
+ def is_placeholder(value: str) -> bool:
134
+ lower = value.lower()
135
+ if any(marker in lower for marker in _PLACEHOLDER_MARKERS):
136
+ return True
137
+ return len(set(value)) <= 1
138
+
139
+
140
+ def _looks_like_identifier(value: str) -> bool:
141
+ if value.startswith(("http://", "https://", "/", "./")) and "@" not in value:
142
+ return True
143
+ return bool(_IDENTIFIER_RE.match(value))
144
+
145
+
146
+ def find_secrets(
147
+ line: str,
148
+ patterns: tuple[SecretPattern, ...] = BUILTIN_PATTERNS,
149
+ *,
150
+ dotenv: bool = False,
151
+ ) -> list[SecretMatch]:
152
+ spans: list[tuple[int, int]] = []
153
+ matches: list[SecretMatch] = []
154
+ for pattern in patterns:
155
+ if pattern.dotenv_only and not dotenv:
156
+ continue
157
+ for m in pattern.regex.finditer(line):
158
+ start, end = m.span(pattern.group)
159
+ if start < 0 or any(start < e and s < end for s, e in spans):
160
+ continue
161
+ value = m.group(pattern.group)
162
+ if pattern.check_placeholder and is_placeholder(value):
163
+ continue
164
+ if pattern.min_entropy and shannon_entropy(value) < pattern.min_entropy:
165
+ continue
166
+ if pattern.key_group is not None:
167
+ key = m.group(pattern.key_group).lower()
168
+ if key.endswith(_IGNORED_KEY_SUFFIXES):
169
+ continue
170
+ if pattern.generic and _looks_like_identifier(value):
171
+ continue
172
+ spans.append((start, end))
173
+ matches.append(
174
+ SecretMatch(
175
+ pattern.kind,
176
+ start,
177
+ end,
178
+ pattern.confidence,
179
+ pattern.description,
180
+ hashlib.sha256(value.encode()).hexdigest()[:12],
181
+ )
182
+ )
183
+ return sorted(matches, key=lambda m: m.start)
184
+
185
+
186
+ def redact(line: str, matches: list[SecretMatch]) -> str:
187
+ out = line
188
+ for m in sorted(matches, key=lambda m: m.start, reverse=True):
189
+ out = out[: m.start] + "[REDACTED]" + out[m.end :]
190
+ return out
191
+
192
+
193
+ def redact_secrets(text: str) -> str:
194
+ """Best-effort redaction of built-in secret patterns from ``text``."""
195
+ return redact(text, find_secrets(text, dotenv=False))
@@ -0,0 +1,118 @@
1
+ """Secret detection on added lines. Secret values are never stored or reported."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import posixpath
6
+ import re
7
+ from collections.abc import Mapping
8
+ from typing import Any
9
+
10
+ from diffguard.core.enums import Category, Confidence, Severity
11
+ from diffguard.core.models import Finding, RuleMetadata
12
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings, clip
13
+ from diffguard.rules.secret_patterns import (
14
+ BUILTIN_PATTERNS,
15
+ SecretPattern,
16
+ find_secrets,
17
+ redact,
18
+ )
19
+ from diffguard.utils.paths import matches_any
20
+
21
+
22
+ class SecretsRule(Rule):
23
+ metadata = RuleMetadata(
24
+ name="secrets",
25
+ description="Detects likely secrets (keys, tokens, private keys, credentials) in added lines.",
26
+ category=Category.SECRETS,
27
+ default_severity=Severity.ERROR,
28
+ checks={"DG-SEC-001": "Likely secret added"},
29
+ )
30
+
31
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
32
+ r = OptionReader(options)
33
+ allow_patterns = r.regexes("allowlist_patterns")
34
+ allow_paths = r.globs("allowlist_paths")
35
+ disable = r.strings("disable_builtin")
36
+ known = {p.kind for p in BUILTIN_PATTERNS}
37
+ for kind in disable:
38
+ if kind not in known:
39
+ r.errors.append(
40
+ f"'disable_builtin': unknown pattern '{kind}' (known: {', '.join(sorted(known))})"
41
+ )
42
+ max_len = r.integer("max_line_length", 4000, minimum=100)
43
+ extra: list[SecretPattern] = []
44
+ for i, item in enumerate(r.mappings("extra_patterns")):
45
+ where = f"'extra_patterns[{i}]'"
46
+ unknown = set(item) - {"name", "regex", "group", "description"}
47
+ if unknown:
48
+ r.errors.append(f"{where}: unknown keys {sorted(unknown)}")
49
+ name = item.get("name")
50
+ compiled = r.regex(item.get("regex"), f"{where}.regex")
51
+ group = item.get("group", 0)
52
+ if not isinstance(name, str) or not name:
53
+ r.errors.append(f"{where}.name is required")
54
+ elif compiled is not None:
55
+ if (
56
+ not isinstance(group, int)
57
+ or isinstance(group, bool)
58
+ or not (0 <= group <= compiled.groups)
59
+ ):
60
+ r.errors.append(f"{where}.group must be a valid group number")
61
+ else:
62
+ extra.append(
63
+ SecretPattern(
64
+ f"custom:{name}",
65
+ compiled,
66
+ group,
67
+ Confidence.MEDIUM,
68
+ str(item.get("description") or f"custom pattern '{name}'"),
69
+ )
70
+ )
71
+ r.finish()
72
+ patterns = tuple(p for p in BUILTIN_PATTERNS if p.kind not in disable) + tuple(extra)
73
+ return {
74
+ "patterns": patterns,
75
+ "allowlist_patterns": allow_patterns,
76
+ "allowlist_paths": allow_paths,
77
+ "max_line_length": max_len,
78
+ }
79
+
80
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
81
+ opts = settings.options
82
+ patterns: tuple[SecretPattern, ...] = opts["patterns"]
83
+ allow_patterns: tuple[re.Pattern[str], ...] = opts["allowlist_patterns"]
84
+ allow_paths: tuple[str, ...] = opts["allowlist_paths"]
85
+ max_len: int = opts["max_line_length"]
86
+ findings: list[Finding] = []
87
+ for change in ctx.diff.files:
88
+ if change.is_binary or matches_any(change.path, allow_paths):
89
+ continue
90
+ base = posixpath.basename(change.path).lower()
91
+ dotenv = base.startswith(".env") or base.endswith(".env")
92
+ for line in change.added_lines():
93
+ text = line.content[:max_len]
94
+ if any(p.search(text) for p in allow_patterns):
95
+ continue
96
+ matches = find_secrets(text, patterns, dotenv=dotenv)
97
+ if not matches:
98
+ continue
99
+ evidence = clip(redact(text, matches))
100
+ for m in matches:
101
+ findings.append(
102
+ self.finding(
103
+ settings,
104
+ "DG-SEC-001",
105
+ message=f"Likely secret added ({m.description})",
106
+ explanation="Secrets committed to a repository stay in history and are "
107
+ "exposed to everyone with read access, even if removed later.",
108
+ remediation="Remove the value, load it from the environment or a secret "
109
+ "manager, and rotate the credential. If this is a safe test value, add "
110
+ "it to options.allowlist_patterns or allowlist_paths.",
111
+ file_path=change.path,
112
+ line=line.new_lineno,
113
+ evidence=evidence,
114
+ confidence=m.confidence,
115
+ key=f"{m.kind}:{m.value_hash}",
116
+ )
117
+ )
118
+ return findings
@@ -0,0 +1,253 @@
1
+ """Test-removal and test-weakening detection.
2
+
3
+ Heuristic and line-based: it distinguishes removal from refactoring only by checking
4
+ whether the same test name is (re)defined elsewhere in the diff. It does not
5
+ understand test semantics.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import posixpath
11
+ import re
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from diffguard.core.enums import Category, ChangeType, Confidence, Severity
16
+ from diffguard.core.models import FileChange, Finding, RuleMetadata
17
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings, clip
18
+ from diffguard.rules.filetypes import DEFAULT_TEST_PATHS
19
+ from diffguard.rules.secret_patterns import redact_secrets
20
+ from diffguard.utils.paths import matches_any
21
+
22
+ _SOURCE_EXTS = {".py", ".js", ".jsx", ".ts", ".tsx", ".go", ".java", ".kt", ".rb", ".rs", ".cs", ".php"}
23
+
24
+ _DEF_PATTERNS = (
25
+ re.compile(r"^\s*(?:async\s+)?def\s+(test\w*)\s*\("),
26
+ re.compile(r"^\s*class\s+(Test\w*)\b"),
27
+ re.compile(r"""\b(?:it|test|describe)(?:\.(?:skip|only|todo))?\s*\(\s*(["'`])(.+?)\1"""),
28
+ re.compile(r"^\s*func\s+(Test\w+)\s*\("),
29
+ re.compile(r"^\s*(?:public\s+)?void\s+(test\w*)\s*\("),
30
+ )
31
+ _ASSERT = re.compile(
32
+ r"\bassert\b|\bself\.assert\w+\(|\bpytest\.raises\(|\bassertRaises\(|\bexpect\(|\bassert\.\w+\("
33
+ r"|\brequire\.\w+\(|\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail|FailNow)\("
34
+ )
35
+ # Unconditional skips only. Conditional guards (skipif/skipIf/skipUnless, e.g. platform checks)
36
+ # are ordinary practice and would be noise.
37
+ _SKIP = re.compile(
38
+ r"@pytest\.mark\.(?:skip|xfail)\b(?!if)|@unittest\.(?:skip|expectedFailure)\b(?!If)"
39
+ r"|\b(?:it|test|describe)\.skip\(|\bx(?:it|describe)\(|\b(?:it|test)\.todo\(|\bt\.Skip(?:Now)?\("
40
+ )
41
+ _TEST_CONFIG_NAMES = {"pytest.ini", "setup.cfg", "tox.ini", "pyproject.toml", "conftest.py", ".coveragerc"}
42
+ _CONFIG_IGNORE = re.compile(r"--(?:ignore|deselect)\b|(?:^|\s)-k\s*[\"']?not\b")
43
+ _COVERAGE = re.compile(r"(?i)(?:fail[_-]under|cov-fail-under)\s*[=:\s]\s*[\"']?(\d+(?:\.\d+)?)")
44
+
45
+
46
+ def _defined_names(content: str) -> list[str]:
47
+ names: list[str] = []
48
+ for pattern in _DEF_PATTERNS:
49
+ m = pattern.search(content)
50
+ if m:
51
+ names.append(m.group(m.lastindex or 1))
52
+ return names
53
+
54
+
55
+ class TestRemovalRule(Rule):
56
+ __test__ = False # not a pytest class
57
+
58
+ metadata = RuleMetadata(
59
+ name="test_removal",
60
+ description="Detects deleted tests, removed test functions and assertions, skipped "
61
+ "tests and weakened test configuration.",
62
+ category=Category.TESTING,
63
+ default_severity=Severity.WARNING,
64
+ checks={
65
+ "DG-TEST-001": "Test file deleted",
66
+ "DG-TEST-002": "Test function or class removed",
67
+ "DG-TEST-003": "Assertions removed",
68
+ "DG-TEST-004": "Test skipped or excluded",
69
+ "DG-TEST-005": "Coverage threshold lowered",
70
+ },
71
+ )
72
+
73
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
74
+ r = OptionReader(options)
75
+ paths = r.globs("test_paths", DEFAULT_TEST_PATHS)
76
+ r.finish()
77
+ return {"test_paths": paths}
78
+
79
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
80
+ test_paths: tuple[str, ...] = settings.options["test_paths"]
81
+ added_names: set[str] = set()
82
+ for change in ctx.diff.files:
83
+ for line in change.added_lines():
84
+ added_names.update(_defined_names(line.content))
85
+ removed_total = added_total = 0
86
+ for change in ctx.diff.files:
87
+ if change.is_binary or not self._is_test_source(change.path, test_paths):
88
+ continue
89
+ removed_total += sum(1 for ln in change.removed_lines() if _ASSERT.search(ln.content))
90
+ added_total += sum(1 for ln in change.added_lines() if _ASSERT.search(ln.content))
91
+ net_assertions_removed = removed_total - added_total
92
+ findings: list[Finding] = []
93
+ for change in ctx.diff.files:
94
+ if change.is_binary:
95
+ continue
96
+ findings.extend(
97
+ self._test_file(change, test_paths, added_names, settings, net_assertions_removed)
98
+ )
99
+ findings.extend(self._config(change, settings))
100
+ return findings
101
+
102
+ @staticmethod
103
+ def _is_test_source(path: str, test_paths: tuple[str, ...]) -> bool:
104
+ return matches_any(path, test_paths) and posixpath.splitext(path)[1] in _SOURCE_EXTS
105
+
106
+ def _test_file(
107
+ self,
108
+ change: FileChange,
109
+ test_paths: tuple[str, ...],
110
+ added_names: set[str],
111
+ settings: RuleSettings,
112
+ net_assertions_removed: int,
113
+ ) -> list[Finding]:
114
+ out: list[Finding] = []
115
+ old = change.old_path
116
+ was_test = old is not None and self._is_test_source(old, test_paths)
117
+ is_test = change.new_path is not None and self._is_test_source(change.new_path, test_paths)
118
+ if was_test and (
119
+ change.change_type is ChangeType.DELETED
120
+ or (change.change_type is ChangeType.RENAMED and not is_test)
121
+ ):
122
+ assert old is not None
123
+ verb = "deleted" if change.change_type is ChangeType.DELETED else "moved out of the test tree"
124
+ out.append(
125
+ self.finding(
126
+ settings,
127
+ "DG-TEST-001",
128
+ message=f"Test file {verb}: {old}",
129
+ explanation="Removing test files reduces the safety net protecting behavior.",
130
+ remediation="Restore the tests, or confirm the removal is intentional and covered elsewhere.",
131
+ file_path=old,
132
+ line_side="old",
133
+ confidence=Confidence.HIGH,
134
+ key="deleted",
135
+ )
136
+ )
137
+ return out
138
+ if not is_test or change.new_path is None:
139
+ return out
140
+ path = change.new_path
141
+ removed_defs = [
142
+ (name, line)
143
+ for line in change.removed_lines()
144
+ for name in _defined_names(line.content)
145
+ if name not in added_names
146
+ ]
147
+ removed_names = {name for name, _ in removed_defs}
148
+ new_defs = {
149
+ name
150
+ for line in change.added_lines()
151
+ for name in _defined_names(line.content)
152
+ if name not in removed_names
153
+ }
154
+ # As many new test names as lost ones: most likely a rename/replacement, not a removal.
155
+ likely_renamed = len(new_defs) >= len(removed_defs) > 0
156
+ for name, line in removed_defs:
157
+ out.append(
158
+ self.finding(
159
+ settings,
160
+ "DG-TEST-002",
161
+ message=(
162
+ f"Test removed or renamed: {name} in {path}"
163
+ if likely_renamed
164
+ else f"Test removed: {name} in {path}"
165
+ ),
166
+ explanation="A test definition was removed and no test with the same name "
167
+ "was added anywhere in this change.",
168
+ remediation="Restore the test, or confirm it was replaced by an equivalent one.",
169
+ file_path=path,
170
+ line=line.old_lineno,
171
+ line_side="old",
172
+ evidence=clip(redact_secrets(line.content)),
173
+ confidence=Confidence.LOW if likely_renamed else Confidence.HIGH,
174
+ key=f"removed-test:{name}",
175
+ )
176
+ )
177
+ removed_asserts = [ln for ln in change.removed_lines() if _ASSERT.search(ln.content)]
178
+ added_asserts = sum(1 for ln in change.added_lines() if _ASSERT.search(ln.content))
179
+ if len(removed_asserts) > added_asserts and net_assertions_removed > 0:
180
+ net = len(removed_asserts) - added_asserts
181
+ first = removed_asserts[0]
182
+ out.append(
183
+ self.finding(
184
+ settings,
185
+ "DG-TEST-003",
186
+ message=f"{net} more assertion(s) removed than added in {path}",
187
+ explanation="Fewer assertions means tests verify less behavior.",
188
+ remediation="Confirm the removed assertions were redundant or replaced.",
189
+ file_path=path,
190
+ line=first.old_lineno,
191
+ line_side="old",
192
+ evidence=clip(redact_secrets(first.content)),
193
+ confidence=Confidence.MEDIUM,
194
+ key="assertions-removed",
195
+ )
196
+ )
197
+ for line in change.added_lines():
198
+ if _SKIP.search(line.content):
199
+ out.append(
200
+ self.finding(
201
+ settings,
202
+ "DG-TEST-004",
203
+ message=f"Test skipped or disabled in {path}",
204
+ explanation="Skipped or expected-to-fail tests silently stop protecting behavior.",
205
+ remediation="Fix the test instead of skipping it, or document why it must be skipped.",
206
+ file_path=path,
207
+ line=line.new_lineno,
208
+ evidence=clip(redact_secrets(line.content)),
209
+ confidence=Confidence.HIGH,
210
+ key=f"skip:{line.content.strip()}",
211
+ )
212
+ )
213
+ return out
214
+
215
+ def _config(self, change: FileChange, settings: RuleSettings) -> list[Finding]:
216
+ path = change.new_path or change.path
217
+ if posixpath.basename(path) not in _TEST_CONFIG_NAMES or change.change_type is ChangeType.DELETED:
218
+ return []
219
+ out: list[Finding] = []
220
+ for line in change.added_lines():
221
+ if _CONFIG_IGNORE.search(line.content):
222
+ out.append(
223
+ self.finding(
224
+ settings,
225
+ "DG-TEST-004",
226
+ message=f"Tests excluded via configuration in {path}",
227
+ explanation="Test selection options can hide failing tests from the suite.",
228
+ remediation="Remove the exclusion or justify it in review.",
229
+ file_path=path,
230
+ line=line.new_lineno,
231
+ evidence=clip(line.content),
232
+ confidence=Confidence.MEDIUM,
233
+ key=f"config-ignore:{line.content.strip()}",
234
+ )
235
+ )
236
+ old_vals = [float(m.group(1)) for ln in change.removed_lines() if (m := _COVERAGE.search(ln.content))]
237
+ new_vals = [float(m.group(1)) for ln in change.added_lines() if (m := _COVERAGE.search(ln.content))]
238
+ if old_vals and (not new_vals or min(new_vals) < max(old_vals)):
239
+ detail = f"{max(old_vals):g} -> {min(new_vals):g}" if new_vals else "threshold removed"
240
+ out.append(
241
+ self.finding(
242
+ settings,
243
+ "DG-TEST-005",
244
+ message=f"Coverage threshold lowered in {path} ({detail})",
245
+ explanation="A lower coverage gate lets less-tested code pass CI.",
246
+ remediation="Keep the threshold, or justify lowering it explicitly.",
247
+ file_path=path,
248
+ evidence=detail,
249
+ confidence=Confidence.HIGH,
250
+ key="coverage",
251
+ )
252
+ )
253
+ return out
File without changes
@@ -0,0 +1,81 @@
1
+ """Suppressions from policy entries and (opt-in) inline markers.
2
+
3
+ Inline markers look like ``# diffguard: ignore[DG-DANGER-001] reason`` and apply to
4
+ findings on that same added line. They are **disabled by default** because the
5
+ author of a diff (for example an AI agent) could add the marker itself.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import re
12
+ from collections.abc import Iterable, Mapping
13
+ from datetime import date
14
+
15
+ from diffguard.core.enums import FindingStatus
16
+ from diffguard.core.models import Finding, SuppressionInfo, SuppressionRule
17
+ from diffguard.utils.paths import matches
18
+
19
+ _INLINE_RE = re.compile(r"diffguard:\s*ignore\[([A-Za-z0-9_,\s-]+)\](?:\s+(\S.*))?")
20
+
21
+ InlineLookup = Mapping[tuple[str, int], str]
22
+
23
+
24
+ def _policy_match(rule: SuppressionRule, finding: Finding) -> bool:
25
+ if rule.rule not in (finding.rule_id, finding.rule_name):
26
+ return False
27
+ if rule.fingerprint is not None and rule.fingerprint != finding.fingerprint:
28
+ return False
29
+ if rule.path is not None:
30
+ return finding.file_path is not None and matches(finding.file_path, rule.path)
31
+ return True
32
+
33
+
34
+ def _inline_match(finding: Finding, lookup: InlineLookup) -> SuppressionInfo | None:
35
+ if finding.file_path is None or finding.line is None or finding.line_side != "new":
36
+ return None
37
+ content = lookup.get((finding.file_path, finding.line))
38
+ if content is None:
39
+ return None
40
+ marker = _INLINE_RE.search(content)
41
+ if marker is None:
42
+ return None
43
+ targets = {t.strip() for t in marker.group(1).split(",") if t.strip()}
44
+ if finding.rule_id in targets or finding.rule_name in targets:
45
+ return SuppressionInfo("inline", (marker.group(2) or "").strip() or None)
46
+ return None
47
+
48
+
49
+ def apply_suppressions(
50
+ findings: Iterable[Finding],
51
+ rules: Iterable[SuppressionRule],
52
+ *,
53
+ today: date,
54
+ inline_lookup: InlineLookup | None = None,
55
+ ) -> tuple[list[Finding], list[str]]:
56
+ """Return findings with suppression status applied, plus warnings (expired entries)."""
57
+ warnings: list[str] = []
58
+ active_rules: list[SuppressionRule] = []
59
+ for rule in rules:
60
+ if rule.expires is not None and rule.expires < today:
61
+ target = rule.path or rule.fingerprint or "?"
62
+ warnings.append(
63
+ f"suppression for {rule.rule} on {target} expired on {rule.expires.isoformat()} "
64
+ "and was ignored"
65
+ )
66
+ else:
67
+ active_rules.append(rule)
68
+
69
+ result: list[Finding] = []
70
+ for finding in findings:
71
+ info: SuppressionInfo | None = None
72
+ for rule in active_rules:
73
+ if _policy_match(rule, finding):
74
+ info = SuppressionInfo("policy", rule.reason)
75
+ break
76
+ if info is None and inline_lookup:
77
+ info = _inline_match(finding, inline_lookup)
78
+ if info is not None:
79
+ finding = dataclasses.replace(finding, status=FindingStatus.SUPPRESSED, suppression=info)
80
+ result.append(finding)
81
+ return result, warnings
File without changes
@@ -0,0 +1,23 @@
1
+ """Logging setup. Logs go to stderr so stdout stays machine-readable."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+
8
+ LOGGER_NAME = "diffguard"
9
+
10
+
11
+ def get_logger(name: str | None = None) -> logging.Logger:
12
+ return logging.getLogger(f"{LOGGER_NAME}.{name}" if name else LOGGER_NAME)
13
+
14
+
15
+ def configure_logging(*, verbose: bool = False, debug: bool = False) -> None:
16
+ level = logging.DEBUG if debug else logging.INFO if verbose else logging.WARNING
17
+ logger = logging.getLogger(LOGGER_NAME)
18
+ logger.handlers.clear()
19
+ handler = logging.StreamHandler(sys.stderr)
20
+ handler.setFormatter(logging.Formatter("diffguard: %(levelname)s: %(message)s"))
21
+ logger.addHandler(handler)
22
+ logger.setLevel(level)
23
+ logger.propagate = False