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,248 @@
1
+ """Rule interface, per-scan context, option validation and finding construction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from abc import ABC, abstractmethod
8
+ from collections.abc import Iterator, Mapping, Sequence
9
+ from dataclasses import dataclass
10
+ from re import _constants, _parser # type: ignore[attr-defined]
11
+ from typing import Any, ClassVar
12
+
13
+ from diffguard.core.enums import Confidence, Severity
14
+ from diffguard.core.exceptions import PatternError
15
+ from diffguard.core.interfaces import ContentReader
16
+ from diffguard.core.models import DiffDocument, Finding, Policy, RuleMetadata, TaskContext
17
+ from diffguard.utils.paths import compile_pattern, normalize_pattern
18
+
19
+ EVIDENCE_LIMIT = 160
20
+ MAX_REGEX_LENGTH = 500
21
+
22
+
23
+ def _iter_subpatterns(value: object) -> Iterator[Any]:
24
+ parsed_type = _parser.SubPattern
25
+ if isinstance(value, parsed_type):
26
+ yield value
27
+ elif isinstance(value, (tuple, list)):
28
+ for item in value:
29
+ yield from _iter_subpatterns(item)
30
+
31
+
32
+ def _has_unbounded_repeat(pattern: Any) -> bool:
33
+ for op, av in pattern:
34
+ if op in _REPEAT_OPS and av[1] == _constants.MAXREPEAT:
35
+ return True
36
+ if any(_has_unbounded_repeat(sub) for sub in _iter_subpatterns(av)):
37
+ return True
38
+ return False
39
+
40
+
41
+ def _find_nested_repeat(pattern: Any) -> bool:
42
+ for op, av in pattern:
43
+ if op in _REPEAT_OPS and av[1] == _constants.MAXREPEAT and _has_unbounded_repeat(av[2]):
44
+ return True
45
+ if any(_find_nested_repeat(sub) for sub in _iter_subpatterns(av)):
46
+ return True
47
+ return False
48
+
49
+
50
+ def catastrophic_regex_reason(text: str) -> str | None:
51
+ """Reject regexes with an unbounded quantifier nested inside another one, e.g. ``(a+)+``.
52
+
53
+ This is the classic cause of catastrophic backtracking (ReDoS). It is a conservative static
54
+ check, not a proof of safety: other pathological patterns may exist.
55
+ """
56
+ try:
57
+ parsed = _parser.parse(text)
58
+ except re.error:
59
+ return None # reported by re.compile
60
+ if _find_nested_repeat(parsed):
61
+ return "contains a nested unbounded quantifier (risk of catastrophic backtracking)"
62
+ return None
63
+
64
+
65
+ class OptionsError(Exception):
66
+ """Invalid rule options. Carries every problem found."""
67
+
68
+ def __init__(self, errors: Sequence[str]) -> None:
69
+ self.errors = tuple(errors)
70
+ super().__init__("; ".join(self.errors))
71
+
72
+
73
+ @dataclass(frozen=True, slots=True)
74
+ class RuleContext:
75
+ diff: DiffDocument
76
+ task: TaskContext
77
+ policy: Policy
78
+ reader: ContentReader
79
+ protected_files: frozenset[str] = frozenset()
80
+
81
+
82
+ @dataclass(frozen=True, slots=True)
83
+ class RuleSettings:
84
+ severity: Severity
85
+ options: Mapping[str, Any]
86
+
87
+
88
+ _MISSING: Any = object()
89
+ _REPEAT_OPS = frozenset({_constants.MAX_REPEAT, _constants.MIN_REPEAT})
90
+
91
+
92
+ class OptionReader:
93
+ """Validates a rule's ``options`` mapping, collecting all errors."""
94
+
95
+ def __init__(self, options: Mapping[str, Any]) -> None:
96
+ self._options = dict(options)
97
+ self._used: set[str] = set()
98
+ self.errors: list[str] = []
99
+
100
+ def _take(self, key: str) -> Any:
101
+ self._used.add(key)
102
+ return self._options.get(key, _MISSING)
103
+
104
+ def boolean(self, key: str, default: bool) -> bool:
105
+ value = self._take(key)
106
+ if value is _MISSING:
107
+ return default
108
+ if not isinstance(value, bool):
109
+ self.errors.append(f"'{key}' must be true or false")
110
+ return default
111
+ return value
112
+
113
+ def integer(self, key: str, default: int, *, minimum: int = 1) -> int:
114
+ value = self._take(key)
115
+ if value is _MISSING:
116
+ return default
117
+ if not isinstance(value, int) or isinstance(value, bool) or value < minimum:
118
+ self.errors.append(f"'{key}' must be an integer >= {minimum}")
119
+ return default
120
+ return value
121
+
122
+ def strings(self, key: str, default: tuple[str, ...] = ()) -> tuple[str, ...]:
123
+ value = self._take(key)
124
+ if value is _MISSING:
125
+ return default
126
+ if not isinstance(value, list) or not all(isinstance(v, str) and v for v in value):
127
+ self.errors.append(f"'{key}' must be a list of non-empty strings")
128
+ return default
129
+ return tuple(value)
130
+
131
+ def globs(self, key: str, default: tuple[str, ...] = ()) -> tuple[str, ...]:
132
+ value = self._take(key)
133
+ if value is _MISSING:
134
+ return default
135
+ if not isinstance(value, list):
136
+ self.errors.append(f"'{key}' must be a list of glob patterns")
137
+ return default
138
+ out: list[str] = []
139
+ for index, item in enumerate(value):
140
+ try:
141
+ pattern = normalize_pattern(item)
142
+ compile_pattern(pattern)
143
+ out.append(pattern)
144
+ except PatternError as exc:
145
+ self.errors.append(f"'{key}[{index}]': {exc}")
146
+ return tuple(out)
147
+
148
+ def regex(self, text: object, where: str) -> re.Pattern[str] | None:
149
+ if not isinstance(text, str) or not text:
150
+ self.errors.append(f"{where} must be a non-empty regular expression string")
151
+ return None
152
+ if len(text) > MAX_REGEX_LENGTH:
153
+ self.errors.append(f"{where} is longer than {MAX_REGEX_LENGTH} characters")
154
+ return None
155
+ try:
156
+ compiled = re.compile(text)
157
+ except re.error as exc:
158
+ self.errors.append(f"{where} is not a valid regular expression: {exc}")
159
+ return None
160
+ reason = catastrophic_regex_reason(text)
161
+ if reason:
162
+ self.errors.append(f"{where} {reason}")
163
+ return None
164
+ return compiled
165
+
166
+ def regexes(self, key: str) -> tuple[re.Pattern[str], ...]:
167
+ value = self._take(key)
168
+ if value is _MISSING:
169
+ return ()
170
+ if not isinstance(value, list):
171
+ self.errors.append(f"'{key}' must be a list of regular expressions")
172
+ return ()
173
+ compiled = [self.regex(item, f"'{key}[{i}]'") for i, item in enumerate(value)]
174
+ return tuple(p for p in compiled if p is not None)
175
+
176
+ def mappings(self, key: str) -> list[Mapping[str, Any]]:
177
+ value = self._take(key)
178
+ if value is _MISSING:
179
+ return []
180
+ if not isinstance(value, list) or not all(isinstance(v, Mapping) for v in value):
181
+ self.errors.append(f"'{key}' must be a list of mappings")
182
+ return []
183
+ return list(value)
184
+
185
+ def finish(self) -> None:
186
+ for key in self._options:
187
+ if key not in self._used:
188
+ self.errors.append(f"unknown option '{key}'")
189
+ if self.errors:
190
+ raise OptionsError(self.errors)
191
+
192
+
193
+ def clip(text: str, limit: int = EVIDENCE_LIMIT) -> str:
194
+ text = text.strip()
195
+ return text if len(text) <= limit else text[: limit - 3] + "..."
196
+
197
+
198
+ def make_fingerprint(rule_id: str, file_path: str | None, key: str) -> str:
199
+ raw = f"v1\0{rule_id}\0{file_path or ''}\0{key}".encode()
200
+ return hashlib.sha256(raw).hexdigest()[:16]
201
+
202
+
203
+ class Rule(ABC):
204
+ """Base class for all rules. Rules are stateless and must not touch the network
205
+ or execute repository code."""
206
+
207
+ metadata: ClassVar[RuleMetadata]
208
+
209
+ @abstractmethod
210
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
211
+ """Return normalized options or raise :class:`OptionsError`."""
212
+
213
+ @abstractmethod
214
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
215
+ """Analyze ``ctx`` and return findings. Raise on internal failure."""
216
+
217
+ def finding(
218
+ self,
219
+ settings: RuleSettings,
220
+ check_id: str,
221
+ *,
222
+ message: str,
223
+ explanation: str,
224
+ remediation: str,
225
+ file_path: str | None = None,
226
+ line: int | None = None,
227
+ line_side: str = "new",
228
+ evidence: str | None = None,
229
+ confidence: Confidence | None = None,
230
+ key: str | None = None,
231
+ severity: Severity | None = None,
232
+ ) -> Finding:
233
+ meta = self.metadata
234
+ return Finding(
235
+ rule_id=check_id,
236
+ rule_name=meta.name,
237
+ severity=severity or settings.severity,
238
+ category=meta.category,
239
+ message=message,
240
+ explanation=explanation,
241
+ remediation=remediation,
242
+ fingerprint=make_fingerprint(check_id, file_path, key if key is not None else message),
243
+ file_path=file_path,
244
+ line=line,
245
+ line_side=line_side,
246
+ evidence=evidence,
247
+ confidence=confidence,
248
+ )
@@ -0,0 +1,98 @@
1
+ """Detection of changes to sensitive configuration files (CI, deploy, infra, security)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from diffguard.core.enums import Category, Confidence, Severity
9
+ from diffguard.core.models import Finding, RuleMetadata
10
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings
11
+ from diffguard.utils.paths import first_match
12
+
13
+ DEFAULT_PATTERNS: tuple[tuple[str, str], ...] = (
14
+ (".github/workflows/**", "ci"), (".github/actions/**", "ci"), (".gitlab-ci.yml", "ci"),
15
+ ("Jenkinsfile", "ci"), (".circleci/**", "ci"), ("azure-pipelines.yml", "ci"),
16
+ (".travis.yml", "ci"), ("buildkite.yml", "ci"), (".buildkite/**", "ci"),
17
+ ("**/Dockerfile", "container"), ("**/Dockerfile.*", "container"),
18
+ ("**/docker-compose*.yml", "container"), ("**/docker-compose*.yaml", "container"),
19
+ ("**/compose*.yml", "container"), ("**/compose*.yaml", "container"),
20
+ ("infrastructure/**", "infrastructure"), ("terraform/**", "infrastructure"),
21
+ ("**/*.tf", "infrastructure"), ("**/*.tfvars", "infrastructure"),
22
+ ("k8s/**", "infrastructure"), ("kubernetes/**", "infrastructure"), ("helm/**", "infrastructure"),
23
+ ("deploy/**", "deployment"), ("**/deploy/**", "deployment"),
24
+ (".github/CODEOWNERS", "security"), ("CODEOWNERS", "security"), ("SECURITY.md", "security"),
25
+ ("**/*.pem", "security"), ("**/*.key", "security"), (".github/dependabot.yml", "security"),
26
+ ("**/.env", "environment"), ("**/.env.*", "environment"), ("**/*.env", "environment"),
27
+ ) # fmt: skip
28
+
29
+
30
+ class ConfigurationRule(Rule):
31
+ metadata = RuleMetadata(
32
+ name="config_changes",
33
+ description="Flags modifications to CI/CD, container, infrastructure, deployment, "
34
+ "security and environment configuration files.",
35
+ category=Category.CONFIGURATION,
36
+ default_severity=Severity.WARNING,
37
+ checks={"DG-CONFIG-001": "Sensitive configuration file changed"},
38
+ )
39
+
40
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
41
+ r = OptionReader(options)
42
+ disable_defaults = r.boolean("disable_defaults", False)
43
+ patterns: list[tuple[str, str, Severity | None]] = []
44
+ for i, item in enumerate(r.mappings("extra_patterns")):
45
+ where = f"'extra_patterns[{i}]'"
46
+ unknown = set(item) - {"pattern", "category", "severity"}
47
+ if unknown:
48
+ r.errors.append(f"{where}: unknown keys {sorted(unknown)}")
49
+ sub = OptionReader({"g": [item.get("pattern")]})
50
+ globs = sub.globs("g")
51
+ r.errors.extend(f"{where}.pattern: {e.split(': ', 1)[-1]}" for e in sub.errors)
52
+ category = item.get("category", "custom")
53
+ if not isinstance(category, str) or not category:
54
+ r.errors.append(f"{where}.category must be a string")
55
+ category = "custom"
56
+ severity: Severity | None = None
57
+ if "severity" in item:
58
+ try:
59
+ severity = Severity.parse(item["severity"])
60
+ except ValueError as exc:
61
+ r.errors.append(f"{where}.severity: {exc}")
62
+ if globs:
63
+ patterns.append((globs[0], category, severity))
64
+ ignore = r.globs("ignore_paths")
65
+ r.finish()
66
+ base = [] if disable_defaults else [(p, c, None) for p, c in DEFAULT_PATTERNS]
67
+ return {"patterns": tuple(patterns + base), "ignore_paths": ignore}
68
+
69
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
70
+ patterns: tuple[tuple[str, str, Severity | None], ...] = settings.options["patterns"]
71
+ ignore: tuple[str, ...] = settings.options["ignore_paths"]
72
+ findings: list[Finding] = []
73
+ seen: set[str] = set()
74
+ for change in ctx.diff.files:
75
+ for path in change.touched_paths:
76
+ if path in seen or first_match(path, ignore):
77
+ continue
78
+ for pattern, category, severity in patterns:
79
+ if first_match(path, (pattern,)):
80
+ seen.add(path)
81
+ findings.append(
82
+ self.finding(
83
+ settings,
84
+ "DG-CONFIG-001",
85
+ message=f"Sensitive {category} configuration {change.change_type.value}: {path}",
86
+ explanation=f"Changes to {category} configuration can alter builds, "
87
+ "deployments or security posture without touching application code.",
88
+ remediation="Confirm the change is intended for this task and have it "
89
+ "reviewed by an owner of this configuration.",
90
+ file_path=path,
91
+ evidence=f"matched pattern '{pattern}'",
92
+ confidence=Confidence.HIGH,
93
+ severity=severity,
94
+ key=f"{category}:{change.change_type}",
95
+ )
96
+ )
97
+ break
98
+ return findings
@@ -0,0 +1,290 @@
1
+ """Dangerous code-pattern detection on added lines (plus removed authorization checks).
2
+
3
+ This is a focused set of high-signal heuristics, not a SAST engine. Matching is
4
+ language-aware (by file type), skips comment lines, and lowers confidence or
5
+ skips cases that are clearly constant (for example ``os.system("ls")``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections import Counter
12
+ from collections.abc import Mapping
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ from diffguard.core.enums import Category, ChangeType, Confidence, Severity
17
+ from diffguard.core.models import Finding, RuleMetadata
18
+ from diffguard.rules.base import OptionReader, Rule, RuleContext, RuleSettings, clip
19
+ from diffguard.rules.filetypes import ALL_GROUPS, DEFAULT_TEST_PATHS, is_comment, language_group
20
+ from diffguard.rules.secret_patterns import redact_secrets
21
+ from diffguard.utils.paths import matches_any
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class _Pattern:
26
+ groups: frozenset[str]
27
+ regex: re.Pattern[str]
28
+ literal_safe: bool = False
29
+
30
+
31
+ def _p(groups: str, pattern: str, *, literal_safe: bool = False) -> _Pattern:
32
+ selected = ALL_GROUPS if groups == "*" else frozenset(groups.split(","))
33
+ return _Pattern(selected, re.compile(pattern), literal_safe)
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class _Check:
38
+ check_id: str
39
+ title: str
40
+ explanation: str
41
+ remediation: str
42
+ patterns: tuple[_Pattern, ...]
43
+
44
+
45
+ _CHECKS: tuple[_Check, ...] = (
46
+ _Check(
47
+ "DG-DANGER-001",
48
+ "TLS/certificate verification disabled",
49
+ "Disabling certificate verification allows man-in-the-middle attacks.",
50
+ "Keep verification enabled; trust a private CA via its certificate bundle instead.",
51
+ (
52
+ _p("python", r"\bverify\s*=\s*False\b"),
53
+ _p("python", r"\bssl\._create_unverified_context\b|\bCERT_NONE\b|check_hostname\s*=\s*False"),
54
+ _p("js", r"\brejectUnauthorized\s*:\s*false\b"),
55
+ _p("js,shell,config", r"NODE_TLS_REJECT_UNAUTHORIZED\s*[=:]\s*['\"]?0"),
56
+ _p("go", r"\bInsecureSkipVerify\s*:\s*true\b"),
57
+ _p("shell,config", r"\bcurl\b[^|;&]*\s(?:-k|--insecure)\b"),
58
+ _p("shell,config", r"\bwget\b[^|;&]*--no-check-certificate"),
59
+ _p("shell,config", r"\bGIT_SSL_NO_VERIFY\b|\bPYTHONHTTPSVERIFY\s*=\s*0\b"),
60
+ ),
61
+ ),
62
+ _Check(
63
+ "DG-DANGER-002",
64
+ "Unsafe deserialization",
65
+ "Deserializing untrusted data with these APIs can execute arbitrary code.",
66
+ "Use a safe format (JSON) or a safe loader (yaml.safe_load); never deserialize untrusted input.",
67
+ (
68
+ _p("python", r"\b(?:c?[pP]ickle|dill|marshal)\.loads?\("),
69
+ _p(
70
+ "python",
71
+ r"\byaml\.unsafe_load\(|\byaml\.load\((?![^)]*Loader\s*=\s*(?:yaml\.)?(?:Safe|CSafe))",
72
+ ),
73
+ _p("python", r"\bjsonpickle\.decode\("),
74
+ _p("java", r"\bObjectInputStream\b"),
75
+ _p("php", r"\bunserialize\("),
76
+ _p("ruby", r"\bMarshal\.load\b|\bYAML\.load\("),
77
+ ),
78
+ ),
79
+ _Check(
80
+ "DG-DANGER-003",
81
+ "Dynamic command or code execution",
82
+ "Executing strings as shell commands or code enables injection when any part is untrusted.",
83
+ "Pass argument lists without a shell, avoid eval/exec, and validate or allowlist inputs.",
84
+ (
85
+ _p("python", r"\bos\.(?:system|popen)\(", literal_safe=True),
86
+ _p("python", r"\bshell\s*=\s*True\b"),
87
+ _p("python", r"(?<![\w.])(?:eval|exec)\(", literal_safe=True),
88
+ _p("js", r"\bchild_process\.exec(?:Sync)?\(|(?<![\w.])exec(?:Sync)?\(\s*[`\"']"),
89
+ _p("js", r"(?<![\w.])eval\(|\bnew Function\(", literal_safe=True),
90
+ _p("php", r"\b(?:shell_exec|system|passthru|proc_open)\("),
91
+ ),
92
+ ),
93
+ _Check(
94
+ "DG-DANGER-005",
95
+ "Security configuration weakened",
96
+ "This setting reduces the security posture of the application or its environment.",
97
+ "Keep the secure setting, or document and review the exception explicitly.",
98
+ (
99
+ _p("python,config", r"\bDEBUG\s*=\s*True\b"),
100
+ _p("python,config", r"\bALLOWED_HOSTS\s*=\s*\[\s*['\"]\*['\"]\s*\]"),
101
+ _p("python,config", r"\bCORS_(?:ORIGIN_ALLOW_ALL|ALLOW_ALL_ORIGINS)\s*=\s*True\b"),
102
+ _p("python,config", r"\b(?:SESSION|CSRF)_COOKIE_SECURE\s*=\s*False\b"),
103
+ _p("*", r"(?i)Access-Control-Allow-Origin['\"]?\s*[:,=]\s*['\"]?\*"),
104
+ _p("shell,config", r"\bchmod\s+(?:-R\s+)?0?777\b"),
105
+ _p("python", r"\bos\.chmod\([^)]*0o?777"),
106
+ _p(
107
+ "*",
108
+ r"(?i)\b(?:auth(?:entication|orization)?|csrf|ssl|tls)[_-]?(?:enabled|required|verify|check)\s*[=:]\s*(?:false|0|no|off)\b",
109
+ ),
110
+ _p(
111
+ "*",
112
+ r"(?i)\b(?:skip|bypass|disable)[_-]?(?:auth|authentication|authorization|csrf)\w*\s*[=:]\s*(?:true|1|yes|on)\b",
113
+ ),
114
+ _p("config,shell", r"\bprivileged:\s*true\b|\ballowPrivilegeEscalation:\s*true\b|--privileged\b"),
115
+ _p("shell,config", r"\bStrictHostKeyChecking\s+no\b"),
116
+ ),
117
+ ),
118
+ )
119
+
120
+ _AUTH_MARKER = re.compile(
121
+ r"@login_required|@permission_required|@requires_auth|@require_auth|@jwt_required"
122
+ r"|@auth_required|@authenticated|@PreAuthorize|@RolesAllowed|@Secured|@Authorize"
123
+ r"|Depends\(\s*get_current_(?:active_)?user|Depends\(\s*require_\w+"
124
+ r"|\b(?:check|require|verify|ensure)_(?:permissions?|auth\w*|admin|role)\("
125
+ r"|\bis_authenticated\b|\bis_staff\b|\bis_superuser\b"
126
+ )
127
+ _DYNAMIC = re.compile(r"""\bf["']|\.format\(|%\s*[(\w]|["']\s*\+|\+\s*["']|\$\{|\$\(""")
128
+ _LITERAL_ARG = re.compile(r"""\(\s*(["'])[^"'\\]*\1\s*[,)]""")
129
+ _AUTH_GROUPS = frozenset({"python", "js", "go", "java", "ruby", "php"})
130
+
131
+
132
+ class DangerousPatternsRule(Rule):
133
+ metadata = RuleMetadata(
134
+ name="dangerous_patterns",
135
+ description="Flags dangerous code changes: disabled TLS verification, unsafe "
136
+ "deserialization, dynamic command execution, removed authorization checks, "
137
+ "weakened security configuration.",
138
+ category=Category.DANGEROUS_PATTERN,
139
+ default_severity=Severity.WARNING,
140
+ checks={
141
+ **{c.check_id: c.title for c in _CHECKS},
142
+ "DG-DANGER-004": "Authorization check removed",
143
+ "DG-DANGER-006": "Custom dangerous pattern matched",
144
+ },
145
+ )
146
+
147
+ def validate_options(self, options: Mapping[str, Any]) -> Mapping[str, Any]:
148
+ r = OptionReader(options)
149
+ disable = r.strings("disable")
150
+ for check_id in disable:
151
+ if check_id not in self.metadata.checks:
152
+ r.errors.append(f"'disable': unknown check '{check_id}'")
153
+ ignore_paths = r.globs("ignore_paths")
154
+ custom: list[dict[str, Any]] = []
155
+ for i, item in enumerate(r.mappings("extra_patterns")):
156
+ where = f"'extra_patterns[{i}]'"
157
+ unknown = set(item) - {"name", "regex", "message", "languages"}
158
+ if unknown:
159
+ r.errors.append(f"{where}: unknown keys {sorted(unknown)}")
160
+ name, message = item.get("name"), item.get("message")
161
+ compiled = r.regex(item.get("regex"), f"{where}.regex")
162
+ langs = item.get("languages", ["*"])
163
+ valid_langs = isinstance(langs, list) and all(
164
+ isinstance(x, str) and (x == "*" or x in ALL_GROUPS) for x in langs
165
+ )
166
+ if not valid_langs:
167
+ r.errors.append(f"{where}.languages must be a list of: *, {', '.join(sorted(ALL_GROUPS))}")
168
+ if not isinstance(name, str) or not name:
169
+ r.errors.append(f"{where}.name is required")
170
+ if message is not None and not isinstance(message, str):
171
+ r.errors.append(f"{where}.message must be a string")
172
+ if compiled is not None and isinstance(name, str) and name and valid_langs:
173
+ groups = ALL_GROUPS if "*" in langs else frozenset(langs)
174
+ custom.append(
175
+ {
176
+ "name": name,
177
+ "regex": compiled,
178
+ "groups": groups,
179
+ "message": message or f"Custom pattern '{name}' matched",
180
+ }
181
+ )
182
+ r.finish()
183
+ return {"disable": frozenset(disable), "ignore_paths": ignore_paths, "custom": tuple(custom)}
184
+
185
+ def evaluate(self, ctx: RuleContext, settings: RuleSettings) -> list[Finding]:
186
+ disable: frozenset[str] = settings.options["disable"]
187
+ ignore_paths: tuple[str, ...] = settings.options["ignore_paths"]
188
+ custom: tuple[dict[str, Any], ...] = settings.options["custom"]
189
+ findings: list[Finding] = []
190
+ for change in ctx.diff.files:
191
+ group = language_group(change.path)
192
+ if change.is_binary or group is None or matches_any(change.path, ignore_paths):
193
+ continue
194
+ in_tests = matches_any(change.path, DEFAULT_TEST_PATHS)
195
+ for line in change.added_lines():
196
+ if is_comment(line.content, group):
197
+ continue
198
+ dynamic = bool(_DYNAMIC.search(line.content))
199
+ for check in _CHECKS:
200
+ if check.check_id in disable:
201
+ continue
202
+ for pat in check.patterns:
203
+ if group not in pat.groups or not pat.regex.search(line.content):
204
+ continue
205
+ if pat.literal_safe and not dynamic and _LITERAL_ARG.search(line.content):
206
+ continue
207
+ findings.append(
208
+ self.finding(
209
+ settings,
210
+ check.check_id,
211
+ message=f"{check.title} in {change.path}",
212
+ explanation=check.explanation,
213
+ remediation=check.remediation,
214
+ file_path=change.path,
215
+ line=line.new_lineno,
216
+ evidence=clip(redact_secrets(line.content)),
217
+ confidence=Confidence.LOW
218
+ if in_tests
219
+ else Confidence.HIGH
220
+ if dynamic or check.check_id != "DG-DANGER-003"
221
+ else Confidence.MEDIUM,
222
+ key=f"{check.check_id}:{pat.regex.pattern}:{line.content.strip()}",
223
+ )
224
+ )
225
+ break
226
+ if "DG-DANGER-006" not in disable:
227
+ for item in custom:
228
+ if group in item["groups"] and item["regex"].search(line.content):
229
+ findings.append(
230
+ self.finding(
231
+ settings,
232
+ "DG-DANGER-006",
233
+ message=f"{item['message']} in {change.path}",
234
+ explanation="A custom dangerous pattern defined in the policy matched.",
235
+ remediation="Review the change against the policy that defines this pattern.",
236
+ file_path=change.path,
237
+ line=line.new_lineno,
238
+ evidence=clip(redact_secrets(line.content)),
239
+ confidence=Confidence.MEDIUM,
240
+ key=f"custom:{item['name']}:{line.content.strip()}",
241
+ )
242
+ )
243
+ if "DG-DANGER-004" not in disable:
244
+ findings.extend(self._auth_removals(ctx, settings, ignore_paths))
245
+ return findings
246
+
247
+ def _auth_removals(
248
+ self, ctx: RuleContext, settings: RuleSettings, ignore_paths: tuple[str, ...]
249
+ ) -> list[Finding]:
250
+ added: Counter[str] = Counter()
251
+ removed: Counter[str] = Counter()
252
+ first_removed: dict[str, tuple[str, int | None, str]] = {}
253
+ for change in ctx.diff.files:
254
+ group = language_group(change.path)
255
+ if change.is_binary or group not in _AUTH_GROUPS or matches_any(change.path, ignore_paths):
256
+ continue
257
+ for line in change.added_lines():
258
+ if not is_comment(line.content, group):
259
+ for m in _AUTH_MARKER.finditer(line.content):
260
+ added[re.sub(r"\s+", "", m.group(0)).lower()] += 1
261
+ if change.change_type is ChangeType.DELETED:
262
+ continue
263
+ for line in change.removed_lines():
264
+ if is_comment(line.content, group):
265
+ continue
266
+ for m in _AUTH_MARKER.finditer(line.content):
267
+ marker = re.sub(r"\s+", "", m.group(0)).lower()
268
+ removed[marker] += 1
269
+ first_removed.setdefault(marker, (change.path, line.old_lineno, line.content))
270
+ findings: list[Finding] = []
271
+ for marker, count in sorted(removed.items()):
272
+ if count > added[marker]:
273
+ path, lineno, content = first_removed[marker]
274
+ findings.append(
275
+ self.finding(
276
+ settings,
277
+ "DG-DANGER-004",
278
+ message=f"Authorization check removed in {path}: {marker}",
279
+ explanation=f"{count} occurrence(s) of this authentication/authorization "
280
+ f"marker were removed and only {added[marker]} added elsewhere in the diff.",
281
+ remediation="Confirm the endpoint or function is still protected, or restore the check.",
282
+ file_path=path,
283
+ line=lineno,
284
+ line_side="old",
285
+ evidence=clip(redact_secrets(content)),
286
+ confidence=Confidence.MEDIUM,
287
+ key=f"auth-removed:{marker}",
288
+ )
289
+ )
290
+ return findings