mcp-security-check 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 (47) hide show
  1. mcp_security/__init__.py +10 -0
  2. mcp_security/analyzers/__init__.py +4 -0
  3. mcp_security/analyzers/attack_paths.py +106 -0
  4. mcp_security/analyzers/capabilities.py +219 -0
  5. mcp_security/analyzers/permissions.py +57 -0
  6. mcp_security/analyzers/provenance.py +57 -0
  7. mcp_security/analyzers/secrets.py +159 -0
  8. mcp_security/cli.py +160 -0
  9. mcp_security/diff/__init__.py +3 -0
  10. mcp_security/diff/capability_diff.py +146 -0
  11. mcp_security/discovery/files.py +93 -0
  12. mcp_security/discovery/mcp.py +166 -0
  13. mcp_security/engine.py +153 -0
  14. mcp_security/github/__init__.py +3 -0
  15. mcp_security/github/annotations.py +42 -0
  16. mcp_security/model/__init__.py +13 -0
  17. mcp_security/model/capability.py +91 -0
  18. mcp_security/model/component.py +47 -0
  19. mcp_security/model/finding.py +99 -0
  20. mcp_security/model/report.py +119 -0
  21. mcp_security/output/__init__.py +5 -0
  22. mcp_security/output/markdown.py +105 -0
  23. mcp_security/output/sarif.py +82 -0
  24. mcp_security/output/terminal.py +59 -0
  25. mcp_security/parsers/__init__.py +4 -0
  26. mcp_security/parsers/json_parser.py +219 -0
  27. mcp_security/parsers/skill_parser.py +18 -0
  28. mcp_security/parsers/yaml_parser.py +80 -0
  29. mcp_security/policy.py +134 -0
  30. mcp_security/redaction.py +133 -0
  31. mcp_security/rules/__init__.py +66 -0
  32. mcp_security/rules/base.py +66 -0
  33. mcp_security/rules/combinations.py +111 -0
  34. mcp_security/rules/credentials.py +159 -0
  35. mcp_security/rules/dangerous_tools.py +270 -0
  36. mcp_security/rules/filesystem.py +43 -0
  37. mcp_security/rules/network.py +43 -0
  38. mcp_security/rules/shell.py +47 -0
  39. mcp_security/scoring/__init__.py +4 -0
  40. mcp_security/scoring/risk.py +75 -0
  41. mcp_security/scoring/trust.py +23 -0
  42. mcp_security_check-0.1.0.dist-info/METADATA +398 -0
  43. mcp_security_check-0.1.0.dist-info/RECORD +47 -0
  44. mcp_security_check-0.1.0.dist-info/WHEEL +5 -0
  45. mcp_security_check-0.1.0.dist-info/entry_points.txt +2 -0
  46. mcp_security_check-0.1.0.dist-info/licenses/LICENSE +21 -0
  47. mcp_security_check-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,10 @@
1
+ """MCP Security Check for GitHub.
2
+
3
+ A GitHub-native security analysis engine for Model Context Protocol (MCP)
4
+ configurations. Detects dangerous capabilities, permission escalation,
5
+ and potential attack paths before a pull request is merged.
6
+
7
+ The engine works offline and never executes any of the content it scans.
8
+ """
9
+
10
+ __version__ = "0.1.0"
@@ -0,0 +1,4 @@
1
+ from mcp_security.analyzers.capabilities import extract_capabilities
2
+ from mcp_security.analyzers.attack_paths import detect_attack_paths
3
+
4
+ __all__ = ["extract_capabilities", "detect_attack_paths"]
@@ -0,0 +1,106 @@
1
+ """Attack path detection.
2
+
3
+ Evaluates *combinations* of capabilities present on a component (not just
4
+ individual capabilities) and reports realistic attack chains. This is
5
+ distinct from single-capability rules: a component can be "safe" per
6
+ individual rules yet still expose a dangerous combination.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import List, Set
13
+
14
+ from mcp_security.model.finding import Severity
15
+ from mcp_security.model.report import AttackPath
16
+
17
+ # Each attack path definition: the set of capability ids that must all be
18
+ # present (on the same component) for the chain to fire, an ordered chain
19
+ # for display purposes, severity, and a human explanation.
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class AttackPathDefinition:
24
+ path_id: str
25
+ required: frozenset
26
+ chain: tuple
27
+ severity: Severity
28
+ description: str
29
+ remediation: str
30
+
31
+
32
+ ATTACK_PATH_DEFINITIONS: List[AttackPathDefinition] = [
33
+ AttackPathDefinition(
34
+ path_id="AP001",
35
+ required=frozenset({"secrets.read", "network.external"}),
36
+ chain=("secrets.read", "network.external"),
37
+ severity=Severity.CRITICAL,
38
+ description="Potential secret/data exfiltration path: the component can read secrets and also reach external networks.",
39
+ remediation="Restrict network access to required endpoints only, or remove secret access if not strictly needed.",
40
+ ),
41
+ AttackPathDefinition(
42
+ path_id="AP002",
43
+ required=frozenset({"filesystem.read", "network.external"}),
44
+ chain=("filesystem.read", "network.external"),
45
+ severity=Severity.HIGH,
46
+ description="Potential local data exfiltration path: the component can read local files and also reach external networks.",
47
+ remediation="Scope filesystem access to the minimum required directory, or restrict network egress.",
48
+ ),
49
+ AttackPathDefinition(
50
+ path_id="AP003",
51
+ required=frozenset({"filesystem.write", "shell.execute"}),
52
+ chain=("filesystem.write", "shell.execute"),
53
+ severity=Severity.CRITICAL,
54
+ description="Potential code/config tampering path: the component can write files and execute shell commands, enabling self-modifying or persistence behavior.",
55
+ remediation="Avoid combining shell execution with unrestricted filesystem write; sandbox or split responsibilities across components.",
56
+ ),
57
+ AttackPathDefinition(
58
+ path_id="AP004",
59
+ required=frozenset({"shell.execute", "network.external"}),
60
+ chain=("shell.execute", "network.external"),
61
+ severity=Severity.CRITICAL,
62
+ description="Potential remote payload execution/exfiltration path: the component can execute shell commands and reach external networks.",
63
+ remediation="Remove shell execution capability if not required, or restrict network egress to a strict allowlist.",
64
+ ),
65
+ AttackPathDefinition(
66
+ path_id="AP005",
67
+ required=frozenset({"package.install", "package.execute"}),
68
+ chain=("package.install", "package.execute"),
69
+ severity=Severity.HIGH,
70
+ description="Potential supply-chain execution path: the component can install and then execute packages, enabling arbitrary third-party code execution.",
71
+ remediation="Pin dependency versions and verify package sources before allowing install+execute in the same component.",
72
+ ),
73
+ AttackPathDefinition(
74
+ path_id="AP006",
75
+ required=frozenset({"credentials.read", "network.external"}),
76
+ chain=("credentials.read", "network.external"),
77
+ severity=Severity.CRITICAL,
78
+ description="Potential credential exfiltration path: the component can read credential material and also reach external networks.",
79
+ remediation="Remove credential access if not required, or isolate the component from external network egress.",
80
+ ),
81
+ AttackPathDefinition(
82
+ path_id="AP007",
83
+ required=frozenset({"filesystem.write", "network.external", "shell.execute"}),
84
+ chain=("filesystem.write", "shell.execute", "network.external"),
85
+ severity=Severity.CRITICAL,
86
+ description="Critical multi-step attack path: the component can write files, execute shell commands, and reach external networks -- sufficient primitives for a full compromise chain.",
87
+ remediation="Treat this combination as a hard blocker; require explicit security review before allowing all three capabilities together.",
88
+ ),
89
+ ]
90
+
91
+
92
+ def detect_attack_paths(capability_ids: Set[str]) -> List[AttackPath]:
93
+ """Return attack paths whose required capability set is a subset of ``capability_ids``."""
94
+ results: List[AttackPath] = []
95
+ for definition in ATTACK_PATH_DEFINITIONS:
96
+ if definition.required.issubset(capability_ids):
97
+ results.append(
98
+ AttackPath(
99
+ path_id=definition.path_id,
100
+ severity=definition.severity,
101
+ chain=list(definition.chain),
102
+ description=definition.description,
103
+ remediation=definition.remediation,
104
+ )
105
+ )
106
+ return results
@@ -0,0 +1,219 @@
1
+ """Capability extraction.
2
+
3
+ Turns a normalized :class:`Component` (produced by the parsers) into a list
4
+ of :class:`Capability` objects. This is heuristic by nature -- MCP
5
+ configuration does not universally declare a machine-readable capability
6
+ list, so we infer capabilities from command names, arguments, declared
7
+ tools, and explicit permission blocks when present.
8
+
9
+ Mandatory principle: unknown/unrecognized data is simply not translated
10
+ into a capability. It must never be treated as automatically dangerous.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ipaddress
16
+ import re
17
+ from typing import Dict, List
18
+ from urllib.parse import urlsplit
19
+
20
+ from mcp_security.model.capability import Capability
21
+ from mcp_security.model.component import Component
22
+
23
+ # Command/binary names that imply shell.execute when used as the launcher
24
+ # or appear as an argument token (e.g. "sh -c", "bash -c").
25
+ SHELL_INDICATORS = {"sh", "bash", "zsh", "cmd", "cmd.exe", "powershell", "pwsh"}
26
+
27
+ # Command/binary names that imply dynamic code execution.
28
+ CODE_EXEC_INDICATORS = {"python", "python3", "node", "ruby", "perl", "eval"}
29
+
30
+ # Package manager commands that imply package.install.
31
+ PACKAGE_INSTALL_INDICATORS = {"pip", "pip3", "npm", "npx", "yarn", "pnpm", "cargo", "gem"}
32
+
33
+ # Explicit "install" style subcommands/flags, used alongside the above.
34
+ INSTALL_TOKENS = {"install", "add", "i"}
35
+
36
+ # Well-known environment variable name fragments that indicate secret/
37
+ # credential material is being read by the component.
38
+ SECRET_ENV_PATTERNS = (
39
+ re.compile(r"(?i)token"),
40
+ re.compile(r"(?i)secret"),
41
+ re.compile(r"(?i)api[_-]?key"),
42
+ re.compile(r"(?i)password"),
43
+ re.compile(r"(?i)credential"),
44
+ re.compile(r"(?i)auth"),
45
+ )
46
+
47
+ # Permission-string -> capability mapping for explicit "permissions" blocks.
48
+ PERMISSION_STRING_MAP: Dict[str, str] = {
49
+ "filesystem:read": "filesystem.read",
50
+ "filesystem:write": "filesystem.write",
51
+ "filesystem:delete": "filesystem.delete",
52
+ "shell:execute": "shell.execute",
53
+ "network:local": "network.local",
54
+ "network:external": "network.external",
55
+ "network:unrestricted": "network.unrestricted",
56
+ "secrets:read": "secrets.read",
57
+ "credentials:read": "credentials.read",
58
+ "env:read": "environment.read",
59
+ "github:read": "github.read",
60
+ "github:write": "github.write",
61
+ "github:admin": "github.admin",
62
+ }
63
+
64
+
65
+ def extract_capabilities(component: Component) -> List[Capability]:
66
+ """Return the list of capabilities inferred for ``component``.
67
+
68
+ Does not mutate ``component``; the caller is responsible for assigning
69
+ the result back to ``component.capabilities``.
70
+ """
71
+ raw = component.raw or {}
72
+ capabilities: List[Capability] = []
73
+
74
+ capabilities.extend(_from_command_and_args(raw))
75
+ capabilities.extend(_from_url(raw))
76
+ capabilities.extend(_from_env(raw))
77
+ capabilities.extend(_from_tools(raw))
78
+ capabilities.extend(_from_permissions(raw))
79
+
80
+ # Deduplicate while preserving order (same id + target).
81
+ seen = set()
82
+ deduped: List[Capability] = []
83
+ for cap in capabilities:
84
+ key = (cap.id, cap.target)
85
+ if key not in seen:
86
+ seen.add(key)
87
+ deduped.append(cap)
88
+ return deduped
89
+
90
+
91
+ def _tokenize_command(raw: Dict) -> List[str]:
92
+ command = raw.get("command")
93
+ args = raw.get("args") or []
94
+ tokens: List[str] = []
95
+ if isinstance(command, str):
96
+ tokens.append(command)
97
+ if isinstance(args, list):
98
+ tokens.extend(str(a) for a in args)
99
+ return tokens
100
+
101
+
102
+ def _basename(token: str) -> str:
103
+ return token.replace("\\", "/").split("/")[-1].lower()
104
+
105
+
106
+ def _from_command_and_args(raw: Dict) -> List[Capability]:
107
+ caps: List[Capability] = []
108
+ tokens = _tokenize_command(raw)
109
+ basenames = [_basename(t) for t in tokens]
110
+
111
+ if any(b in SHELL_INDICATORS for b in basenames):
112
+ caps.append(Capability("shell", "execute", target="local"))
113
+
114
+ if any(b in CODE_EXEC_INDICATORS for b in basenames):
115
+ caps.append(Capability("code", "execute", target="local"))
116
+
117
+ if any(b in PACKAGE_INSTALL_INDICATORS for b in basenames):
118
+ if any(t.lower() in INSTALL_TOKENS for t in tokens):
119
+ caps.append(Capability("package", "install"))
120
+ else:
121
+ caps.append(Capability("package", "execute"))
122
+
123
+ # A local filesystem-backed MCP server process is, at minimum,
124
+ # implicitly able to read its working directory. We only infer this
125
+ # for servers launched via a local command (not remote/url-based).
126
+ if raw.get("command") and not raw.get("url"):
127
+ caps.append(Capability("filesystem", "read", target="workspace"))
128
+
129
+ return caps
130
+
131
+
132
+ def _from_url(raw: Dict) -> List[Capability]:
133
+ url = raw.get("url")
134
+ if not isinstance(url, str) or not url:
135
+ return []
136
+ if not url.lower().startswith(("http://", "https://")):
137
+ return []
138
+
139
+ # Classify by the parsed hostname, never by substring: an attacker-controlled
140
+ # host such as localhost.attacker.example must remain external.
141
+ try:
142
+ hostname = urlsplit(url).hostname
143
+ except ValueError:
144
+ hostname = None
145
+ normalized_host = (hostname or "").rstrip(".").lower()
146
+ is_local = normalized_host == "localhost" or normalized_host.endswith(".localhost")
147
+ if not is_local and normalized_host:
148
+ try:
149
+ is_local = ipaddress.ip_address(normalized_host).is_loopback
150
+ except ValueError:
151
+ pass
152
+
153
+ if is_local:
154
+ return [Capability("network", "local", target=url)]
155
+ return [Capability("network", "external", target=url)]
156
+
157
+
158
+ def _from_env(raw: Dict) -> List[Capability]:
159
+ env = raw.get("env") or {}
160
+ caps: List[Capability] = []
161
+ if not isinstance(env, dict):
162
+ return caps
163
+ for key in env.keys():
164
+ if any(pattern.search(str(key)) for pattern in SECRET_ENV_PATTERNS):
165
+ caps.append(Capability("secrets", "read", target=str(key)))
166
+ return caps
167
+
168
+
169
+ def _from_tools(raw: Dict) -> List[Capability]:
170
+ tools = raw.get("tools") or []
171
+ caps: List[Capability] = []
172
+ if not isinstance(tools, list):
173
+ return caps
174
+ for tool in tools:
175
+ tool_name = tool if isinstance(tool, str) else (tool.get("name") if isinstance(tool, dict) else None)
176
+ if not tool_name:
177
+ continue
178
+ lowered = str(tool_name).lower()
179
+ if any(k in lowered for k in ("shell", "exec", "command", "run")):
180
+ caps.append(Capability("shell", "execute", target=str(tool_name)))
181
+ if any(k in lowered for k in ("browser", "navigate")):
182
+ caps.append(Capability("browser", "navigate", target=str(tool_name)))
183
+ if "download" in lowered:
184
+ caps.append(Capability("browser", "download", target=str(tool_name)))
185
+ if any(k in lowered for k in ("write_file", "writefile", "file_write")):
186
+ caps.append(Capability("filesystem", "write", target=str(tool_name)))
187
+ if any(k in lowered for k in ("delete_file", "deletefile", "file_delete", "rm")):
188
+ caps.append(Capability("filesystem", "delete", target=str(tool_name)))
189
+ return caps
190
+
191
+
192
+ def _from_permissions(raw: Dict) -> List[Capability]:
193
+ permissions = raw.get("permissions")
194
+ caps: List[Capability] = []
195
+ if permissions is None:
196
+ return caps
197
+
198
+ entries: List[str] = []
199
+ if isinstance(permissions, list):
200
+ entries = [str(p) for p in permissions]
201
+ elif isinstance(permissions, dict):
202
+ for key, value in permissions.items():
203
+ if value:
204
+ entries.append(str(key))
205
+
206
+ for entry in entries:
207
+ normalized = entry.strip().lower()
208
+ mapped = PERMISSION_STRING_MAP.get(normalized)
209
+ if mapped:
210
+ type_, action = mapped.split(".", 1)
211
+ caps.append(Capability(type_, action, target="declared"))
212
+ elif "." in normalized:
213
+ # Already looks like a dotted capability id, e.g. "filesystem.write".
214
+ type_, _, action = normalized.partition(".")
215
+ caps.append(Capability(type_, action, target="declared"))
216
+ # Unrecognized permission strings are intentionally NOT translated
217
+ # into a capability -- unknown data must not be treated as
218
+ # automatically dangerous.
219
+ return caps
@@ -0,0 +1,57 @@
1
+ """Capability risk tiering.
2
+
3
+ Provides a single, shared mapping from capability id to an intrinsic risk
4
+ tier. Used by the rule engine (for single-capability findings), the diff
5
+ engine (to flag newly introduced *high-risk* capabilities specifically),
6
+ and scoring.
7
+
8
+ This mapping is intentionally conservative and documented so severity is
9
+ not arbitrary -- see README "Risk scoring" section for rationale.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from mcp_security.model.finding import Severity
15
+
16
+ # Capability id -> intrinsic severity if this capability appears at all,
17
+ # independent of combinations. Capabilities not listed here are treated as
18
+ # informational (no automatic finding) -- unknown/uncommon capabilities are
19
+ # not assumed dangerous.
20
+ CAPABILITY_BASE_SEVERITY = {
21
+ "shell.execute": Severity.HIGH,
22
+ "code.execute": Severity.HIGH,
23
+ "filesystem.write": Severity.HIGH,
24
+ "filesystem.delete": Severity.HIGH,
25
+ "network.unrestricted": Severity.HIGH,
26
+ "network.external": Severity.MEDIUM,
27
+ "secrets.read": Severity.MEDIUM,
28
+ "credentials.read": Severity.MEDIUM,
29
+ "environment.read": Severity.LOW,
30
+ "github.admin": Severity.HIGH,
31
+ "github.write": Severity.MEDIUM,
32
+ "package.install": Severity.MEDIUM,
33
+ "package.execute": Severity.MEDIUM,
34
+ "browser.execute": Severity.MEDIUM,
35
+ "browser.download": Severity.LOW,
36
+ "filesystem.read": Severity.INFO,
37
+ "network.local": Severity.INFO,
38
+ "github.read": Severity.INFO,
39
+ "browser.navigate": Severity.INFO,
40
+ }
41
+
42
+ # Capabilities considered "high-risk" for the purposes of capability-diff
43
+ # escalation reporting (MSC015 - New High-Risk Capability), regardless of
44
+ # their exact base severity above.
45
+ HIGH_RISK_CAPABILITIES = {
46
+ cap_id
47
+ for cap_id, severity in CAPABILITY_BASE_SEVERITY.items()
48
+ if severity in (Severity.CRITICAL, Severity.HIGH)
49
+ }
50
+
51
+
52
+ def base_severity_for(capability_id: str) -> Severity:
53
+ return CAPABILITY_BASE_SEVERITY.get(capability_id, Severity.INFO)
54
+
55
+
56
+ def is_high_risk(capability_id: str) -> bool:
57
+ return capability_id in HIGH_RISK_CAPABILITIES
@@ -0,0 +1,57 @@
1
+ """Basic offline trust/provenance signals.
2
+
3
+ This is deliberately minimal for v0.1: it only inspects information already
4
+ present locally (no network calls). It must never be presented as proof
5
+ that a component is trustworthy -- only as informational signals that
6
+ *reduce confidence* when absent, separate from security risk.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import List
13
+
14
+ from mcp_security.model.component import Component
15
+
16
+
17
+ @dataclass
18
+ class ProvenanceSignal:
19
+ name: str
20
+ present: bool
21
+ note: str
22
+
23
+
24
+ def evaluate_provenance(component: Component) -> List[ProvenanceSignal]:
25
+ raw = component.raw or {}
26
+ metadata = component.metadata or {}
27
+ signals: List[ProvenanceSignal] = []
28
+
29
+ signals.append(
30
+ ProvenanceSignal(
31
+ name="source_locality",
32
+ present=component.source == "local",
33
+ note="Component is launched from a local command" if component.source == "local"
34
+ else "Component is fetched from a remote URL",
35
+ )
36
+ )
37
+
38
+ publisher = metadata.get("publisher")
39
+ signals.append(
40
+ ProvenanceSignal(
41
+ name="publisher_declared",
42
+ present=bool(publisher),
43
+ note=f"Publisher declared: {publisher}" if publisher else "No publisher metadata declared",
44
+ )
45
+ )
46
+
47
+ version = metadata.get("version")
48
+ pinned = bool(version) and version not in ("latest", "*")
49
+ signals.append(
50
+ ProvenanceSignal(
51
+ name="version_pinned",
52
+ present=pinned,
53
+ note=f"Version pinned: {version}" if pinned else "No pinned version declared (or uses 'latest')",
54
+ )
55
+ )
56
+
57
+ return signals
@@ -0,0 +1,159 @@
1
+ """Heuristics for hardcoded secret-like literal values in configuration.
2
+
3
+ This is separate from capability-based secret *access* detection (which
4
+ looks at env var names, see analyzers.capabilities). This module instead
5
+ flags values that look like an actual secret was hardcoded into the
6
+ configuration file itself.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import Dict, List, Tuple
13
+ from urllib.parse import parse_qsl, unquote, urlsplit
14
+
15
+ # Conservative heuristic: long, high-looking-entropy alphanumeric tokens.
16
+ # False positives are possible (e.g. long hashes); this is informational,
17
+ # not an automatic critical finding.
18
+ _TOKEN_PATTERN = re.compile(r"^[A-Za-z0-9_\-/+=]{24,}$")
19
+
20
+
21
+ _SENSITIVE_SECRET_KEY_EXACT = {
22
+ "auth", "authorization", "key", "secret", "token", "password", "passwd",
23
+ "credential", "credentials", "cookie", "setcookie", "clientsecret",
24
+ "apikey", "accesskey", "accesskeyid", "privatekey", "secretaccesskey",
25
+ }
26
+ _SENSITIVE_SECRET_KEY_SUFFIXES = (
27
+ "authorization", "accesstoken", "refreshtoken", "idtoken", "token",
28
+ "clientsecret", "secret", "password", "passwd", "credentials",
29
+ "credential", "apikey", "accesskeyid", "accesskey", "privatekey",
30
+ "secretaccesskey", "cookie",
31
+ )
32
+
33
+
34
+ def _is_sensitive_secret_key(key: str) -> bool:
35
+ """Check the field name rather than flagging arbitrary short values."""
36
+ lowered = key.strip().lower()
37
+ normalized = re.sub(r"[^a-z0-9]", "", lowered)
38
+ if normalized in _SENSITIVE_SECRET_KEY_EXACT:
39
+ return True
40
+ if normalized.endswith(_SENSITIVE_SECRET_KEY_SUFFIXES):
41
+ return True
42
+ # Generic KEY is sensitive only when it is a standalone name or a
43
+ # separator-delimited suffix; this avoids false positives like "monkey".
44
+ return bool(re.search(r"(?:^|[_-])key$", lowered))
45
+
46
+
47
+ def _is_placeholder_or_reference(value: str) -> bool:
48
+ """Whether a value is clearly a placeholder or runtime reference."""
49
+ candidate = unquote(value).strip().strip("\\\"'").strip().lower()
50
+ if not candidate or candidate.startswith("$") or "${" in candidate:
51
+ return True
52
+ if candidate in {
53
+ "changeme", "example", "placeholder", "todo", "none", "null",
54
+ "undefined", "redacted", "your-token", "your_api_key",
55
+ "your-api-key", "replace_me", "replace-with-token",
56
+ }:
57
+ return True
58
+ return candidate.startswith(("your_", "your-", "replace_", "replace-"))
59
+
60
+
61
+ def find_hardcoded_secret_like_values(values: Dict) -> List[Tuple[str, str]]:
62
+ """Return key/value pairs whose string value resembles a hardcoded secret.
63
+
64
+ Sensitive field names lower the detection threshold because even short
65
+ values can be valid credentials. Runtime references and obvious placeholders
66
+ are excluded before either the key-name or token-shape heuristic runs.
67
+ """
68
+ findings: List[Tuple[str, str]] = []
69
+ if not isinstance(values, dict):
70
+ return findings
71
+ for key, value in values.items():
72
+ if not isinstance(value, str) or not value.strip():
73
+ continue
74
+ if _is_placeholder_or_reference(value):
75
+ continue
76
+
77
+ candidate = value.strip()
78
+ # Remote MCP configs often place a token in "Authorization: Bearer ...".
79
+ # Inspect the token portion but keep the original value for redaction length.
80
+ parts = candidate.split(None, 1)
81
+ if len(parts) == 2 and parts[0].lower() in ("bearer", "basic"):
82
+ candidate = parts[1].strip()
83
+ if not candidate or _is_placeholder_or_reference(candidate):
84
+ continue
85
+
86
+ if _TOKEN_PATTERN.fullmatch(candidate) or _is_sensitive_secret_key(str(key)):
87
+ findings.append((str(key), value))
88
+ return findings
89
+
90
+
91
+ _SENSITIVE_URL_KEY_MARKERS = (
92
+ "accesstoken", "refreshtoken", "token", "clientsecret", "secret",
93
+ "password", "passwd", "apikey", "credential", "authorization",
94
+ "signature", "privatekey", "accesskey",
95
+ )
96
+
97
+
98
+ def _is_sensitive_url_key(key: str) -> bool:
99
+ """Match credential-bearing parameter names without substring false positives."""
100
+ normalized = re.sub(r"[^a-z0-9]", "", key.lower())
101
+
102
+ # Exact names cover generic fields; suffixes cover common namespaced forms
103
+ # such as github_token, client_secret, and X-Amz-Signature.
104
+ exact_names = {
105
+ "auth", "authkey", "key", "sig", "secret", "token", "password",
106
+ "passwd", "credential", "credentials", "authorization", "signature",
107
+ }
108
+ if normalized in exact_names:
109
+ return True
110
+
111
+ sensitive_suffixes = (
112
+ "accesstoken", "refreshtoken", "idtoken", "token",
113
+ "clientsecret", "secret", "password", "passwd",
114
+ "apikey", "credential", "authorization", "signature",
115
+ "privatekey", "accesskey",
116
+ )
117
+ if normalized.endswith(sensitive_suffixes):
118
+ return True
119
+
120
+ # Preserve separator-based key forms (api_key, subscription-key) without
121
+ # treating unrelated words ending in "key" (for example, "monkey") as secrets.
122
+ return bool(re.search(r"(?i)(?:^|[_-])key(?:$|[_-])", key))
123
+
124
+
125
+ def find_hardcoded_url_credentials(url: str) -> List[Tuple[str, str]]:
126
+ """Find literal credentials embedded in URL userinfo, query, or fragment.
127
+
128
+ Returned values are internal-only, for reporting redacted lengths. Never
129
+ interpolate a returned value into an output message.
130
+ """
131
+ findings: List[Tuple[str, str]] = []
132
+ if not isinstance(url, str) or not url.strip():
133
+ return findings
134
+ try:
135
+ parts = urlsplit(url.strip())
136
+ if parts.password:
137
+ password = unquote(parts.password)
138
+ if not _is_placeholder_or_reference(password):
139
+ findings.append(("url.userinfo.password", password))
140
+ elif parts.username:
141
+ # A username is not automatically a secret; flag it only if it
142
+ # looks like a token rather than a normal account name.
143
+ username = unquote(parts.username)
144
+ if not _is_placeholder_or_reference(username) and _TOKEN_PATTERN.fullmatch(username):
145
+ findings.append(("url.userinfo.username", username))
146
+
147
+ for location, encoded_fields in (("query", parts.query), ("fragment", parts.fragment)):
148
+ for key, value in parse_qsl(encoded_fields, keep_blank_values=True):
149
+ if not _is_sensitive_url_key(key) or not value:
150
+ continue
151
+ if _is_placeholder_or_reference(value):
152
+ continue
153
+ safe_key = re.sub(r"[^A-Za-z0-9_.-]", "_", key)[:64] or "credential"
154
+ findings.append((f"url.{location}.{safe_key}", unquote(value)))
155
+ except (ValueError, UnicodeError):
156
+ # Malformed URLs should not crash the audit; parser/schema validation
157
+ # handles their validity separately.
158
+ return findings
159
+ return findings