Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
291 lines (236 loc) · 8.8 KB
/
Copy pathutils.py
File metadata and controls
291 lines (236 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""
工具函数模块 - 通用工具函数集合
提供:
- 熵值计算 (LRU缓存)
- Key/URL 过滤检测
- 字符串处理
- 文件过滤
"""
import ipaddress
import math
import re
import socket
from collections import Counter
from functools import lru_cache
from typing import Tuple
from urllib.parse import urlparse
# ============================================================================
# 常量定义
# ============================================================================
# 熵值阈值
ENTROPY_THRESHOLD = 3.8
# 测试 Key 关键词。scanner 导入本模块后会把这份名单替换成
# 已合并 config.yaml 的同一列表,过滤逻辑只保留这一处实现。
TEST_KEY_PATTERNS = [
'test', 'demo', 'example', 'sample', 'fake', 'dummy', 'placeholder',
'xxx', 'your_', 'your-', '<your', '{your', 'abcdef', '123456',
'insert', 'replace', 'xxxxxx', 'aaaaaa',
'dev_', 'dev-', 'staging', 'sandbox', 'tutorial', 'workshop',
'playground', 'temp_', 'tmp_', 'mock_', 'stub_',
'changeme', 'fixme', 'todo', 'secret', 'password', 'credential',
'redacted', 'hidden', 'masked', 'obfuscated', 'censored',
'null', 'none', 'undefined', 'empty', 'blank',
'default', 'template', 'boilerplate', 'skeleton',
'api_key_here', 'your_api_key', 'enter_key', 'put_key',
'add_your', 'fill_in', 'replace_with', 'insert_your',
]
# 域名黑名单
DOMAIN_BLACKLIST = [
'localhost', '127.0.0.1', '0.0.0.0', 'example.com', 'test.com',
'my-api', 'your-api', 'xxx', 'placeholder', 'fake', 'dummy', 'sample', 'mock',
'staging.', 'sandbox.', 'dev.', 'demo.', 'test.', '.local', '.internal',
'ngrok.io', 'localtunnel',
]
# 文件过滤配置
MAX_FILE_SIZE_KB = 500
BLOCKED_EXTENSIONS = {
'.lock', '.min.js', '.min.css', '.map', '.md', '.rst', '.txt',
'.html', '.htm', '.css', '.scss', '.less', '.svg', '.png', '.jpg',
'.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.eot',
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.zip', '.tar', '.gz', '.rar',
'.exe', '.dll', '.so', '.dylib', '.pyc', '.pyo', '.class', '.ipynb', '.csv',
}
PATH_BLACKLIST = [
'/test/', '/tests/', '/__tests__/', '/spec/', '/specs/',
'/mock/', '/mocks/', '/__mocks__/', '/fixture/', '/fixtures/',
'/example/', '/examples/', '/sample/', '/samples/', '/demo/', '/demos/',
'/doc/', '/docs/', '/vendor/', '/node_modules/', '/venv/', '/.venv/',
'/dist/', '/build/', '/out/', '/coverage/', '/.github/ISSUE_TEMPLATE/',
'/sandbox/', '/playground/', '/staging/', '/tutorial/', '/tutorials/',
'/workshop/', '/workshops/', '/boilerplate/', '/starter/',
]
# ============================================================================
# 工具函数
# ============================================================================
@lru_cache(maxsize=4096)
def calculate_entropy(s: str) -> float:
"""计算字符串香农熵 (带 LRU 缓存)"""
if not s:
return 0.0
freq = Counter(s)
length = len(s)
return -sum((c / length) * math.log2(c / length) for c in freq.values() if c > 0)
@lru_cache(maxsize=2048)
def is_test_key(api_key: str) -> bool:
"""检测是否为测试 Key (带 LRU 缓存)"""
key_lower = api_key.lower()
return any(p in key_lower for p in TEST_KEY_PATTERNS)
@lru_cache(maxsize=1024)
def is_blacklisted_url(url: str) -> bool:
"""检测 URL 是否在黑名单中 (带 LRU 缓存)"""
if not url:
return False
url_lower = url.lower()
return any(b in url_lower for b in DOMAIN_BLACKLIST)
def mask_key(api_key: str) -> str:
"""遮蔽 API Key"""
if len(api_key) <= 12:
return api_key[:4] + "..." + api_key[-4:]
return api_key[:8] + "..." + api_key[-4:]
_REDACT = True
_KEYISH = re.compile(
r"(sk-[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{20,}|xai-[A-Za-z0-9]{20,}"
r"|ghp_[A-Za-z0-9]{20,}|gsk_[A-Za-z0-9]{20,}|hf_[A-Za-z0-9]{20,}"
r"|sk-ant-[A-Za-z0-9_-]{16,}|sk-or-v1-[A-Za-z0-9]{16,})"
)
def set_redact(enabled: bool) -> None:
global _REDACT
_REDACT = bool(enabled)
def redact_enabled() -> bool:
return _REDACT
def redact_message(text: str) -> str:
if not text or not _REDACT:
return text
return _KEYISH.sub(lambda match: mask_key(match.group(0)), text)
def install_log_redact() -> None:
"""Strip key-shaped tokens from loguru messages. Default on."""
from loguru import logger
def _patch(record):
record["message"] = redact_message(record["message"])
logger.configure(patcher=_patch)
def should_skip_file(file_path: str, file_size: int = 0) -> Tuple[bool, str]:
"""检查文件是否应该跳过"""
file_path_lower = file_path.lower()
# 文件大小检查
if file_size > 0 and file_size > MAX_FILE_SIZE_KB * 1024:
return True, f"file_too_large:{file_size // 1024}KB"
# 路径黑名单
for bp in PATH_BLACKLIST:
if bp in file_path_lower:
return True, f"path_blacklist:{bp}"
# 文件后缀检查
ext = ''
if '.' in file_path:
if file_path_lower.endswith('.min.js'):
ext = '.min.js'
elif file_path_lower.endswith('.min.css'):
ext = '.min.css'
else:
ext = '.' + file_path.rsplit('.', 1)[-1].lower()
if ext in BLOCKED_EXTENSIONS:
return True, f"blocked_ext:{ext}"
# 重要文件检查
important_files = ['dockerfile', '.env', 'config', 'secret', 'credential']
file_name = file_path.rsplit('/', 1)[-1].lower() if '/' in file_path else file_path.lower()
if any(imp in file_name for imp in important_files):
return False, ""
return False, ""
def has_sequential_chars(s: str, min_len: int = 6) -> bool:
"""检测连续递增/递减字符"""
if len(s) < min_len:
return False
count = 1
for i in range(1, len(s)):
if ord(s[i]) == ord(s[i - 1]) + 1 or ord(s[i]) == ord(s[i - 1]) - 1:
count += 1
if count >= min_len:
return True
else:
count = 1
return False
# 文档站和示例页,配对到的地址不能拿去验证。
_RELAY_DOC_MARKERS = (
"docs.djangoproject.com",
"docs.python.org",
"developer.mozilla.org",
"stackoverflow.com",
"themoviedb.org",
"prisma.io",
"pris.ly",
"every.to",
"makersuite.google.com",
"/settings",
"/ref/",
"/docs/",
"/guide",
)
_RELAY_HOST_SUFFIXES = (".local", ".internal", ".corp", ".lan", ".home")
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
def relay_url_is_allowed(base_url: str) -> bool:
"""验证请求能不能打到这个中转地址。空地址表示稍后用平台默认值。"""
if not base_url:
return True
parsed = urlparse(base_url)
host = (parsed.hostname or "").strip("[]").lower()
scheme = (parsed.scheme or "").lower()
if scheme not in ("http", "https"):
return False
if scheme == "http" and host not in _LOOPBACK_HOSTS:
return False
if any(host.endswith(suffix) for suffix in _RELAY_HOST_SUFFIXES):
return False
if not host_is_safe_to_contact(host):
return False
url_lower = base_url.lower()
return not any(marker in url_lower for marker in _RELAY_DOC_MARKERS)
def host_is_safe_to_contact(host: str) -> bool:
"""
验证请求只能打到公网地址。
字面量私有、链路本地、保留和元数据地址直接拒绝。
域名会解析出全部地址,任一落在这些范围里就拒绝。
localhost 和 127.0.0.1 保留给本机中转调试。
"""
if not host:
return False
normalized = host.strip("[]").lower().rstrip(".")
if normalized in ("localhost", "127.0.0.1", "::1"):
return True
def _blocked(ip: "ipaddress._BaseAddress") -> bool:
return (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
)
try:
return not _blocked(ipaddress.ip_address(normalized))
except ValueError:
pass
try:
records = socket.getaddrinfo(normalized, None)
except socket.gaierror:
return False
if not records:
return False
for record in records:
try:
address = ipaddress.ip_address(record[4][0])
except ValueError:
return False
if _blocked(address):
return False
return True
def clear_caches():
"""清理所有 LRU 缓存"""
calculate_entropy.cache_clear()
is_test_key.cache_clear()
is_blacklisted_url.cache_clear()
def get_cache_stats() -> dict:
"""获取缓存统计信息"""
return {
"entropy": calculate_entropy.cache_info()._asdict(),
"test_key": is_test_key.cache_info()._asdict(),
"blacklist_url": is_blacklisted_url.cache_info()._asdict(),
}