sycommon-python-lib 0.2.12a12__py3-none-any.whl → 0.2.12a14__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.
@@ -134,6 +134,7 @@ class TeamConfig(BaseModel):
134
134
  model_tier: str = "external" # "external"|"internal";internal 时跳过敏感检测
135
135
  sensitive_guard: bool = True # 是否启用敏感信息检测守卫
136
136
  internal_model_name: Optional[str] = None # 敏感降级目标内部模型名(应用层透传)
137
+ sensitive_detector_model_name: Optional[str] = None # 敏感检测分类器专用模型名(与降级目标解耦;None 回退 internal_model_name)
137
138
  sensitive_detect_prompt: Optional[str] = None # 敏感检测提示词(应用层覆盖)
138
139
  sensitive_action: str = "allow" # "allow"=不检测放行;"downgrade"=降级继续;"block"=阻断(整段上下文);"block_user_input"=阻断(仅检测用户输入)
139
140
 
@@ -110,11 +110,25 @@ class EgressPolicyConfig(BaseModel):
110
110
  def direct_targets(self) -> list[tuple[str, int]]:
111
111
  """把 directAllow 条目解析成 (ip, port) 列表,供 iptables 放行。
112
112
 
113
- 条目可以是 host、host:port、裸 IP。域名在此(沙箱进程)解析成 IP——
114
- child 只放行解析后的 IP。解析失败跳过并告警(不阻断其它条目)。
113
+ 条目可以是 host、host:port、裸 IP(v4/v6)。域名在此(沙箱进程)解析成
114
+ IP——child 只放行解析后的 IP。解析失败跳过并告警(不阻断其它条目)。
115
115
  默认端口 443(host 无端口且是 https 语义)——为兼容 http 内网服务,
116
116
  无端口条目同时放行 80 与 443。
117
+
118
+ 审核修复(M2):旧实现 socket.inet_aton/gethostbyname,IPv6 字面量在
119
+ 解析阶段即失败被静默跳过 → 硬墙新增的 ip6tables 分支生产路径不可达。
120
+ 改用 ipaddress(字面量 v4/v6)+ getaddrinfo(域名)。
121
+ 已知限制(记录不修):
122
+ - BUG-3:域名解析只取 infos[0] 首条(记录顺序不保证,双栈域名通常只
123
+ 放行到其中一个族——纯 v6 目标可能进不了放行列表,直连被兜底 DROP;
124
+ 网关通道不受影响)。
125
+ - BUG-4:歧义裸 v6 写法('::1:8443' 恰好是合法 v6 地址,整段被当地址、
126
+ 末段被当地址组而非端口)按字面量静默放行 80/443——无法与合法的
127
+ 「尾组为纯数字的 v6 地址」(如 fd00::1)区分,只能靠配置规范
128
+ ([v6]:port)。getaddrinfo 分支对「多冒号条目却解析出 v4」的异常
129
+ 组合有 warning 兜底提示。
117
130
  """
131
+ import ipaddress as _ipa
118
132
  out: list[tuple[str, int]] = []
119
133
  for raw in self.directAllow:
120
134
  entry = (raw or "").strip()
@@ -122,25 +136,47 @@ class EgressPolicyConfig(BaseModel):
122
136
  continue
123
137
  port = None
124
138
  host = entry
125
- if ":" in entry and not entry.count(":") > 1: # host:port(非 IPv6)
139
+ # host:port(仅单冒号才是 v4 形态;v6 字面量多冒号,整段给解析器)
140
+ if ":" in entry and entry.count(":") == 1:
126
141
  host, _, ps = entry.partition(":")
127
142
  if ps.isdigit():
128
143
  port = int(ps)
144
+ elif entry.startswith("[") and "]" in entry:
145
+ # [v6]:port 形态
146
+ host = entry[1:entry.index("]")]
147
+ tail = entry[entry.index("]") + 1:]
148
+ if tail.startswith(":") and tail[1:].isdigit():
149
+ port = int(tail[1:])
129
150
  # 跳过通配符条目(硬墙按 IP 放行,通配域名无法枚举;告警提示)
130
151
  if "*" in host or "?" in host:
131
152
  SYLogger.warning(
132
153
  f"[EgressPolicy] directAllow 含通配符 {entry},iptables 无法按 IP 放行,跳过(改用精确 host)")
133
154
  continue
134
- # host → IP(是 IP 则原样)
155
+ # host → IP:字面量(v4/v6)原样;域名解析(见上方 docstring:仅取
156
+ # infos[0],双栈域名可能只覆盖一个族——BUG-3 记录不修)
135
157
  try:
136
- socket.inet_aton(host)
158
+ _ipa.ip_address(host)
137
159
  ip = host
138
- except OSError:
160
+ except ValueError:
139
161
  try:
140
- ip = socket.gethostbyname(host)
162
+ infos = socket.getaddrinfo(host, None)
163
+ if not infos:
164
+ continue
165
+ ip = infos[0][4][0]
166
+ if host.count(":") not in (0, 1) and ":" not in ip:
167
+ # 歧义裸 v6 写法(BUG-4,记录不修):多冒号条目按 v6 语义
168
+ # 期望,但解析结果是 v4 → 极可能是歧义形态('::1:8443' 这类
169
+ # 被当整段地址)。放行列表按解析产物生成,此处仅提示存在
170
+ # 歧义写法,提示人工核对 directAllow 条目格式。
171
+ SYLogger.warning(
172
+ f"[EgressPolicy] directAllow 条目 {entry} 含多个冒号但解析为"
173
+ f" IPv4({ip})——疑似缺方括号的歧义 v6:port 写法,请核对"
174
+ " directAllow 条目格式([v6]:port)")
141
175
  except Exception as e:
142
176
  SYLogger.warning(f"[EgressPolicy] 解析 {host} 失败,跳过: {e}")
143
177
  continue
178
+ if not ip:
179
+ continue
144
180
  ports = [port] if port else [80, 443]
145
181
  for p in ports:
146
182
  if (ip, p) not in out:
@@ -46,7 +46,10 @@ _RULE_COMMENT = "sycommon-egress-wall"
46
46
 
47
47
 
48
48
  def _read_dns_ips() -> list[str]:
49
- """从 /etc/resolv.conf 读 nameserver IP(去重)。child 要能解析域名。"""
49
+ """从 /etc/resolv.conf 读 nameserver IP(去重)。child 要能解析域名。
50
+
51
+ 返回 v4 与 v6 地址的并集;调用方按地址族分发到 iptables / ip6tables。
52
+ """
50
53
  ips: list[str] = []
51
54
  try:
52
55
  with open("/etc/resolv.conf") as f:
@@ -61,6 +64,20 @@ def _read_dns_ips() -> list[str]:
61
64
  return ips
62
65
 
63
66
 
67
+ def _is_ipv6(s: str) -> bool:
68
+ """判断字符串形式的 IP 是否为【纯】IPv6 地址(审核 M3)。
69
+
70
+ IPv4-mapped(::ffff:a.b.c.d)归 v4:内核 connect() 发的是 IPv4 包,
71
+ ip6tables 规则永不命中,归 v6 组会导致该地址在两张表里都没规则。
72
+ """
73
+ import ipaddress
74
+ try:
75
+ parsed = ipaddress.ip_address(s)
76
+ return parsed.version == 6 and parsed.ipv4_mapped is None
77
+ except ValueError:
78
+ return False
79
+
80
+
64
81
  def _have_net_admin() -> bool:
65
82
  """实测当前进程能否配 iptables(有 CAP_NET_ADMIN)。"""
66
83
  if platform.system() != "Linux":
@@ -84,26 +101,53 @@ def _run_iptables(args: list[str]) -> tuple[int, str]:
84
101
  return 1, str(e)
85
102
 
86
103
 
104
+ def _run_ip6tables(args: list[str]) -> tuple[int, str]:
105
+ """跑一条 ip6tables 命令。镜像里可能没有 ip6tables(装了 iptables
106
+ 不代表有 v6 命令),缺失时调用方降级为「仅 v4 规则」。"""
107
+ try:
108
+ r = subprocess.run(["ip6tables", *args], capture_output=True, timeout=10)
109
+ return r.returncode, (r.stderr.decode(errors="replace").strip())
110
+ except Exception as e:
111
+ return 1, str(e)
112
+
113
+
114
+ def _have_ip6tables() -> bool:
115
+ """探测 ip6tables 可用性(存在且能列规则)。"""
116
+ if platform.system() != "Linux":
117
+ return False
118
+ try:
119
+ r, _ = _run_ip6tables(["-L", "OUTPUT", "-n"])
120
+ return r == 0
121
+ except Exception:
122
+ return False
123
+
124
+
87
125
  def _clear_old_rules(child_uid: int) -> None:
88
126
  """幂等清理本模块之前加的 OUTPUT 规则(按注释标记匹配)。
89
127
 
90
128
  iptables 无「按注释批量删」的原子操作,这里用 -S 列出 OUTPUT 规则,
91
129
  逐条匹配含 _RULE_COMMENT 的,-D 删除。重复 setup 不累积规则。
130
+ v4/v6 双栈都清(ip6tables 不可用时静默跳过)。
92
131
  """
93
- try:
94
- r = subprocess.run(["iptables", "-S", "OUTPUT"], capture_output=True, timeout=10)
95
- if r.returncode != 0:
96
- return
97
- lines = r.stdout.decode(errors="replace").splitlines()
98
- for line in lines:
99
- if _RULE_COMMENT in line:
100
- # line 形如 "-A OUTPUT -m owner ... -j DROP -m comment --comment sycommon-egress-wall"
101
- # 把 -A 换成 -D 即可删除该条。
102
- del_spec = line.replace("-A OUTPUT", "OUTPUT", 1).strip()
103
- # 去掉行首可能的 "-A"
104
- _run_iptables(["-D"] + shlex.split(del_spec))
105
- except Exception as e:
106
- SYLogger.debug(f"[EgressWall] 清理旧规则异常(非致命): {e}")
132
+ bins = ["iptables"]
133
+ if _have_ip6tables():
134
+ bins.append("ip6tables")
135
+ for bin_name in bins:
136
+ try:
137
+ r = subprocess.run([bin_name, "-S", "OUTPUT"], capture_output=True, timeout=10)
138
+ if r.returncode != 0:
139
+ continue
140
+ lines = r.stdout.decode(errors="replace").splitlines()
141
+ for line in lines:
142
+ if _RULE_COMMENT in line:
143
+ # line 形如 "-A OUTPUT -m owner ... -j DROP -m comment --comment sycommon-egress-wall"
144
+ # 把 -A 换成 -D 即可删除该条。
145
+ del_spec = line.replace("-A OUTPUT", "OUTPUT", 1).strip()
146
+ # 去掉行首可能的 "-A"
147
+ runner = _run_iptables if bin_name == "iptables" else _run_ip6tables
148
+ runner(["-D"] + shlex.split(del_spec))
149
+ except Exception as e:
150
+ SYLogger.debug(f"[EgressWall] 清理旧规则异常({bin_name},非致命): {e}")
107
151
 
108
152
 
109
153
  def setup_egress_wall(child_uid: int, gateway_port: int,
@@ -146,63 +190,120 @@ def setup_egress_wall(child_uid: int, gateway_port: int,
146
190
  return False
147
191
 
148
192
  dns_ips = _read_dns_ips()
193
+ dns_v4 = [ip for ip in dns_ips if not _is_ipv6(ip)]
194
+ dns_v6 = [ip for ip in dns_ips if _is_ipv6(ip)]
195
+ ip6 = _have_ip6tables()
149
196
  direct_targets = direct_targets or []
150
197
 
151
198
  _clear_old_rules(child_uid)
152
199
 
153
200
  uid = str(child_uid)
154
- c = lambda spec: ["-m", "comment", "--comment", _RULE_COMMENT, *spec] # noqa: E731
201
+
202
+ def c(*spec: str) -> list:
203
+ return ["-m", "comment", "--comment", _RULE_COMMENT, *spec]
204
+
205
+ # 0. loopback 放行(child 连 127.0.0.1/::1 的本地辅助服务)。只放
206
+ # 127.0.0.0/8 + ::1,【不用 -o lo】:Linux 下连 pod 自身 IP 的 OUTPUT
207
+ # 同样出 lo 接口,-o lo 会把沙箱服务自身 HTTP API(/v1/sandbox/*,
208
+ # 无 token 时不校验)与同 pod sidecar 全部暴露给子进程(审核 H2)。
209
+ _run_iptables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
210
+ "-d", "127.0.0.0/8", *c("-j", "ACCEPT")])
211
+ if ip6:
212
+ _run_ip6tables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
213
+ "-d", "::1", *c("-j", "ACCEPT")])
155
214
 
156
215
  # 1. ESTABLISHED,RELATED(回包)
157
216
  _run_iptables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
158
217
  "-m", "conntrack", "--ctstate", "ESTABLISHED,RELATED",
159
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "ACCEPT"])
160
-
161
- # 2. DNS(每个 nameserver,udp + tcp 53)
162
- for ip in dns_ips:
218
+ *c("-j", "ACCEPT")])
219
+ if ip6:
220
+ _run_ip6tables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
221
+ "-m", "conntrack", "--ctstate", "ESTABLISHED,RELATED",
222
+ *c("-j", "ACCEPT")])
223
+
224
+ # 2. DNS(每个 nameserver,udp + tcp 53;v4 → iptables / v6 → ip6tables)
225
+ for ip in dns_v4:
163
226
  _run_iptables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
164
227
  "-p", "udp", "-d", ip, "--dport", "53",
165
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "ACCEPT"])
228
+ *c("-j", "ACCEPT")])
166
229
  _run_iptables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
167
230
  "-p", "tcp", "-d", ip, "--dport", "53",
168
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "ACCEPT"])
231
+ *c("-j", "ACCEPT")])
232
+ for ip in dns_v6:
233
+ if not ip6:
234
+ SYLogger.warning(
235
+ f"[EgressWall] DNS nameserver {ip} 是 IPv6 但 ip6tables 不可用,"
236
+ "drop 模式下 v6 DNS 将被兜底 DROP(域名解析可能失败)")
237
+ continue
238
+ _run_ip6tables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
239
+ "-p", "udp", "-d", ip, "--dport", "53",
240
+ *c("-j", "ACCEPT")])
241
+ _run_ip6tables(["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
242
+ "-p", "tcp", "-d", ip, "--dport", "53",
243
+ *c("-j", "ACCEPT")])
169
244
 
170
245
  # 3. 本机网关
171
246
  gw_rc, gw_err = _run_iptables(
172
247
  ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
173
248
  "-p", "tcp", "-d", gateway_host, "--dport", str(gateway_port),
174
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "ACCEPT"])
249
+ *c("-j", "ACCEPT")])
175
250
  if gw_rc != 0:
176
251
  SYLogger.warning(f"[EgressWall] 放行网关规则失败: {gw_err}")
177
252
 
178
- # 4. directAllow 直连放行(EgressPolicy.directAllow 解析出的 (ip, port))
253
+ # 4. directAllow 直连放行(v4 → iptables / v6 → ip6tables)
179
254
  direct_ok = 0
180
255
  for ip, port in direct_targets:
181
- rc, err = _run_iptables(
182
- ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
183
- "-p", "tcp", "-d", ip, "--dport", str(port),
184
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "ACCEPT"])
256
+ if _is_ipv6(ip):
257
+ if not ip6:
258
+ SYLogger.warning(
259
+ f"[EgressWall] directAllow {ip} 是 IPv6 但 ip6tables 不可用,"
260
+ "drop 模式下将被兜底 DROP")
261
+ continue
262
+ rc, err = _run_ip6tables(
263
+ ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
264
+ "-p", "tcp", "-d", ip, "--dport", str(port),
265
+ *c("-j", "ACCEPT")])
266
+ else:
267
+ rc, err = _run_iptables(
268
+ ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
269
+ "-p", "tcp", "-d", ip, "--dport", str(port),
270
+ *c("-j", "ACCEPT")])
185
271
  if rc == 0:
186
272
  direct_ok += 1
187
273
  else:
188
274
  SYLogger.warning(f"[EgressWall] directAllow 放行失败 {ip}:{port}: {err}")
189
275
 
190
- # 5. 兜底 DROP(defaultMode='drop' 时;当前阶段 allow 不加,其余外网放行)
276
+ # 5. 兜底 DROP(v4/v6 各一条;drop_fallback=True 时)。
277
+ # 审核修正(M4):v4 成功 v6 失败不再 return False(那会留下「v4 全锁、
278
+ # v6 全开」的半面墙却谎报失败;调用方也不重试)。统一为告警不失败 ——
279
+ # 与「ip6tables 缺失只告警」同一语义:v6 防线缺失在日志里显式可见。
191
280
  if drop_fallback:
192
281
  drop_rc, drop_err = _run_iptables(
193
282
  ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
194
- "-m", "comment", "--comment", _RULE_COMMENT, "-j", "DROP"])
283
+ *c("-j", "DROP")])
195
284
  if drop_rc != 0:
196
285
  SYLogger.warning(f"[EgressWall] DROP 规则失败: {drop_err}")
197
286
  return False
198
- fallback_desc = "其余 DROP"
287
+ if ip6:
288
+ v6_rc, v6_err = _run_ip6tables(
289
+ ["-A", "OUTPUT", "-m", "owner", "--uid-owner", uid,
290
+ *c("-j", "DROP")])
291
+ if v6_rc != 0:
292
+ SYLogger.warning(
293
+ f"[EgressWall] v6 DROP 规则失败: {v6_err}"
294
+ "——IPv6 出网不受硬墙限制(建议镜像安装 ip6tables 或容器禁用 IPv6)")
295
+ else:
296
+ SYLogger.warning(
297
+ "[EgressWall] ip6tables 不可用,IPv6 出网不受硬墙限制"
298
+ "(建议镜像安装 ip6tables 或容器禁用 IPv6)")
299
+ fallback_desc = "其余 DROP(v4+v6)"
199
300
  else:
200
301
  fallback_desc = "其余放行(defaultMode=allow)"
201
302
 
202
303
  SYLogger.info(
203
304
  f"[EgressWall] 硬墙已配置: child uid={child_uid}, "
204
- f"放行网关 {gateway_host}:{gateway_port} + DNS({dns_ips}) + "
205
- f"directAllow({direct_ok} 条), {fallback_desc}")
305
+ f"放行 loopback + 网关 {gateway_host}:{gateway_port} + "
306
+ f"DNS(v4:{dns_v4} v6:{dns_v6}) + directAllow({direct_ok} 条), {fallback_desc}")
206
307
  return True
207
308
 
208
309
 
@@ -1371,9 +1371,15 @@ def setup_sandbox_handler(app: FastAPI, config: dict = None):
1371
1371
  env[_k] = str(_v)
1372
1372
  except Exception:
1373
1373
  pass
1374
- # 出网网关:子进程 SYT_BASE_URL 指向网关(http://127.0.0.1:port),
1375
- # HTTPS_PROXY 让 requests/httpx/curl/wget 自动走网关。node/裸 socket 不读
1376
- # proxy 的运行时,由后续 seccomp 硬墙兜底(只放行网关 host:port)。
1374
+ # 出网网关:子进程 SYT_BASE_URL 指向网关(http://127.0.0.1:port)。
1375
+ # 代理收口(2026-11-29,对齐 Go;审核 H2 修正):只注入 HTTP_PROXY
1376
+ # (http 目标走绝对 URI 明文代理,网关可见可注入 X-Sy-Api-Authz+审计)。
1377
+ # 不注入 HTTPS_PROXY:https 目标经代理必走 CONNECT 隧道,网关拒绝
1378
+ # (405,端到端加密无法注入头),且客户端代理失败不回退直连 —— 注入它
1379
+ # 会把 pip/git/硬编码 https 技能全部打断。https 直连由 iptables 硬墙管
1380
+ # (defaultMode=drop 时名单外 DROP)。NO_PROXY 豁免回环:连网关自身/
1381
+ # 本地服务的流量不该进代理。不读代理 env 的运行时(node fetch/裸
1382
+ # socket)同样由硬墙兜底。
1377
1383
  from sycommon.middleware.sandbox_gateway import gateway_base_url
1378
1384
  gw = gateway_base_url()
1379
1385
  if gw:
@@ -1381,11 +1387,8 @@ def setup_sandbox_handler(app: FastAPI, config: dict = None):
1381
1387
  # (shared 多用户正确归属,不再 any_user() 取错人)。脚本无感——它只做
1382
1388
  # 字符串拼接 SYT_BASE_URL + path,前缀自动带上。
1383
1389
  env["SYT_BASE_URL"] = f"{gw}/__u__/{req.user_id}" if req.user_id else gw
1384
- # ⚠️ 审核修正(P0-1):不再设 HTTP_PROXY/HTTPS_PROXY。网关不支持
1385
- # CONNECT 隧道,设了反而把所有硬编码 https:// 的技能(OA/星瀚/亿联/
1386
- # 企微)打成 404 tunnel 错误。SYT 流量本来就经 SYT_BASE_URL 指向网关;
1387
- # 其他域名按 EgressPolicy(defaultMode=allow)直连即可。
1388
- env["NO_PROXY"] = "*"
1390
+ env["HTTP_PROXY"] = env["http_proxy"] = gw
1391
+ env["NO_PROXY"] = env["no_proxy"] = "localhost,127.0.0.1,::1"
1389
1392
  # 技能 scope(system/shengye-platform/user):网关据此分级出网策略。
1390
1393
  # 命令级权威注入(审核 P0-3):env 只写 scope 供脚本读取展示;
1391
1394
  # 真正的分级判定在网关侧按【本命令的 scope】执行——见下方
@@ -1,7 +1,9 @@
1
1
  """沙箱出网收口网关(egress gateway)。
2
2
 
3
- 嵌入沙箱服务端进程内的 aiohttp.web 反向代理。子进程的所有出网请求指向本网关
4
- (child env 的 SYT_BASE_URL/HTTPS_PROXY = http://127.0.0.1:<port>),网关做四件事:
3
+ 嵌入沙箱服务端进程内的 aiohttp.web 反向代理。子进程的出网请求指向本网关
4
+ (child env 的 SYT_BASE_URL 与 HTTP_PROXY = http://127.0.0.1:<port>,R5 终验
5
+ 备注:仅注入 HTTP_PROXY 不注入 HTTPS_PROXY——https 经代理必走 CONNECT 被拒,
6
+ 见 sandbox.py env 注入注释),网关做四件事:
5
7
 
6
8
  1. 按「目标 host → 凭据形态」注入正确凭据(SYT 用 Authorization Bearer +
7
9
  X-Sy-Api-Authz;OA 系用 SYU-Token + SYU-Url 改写;企微 gettoken 用
@@ -29,6 +31,7 @@ from typing import Optional
29
31
  from urllib.parse import urlparse, urlunparse, urlencode, parse_qsl
30
32
 
31
33
  from aiohttp import web, ClientSession, ClientTimeout
34
+ from yarl import URL as yarl_URL
32
35
 
33
36
  from sycommon.logging.kafka_log import SYLogger
34
37
 
@@ -155,6 +158,9 @@ def _apply_credentials(method: str, target_url: str, headers: dict,
155
158
  target_url = urlunparse(parsed._replace(query=urlencode(q)))
156
159
  # 企微文档机器人(wecom.py 的 MCP 网关)用 DOC_BOT 凭据签名——不在此注入
157
160
  # (wecom.py 本地算签名),只保证 gettoken 的 corp 凭据注入。
161
+ authz = creds.get("SYT_API_AUTHZ", "")
162
+ if authz:
163
+ headers["X-Sy-Api-Authz"] = authz
158
164
  return target_url, headers
159
165
 
160
166
  # --- OA MCP 后端:SYU-Token + SYU-Url(改写为真上游 base)---
@@ -171,9 +177,17 @@ def _apply_credentials(method: str, target_url: str, headers: dict,
171
177
  # 而非子进程 SYT_BASE_URL(那是网关地址)。这里改写回真上游。
172
178
  if syt_base:
173
179
  headers["SYU-Url"] = f"{syt_base}/oauth/loadUser"
180
+ authz = creds.get("SYT_API_AUTHZ", "")
181
+ if authz:
182
+ headers["X-Sy-Api-Authz"] = authz
174
183
  return target_url, headers
175
184
 
176
- # --- 内网服务:无鉴权透传 ---
185
+ # --- 全域鉴权标记(2026-11-28,对齐 Go):所有出站请求统一带
186
+ # X-Sy-Api-Authz —— 内网服务(无鉴权透传分支)、外部域名同样携带;
187
+ # 内网侧按它统一鉴权,外部域名收到多余头无影响。置空即全域关闭。
188
+ authz = creds.get("SYT_API_AUTHZ", "")
189
+ if authz:
190
+ headers["X-Sy-Api-Authz"] = authz
177
191
  return target_url, headers
178
192
 
179
193
 
@@ -408,6 +422,36 @@ class EgressGateway:
408
422
  return self._store.get(user_id)
409
423
  return self._store.any_user() and self._store.get(self._store.any_user())
410
424
 
425
+ def _is_self(self, hostport: str) -> bool:
426
+ """代理模式自指防护:目标 host:port 是否网关自身(审核 M2 对齐 Go)。
427
+
428
+ host 归一(小写;方括号 v6 由 yarl 解析时剥掉)后按「回环等价 host +
429
+ 同端口」判定。识别的形态:localhost(任意大小写)、::1、127.0.0.0/8
430
+ 完整四段(如 127.0.0.1)、本进程 bind 地址——同端口即 self。
431
+ 【不】识别(yarl/urlparse 拒绝或归一不等价,判 False 走后续 SSRF 兜底):
432
+ 缩写 v4 段(127.1 —— Python ipaddress 拒绝缩写)、方括号 v4
433
+ ([127.0.0.1] —— RFC 3986 方括号仅限 IPv6)、无端口 hostport
434
+ (port None != actual_port)、折叠无括号 v6('::1:8443' 解析歧义)。
435
+ caller(_proxy)传方括号 v6(BUG-1/R3 修复后),本函数可正确解析。
436
+ """
437
+ if not hostport or not self._actual_port:
438
+ return False
439
+ try:
440
+ u = yarl_URL(f"http://{hostport}")
441
+ host = (u.host or "").lower()
442
+ port = u.port
443
+ except Exception:
444
+ return False
445
+ if port != self._actual_port:
446
+ return False
447
+ try:
448
+ import ipaddress as _ipa
449
+ if _ipa.ip_address(host).is_loopback:
450
+ return True
451
+ except ValueError:
452
+ pass
453
+ return host == "localhost" or host == self._bind
454
+
411
455
  async def _proxy(self, request: web.Request) -> web.StreamResponse:
412
456
  # SSRF 防护(审核 P0-2):拒绝 CONNECT(网关不做隧道),拒绝把上游指向
413
457
  # 本机/回环/私有地址——否则子进程可经网关打沙箱自身的无鉴权 API
@@ -418,10 +462,19 @@ class EgressGateway:
418
462
 
419
463
  # 解析用户前缀:/execute 注入的 SYT_BASE_URL = http://127.0.0.1:port/__u__/<user_id>
420
464
  # 网关据此按 user_id 取凭据(shared 多用户正确归属),再剥掉前缀转发。
465
+ # ⚠️ 仅 origin 形态(审核 R2-M3,对齐 Go):proxy 模式(绝对 URI)下
466
+ # /__u__ 是【目标 URL 路径的一部分】,照常解析会让 child A 借
467
+ # http://target/__u__/<B>/api 以 B 的凭据身份调用。proxy 模式强制
468
+ # 无前缀(归属走 _resolve_user("")→any_user 回退)。
469
+ # scheme 大小写不敏感(BUG-5/R3):RFC 3986 scheme 大小写等价,aiohttp
470
+ # raw_path 保留原始大小写('HTTP://...')——按小写判定,否则大写 scheme
471
+ # 会被当 origin 形态:/__u__ 解析重开(身份串号回归)+ 绝对 URI 的
472
+ # host 被丢弃静默改路由到 SYT 上游(H1 误路由回归)。
473
+ proxy_abs_uri = request.raw_path.lower().startswith(("http://", "https://"))
421
474
  raw_path = request.path
422
475
  request_user_id = ""
423
476
  real_path = raw_path
424
- if raw_path.startswith("/__u__/"):
477
+ if not proxy_abs_uri and raw_path.startswith("/__u__/"):
425
478
  parts = raw_path.split("/", 3) # ["", "__u__", "<uid>", "rest..."]
426
479
  if len(parts) >= 4:
427
480
  request_user_id = parts[2]
@@ -443,9 +496,56 @@ class EgressGateway:
443
496
  # 或:子进程直接用 http://<真host>/ 绝对路径(含真 host),网关按 host 路由。
444
497
  # 约定:子进程发的 URL 形如 http://127.0.0.1:port/<path>,真 host 由
445
498
  # X-Upstream-Host 携带;若缺省则取 SYT 上游(兼容直接拼 SYT_BASE_URL 的脚本)。
499
+ # 代理收口(2026-11-29,审核 H1 修复):HTTP_PROXY 代理协议下请求行是
500
+ # 【绝对 URI】(request.raw_path 含 scheme://host),真目标取 URL 自身
501
+ # host。归属限制(审核 R2-L4,对齐 Go):代理协议下客户端不发送 proxy
502
+ # URL 的 path,/__u__ 前缀无法随 HTTP_PROXY 传递 → 代理流量退化为
503
+ # any_user 归属(单用户/local 语义正确;shared 多用户会串)。
504
+ # 旧行为:绝对 URI 的 host 被丢弃 → 静默改路由到 SYT 上游并注入
505
+ # Bearer —— 误路由+凭据串号,已修复。
446
506
  upstream_host = request.headers.get("X-Upstream-Host", "").strip()
447
507
  syt_base = (creds.get("SYT_BASE_URL") or "").rstrip("/")
448
- if upstream_host:
508
+ # 判定与上方 proxy_abs_uri 同一规则(scheme 大小写不敏感,BUG-5/R3):
509
+ # 大写 scheme 的绝对 URI 走到这里若漏判,host 会被丢弃并静默改路由
510
+ # 到 SYT 上游(H1 误路由回归)。
511
+ if request.raw_path.lower().startswith(("http://", "https://")):
512
+ # forward-proxy 形态:URL 自带真目标。自指防护(转发回网关会
513
+ # handler 自环)+ SSRF 防护与 origin 模式同一套。
514
+ proxy_url = yarl_URL(request.raw_path)
515
+ proxy_hostport = proxy_url.host or ""
516
+ if proxy_url.port:
517
+ # IPv6 字面量保留方括号(BUG-1/R3):host 含 ':' 时必须还原
518
+ # [v6]:port 形态——折叠成 v6:port 后 yarl/urlparse 把整段当
519
+ # 不带方括号的歧义 v6,_is_self 解析失败 fail-open(自指防护
520
+ # 失效),_is_loopback_or_private/_apply_credentials 的 hostname
521
+ # 提取同样失真。
522
+ proxy_hostport = (f"[{proxy_hostport}]:{proxy_url.port}"
523
+ if ":" in proxy_hostport
524
+ else f"{proxy_hostport}:{proxy_url.port}")
525
+ if self._is_self(proxy_hostport):
526
+ SYLogger.warning(
527
+ f"[EgressGateway] 拒绝代理模式自指请求(回环保护): {proxy_hostport}")
528
+ return web.Response(status=403, text="gateway: upstream host not allowed")
529
+ policy = None
530
+ try:
531
+ from sycommon.config.EgressPolicyConfig import EgressPolicyConfig
532
+ policy = EgressPolicyConfig.from_config()
533
+ except Exception:
534
+ policy = None
535
+ trusted = []
536
+ if policy is not None:
537
+ trusted = list(policy.viaGateway) + list(policy.directAllow)
538
+ ph = proxy_url.host or ""
539
+ if (_is_loopback_or_private(proxy_hostport)
540
+ and not EgressPolicyConfig._host_match(ph.lower(), trusted)):
541
+ SYLogger.warning(
542
+ f"[EgressGateway] 拒绝内网/回环上游(SSRF 防护, proxy 模式): {proxy_hostport}")
543
+ return web.Response(status=403, text="gateway: upstream host not allowed")
544
+ upstream_host = proxy_hostport # 凭据路由按真目标 host 判定
545
+ # target_url 自带 scheme/host/path/query,后续转发/白名单/凭据全走它;
546
+ # path_qs(上方 origin 形态解析产物)仅下方 elif 分支使用,proxy 模式不读。
547
+ target_url = str(proxy_url)
548
+ elif upstream_host:
449
549
  # SSRF 防护:上游 host 禁止指向回环/本机/私有网段(本机服务含沙箱
450
550
  # 自身 API,免鉴权,打穿即跨用户任意执行)。例外:EgressPolicy 里
451
551
  # viaGateway/directAllow 显式登记的【信任内网上游】(如 OA MCP
@@ -467,7 +567,11 @@ class EgressGateway:
467
567
  SYLogger.warning(
468
568
  f"[EgressGateway] 拒绝内网/回环上游(SSRF 防护): {upstream_host}")
469
569
  return web.Response(status=403, text="gateway: upstream host not allowed")
470
- scheme = "https"
570
+ # 上游 scheme:X-Upstream-Scheme 头显式指定(默认 https);内网
571
+ # http 服务(如内网 OCR)可用该头降级 —— 对齐 Go 侧同款能力。
572
+ scheme = (request.headers.get("X-Upstream-Scheme", "") or "").strip().lower()
573
+ if scheme not in ("http", "https"):
574
+ scheme = "https"
471
575
  target_url = f"{scheme}://{upstream_host}{path_qs}"
472
576
  elif syt_base:
473
577
  target_url = f"{syt_base}{path_qs}"
@@ -1,39 +1,39 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sycommon-python-lib
3
- Version: 0.2.12a12
3
+ Version: 0.2.12a14
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: aio-pika==10.2.2
7
+ Requires-Dist: aio-pika==10.2.3
8
8
  Requires-Dist: aiohttp==3.14.5
9
9
  Requires-Dist: aiomysql==0.3.2
10
10
  Requires-Dist: anyio==4.16.0
11
- Requires-Dist: decorator==5.3.1
12
- Requires-Dist: deepagents==0.7.34
11
+ Requires-Dist: decorator==5.3.2
12
+ Requires-Dist: deepagents==0.7.41
13
13
  Requires-Dist: elasticsearch==9.5.1
14
- Requires-Dist: fastapi==0.162.2
14
+ Requires-Dist: fastapi==0.165.0
15
15
  Requires-Dist: jinja2==3.1.6
16
16
  Requires-Dist: kafka-python==3.0.13
17
- Requires-Dist: langchain==1.4.9
18
- Requires-Dist: langchain-core==1.7.6
19
- Requires-Dist: langchain-openai==1.7.4
17
+ Requires-Dist: langchain==1.5.2
18
+ Requires-Dist: langchain-core==1.8.4
19
+ Requires-Dist: langchain-openai==1.8.5
20
20
  Requires-Dist: langfuse==5.2.0
21
- Requires-Dist: langgraph==1.2.20
22
- Requires-Dist: langgraph-checkpoint-postgres==3.2.0
21
+ Requires-Dist: langgraph==1.2.24
22
+ Requires-Dist: langgraph-checkpoint-postgres==3.2.1
23
23
  Requires-Dist: langgraph-checkpoint-redis==0.6.0
24
24
  Requires-Dist: ldap3==2.9.1
25
- Requires-Dist: loguru==0.7.3
25
+ Requires-Dist: loguru==0.8.0
26
26
  Requires-Dist: mysql-connector-python==26.10.0
27
27
  Requires-Dist: nacos-sdk-python==3.2.0
28
28
  Requires-Dist: psutil==7.2.2
29
29
  Requires-Dist: pyxxl==0.4.8
30
- Requires-Dist: pydantic==2.14.3
30
+ Requires-Dist: pydantic==2.14.4
31
31
  Requires-Dist: python-dotenv==1.2.4
32
- Requires-Dist: python-multipart==0.0.33
33
- Requires-Dist: pyyaml==6.0.3
32
+ Requires-Dist: python-multipart==0.0.34
33
+ Requires-Dist: pyyaml==6.0.4
34
34
  Requires-Dist: redis==7.4.0
35
- Requires-Dist: sentry-sdk[fastapi]==2.74.0
36
- Requires-Dist: sqlalchemy[asyncio]==2.1.8
35
+ Requires-Dist: sentry-sdk[fastapi]==3.0.0
36
+ Requires-Dist: sqlalchemy[asyncio]==2.1.9
37
37
  Requires-Dist: starlette[full]==1.10.0
38
38
  Requires-Dist: tiktoken==0.14.0
39
39
  Requires-Dist: uvicorn==0.54.0
@@ -42,7 +42,7 @@ Requires-Dist: twine==7.0.0
42
42
  Requires-Dist: minio==7.2.20
43
43
  Requires-Dist: langchain-mcp-adapters==0.3.2
44
44
  Requires-Dist: fastapi-mcp==0.4.0
45
- Requires-Dist: psycopg[binary,pool]==3.3.8
45
+ Requires-Dist: psycopg[binary,pool]==3.3.9
46
46
  Requires-Dist: agent-client-protocol==0.12.1
47
47
  Requires-Dist: langchain-acp==1.13.0
48
48
  Requires-Dist: pypinyin==0.55.0
@@ -138,7 +138,7 @@ sycommon/agent/__init__.py,sha256=mxceAeUifQ-DKvWp7ZEJIFlmOCb5wpYHPGQw3rwEN8I,43
138
138
  sycommon/agent/agent_manager.py,sha256=6GpQHk2PBX4UvvyosGKXtGkuEc5Jh0gi1iZqbyXjg04,18833
139
139
  sycommon/agent/chat_events.py,sha256=t7qWa6OrIWLfqtd1AnqaVP67QWkn1JxpCBTZYQpoLuM,14226
140
140
  sycommon/agent/deep_agent.py,sha256=5RWhVQ4f6gO7rHmFS3uKDN7e-Oog66_ePjjdCN5NT94,93905
141
- sycommon/agent/multi_agent_team.py,sha256=TxcQRSXHWnPnAsQfzcaHRXcaLZy1mtIHpXvK6QGtJcA,35110
141
+ sycommon/agent/multi_agent_team.py,sha256=4mXOvWiS9Vk9mqLrs2BcXwdOgBnJFUWR-JNvFE55SYg,35267
142
142
  sycommon/agent/reasoning_content_patch.py,sha256=HZ_If0qVDHlz_b1mDT3tuTqbExhzRVhP4VgsoDt0JLc,3945
143
143
  sycommon/agent/resume_compactor.py,sha256=CJp3AUqeStr8U2JeWP31DyulomXZdrkLL4kVtLxnwn8,20849
144
144
  sycommon/agent/skills_retry_patch.py,sha256=syDXFpnz8dVV4tCbJXc3XxLCUab8uePfbKfvE8Fmo44,4566
@@ -190,7 +190,7 @@ sycommon/auth/wecom_ldap_service.py,sha256=7yw4gvoaaT2G1SuL_jC6kTORgMuT4GVYbusFb
190
190
  sycommon/config/ACPAgentConfig.py,sha256=paAa0c0gy1RnDDum-Q6m7QLTe7lhz2dsFt4r72QtmWE,3202
191
191
  sycommon/config/Config.py,sha256=kROrFMRWwio_qW28XKMLygbtyFaaXc1vBYzCkiZutHA,15054
192
192
  sycommon/config/DatabaseConfig.py,sha256=ILiUuYT9_xJZE2W-RYuC3JCt_YLKc1sbH13-MHIOPhg,804
193
- sycommon/config/EgressPolicyConfig.py,sha256=pFO3XbDqzGCEtlh55ejSqXsZrzoecbKQdKYEoj6dZpY,8131
193
+ sycommon/config/EgressPolicyConfig.py,sha256=ZWibKpgBmJkkEwjuVi4rzi0AVtjztLMrgFr1N-HQ14A,10551
194
194
  sycommon/config/ElasticsearchConfig.py,sha256=fO9ZPMgJxSg1-UyDJ90wO6UvYy-jscwPJsSkXgx9qTU,2308
195
195
  sycommon/config/EmbeddingConfig.py,sha256=gPKwiDYbeu1GpdIZXMmgqM7JqBIzCXi0yYuGRLZooMI,362
196
196
  sycommon/config/LLMConfig.py,sha256=JCYXywqDgiVmgQ7jra3wMJjDt5133FR4loJurzoGypE,1144
@@ -265,13 +265,13 @@ sycommon/middleware/context.py,sha256=tSex_gWQhRplTwgwIHmbD8--sijMfXz3C3lcuggUrS
265
265
  sycommon/middleware/cors.py,sha256=0B5d_ovD56wcH9TfktRs88Q09R9f8Xx5h5ALWYvE8Iw,600
266
266
  sycommon/middleware/crosstenant.py,sha256=FSIUN_LUcQ7YsS-h32MBjnGyg274BnKekmkyzAepao8,3693
267
267
  sycommon/middleware/docs.py,sha256=bVdDBIHXGVBv562MQLSroa1DgHoObxR9gFzv71PIejg,1187
268
- sycommon/middleware/egress_wall.py,sha256=z66EInw-tjy7UnPzP6lAjBqSoMKi2FbPKGVqRV-3qpY,11759
268
+ sycommon/middleware/egress_wall.py,sha256=BhfWPTaQnru7Hv3K0eTo-WoSzYE_405rLOc_0BZ0tjA,16176
269
269
  sycommon/middleware/exception.py,sha256=suu9n5XgLBJHGNY1zc76g1k48cs64U38MKAj2RGMCU4,5503
270
270
  sycommon/middleware/middleware.py,sha256=fAW7Rje6u0uZ_7Dc_c-pTmoK2A20HdXFT2h1Mwmj2Dc,1962
271
271
  sycommon/middleware/monitor_memory.py,sha256=pYRK-wRuDd6enSg9Pf8tQxPdYQS6S0AyjyXeKFRLKEs,628
272
272
  sycommon/middleware/mq.py,sha256=9X6KKtadFjBXKS5L3kEKujYio9wwGfWgXwWOAHO-HDg,254
273
- sycommon/middleware/sandbox.py,sha256=0GLFH360uTO875w-GZNvmSjzb81YD5j2qGgHzymWBo4,127615
274
- sycommon/middleware/sandbox_gateway.py,sha256=ZyXV9iwvaLNNTk0oM-RdjGRSgkBPaPp67A-K1-i5f84,26145
273
+ sycommon/middleware/sandbox.py,sha256=3pZ6KA8COYMeXQ8dh3gQvtQia5WK2TA1OzZRLchWsdQ,127852
274
+ sycommon/middleware/sandbox_gateway.py,sha256=Lutc3yyvN7uxbHTjqm2XSHpLrxM7hNtUsnhqBKXdNY8,32557
275
275
  sycommon/middleware/timeout.py,sha256=KlxOPa8xl2dg6yuRi_EzkVJG8bX4stb5ueYxctzzGM8,1433
276
276
  sycommon/middleware/token_tracking.py,sha256=rEbgV1bgWMdzAERx4aq5XAvOIT6jTY_tK1P0xHJnL3o,6609
277
277
  sycommon/middleware/tool_result_truncation.py,sha256=xtwBf8q11Z8EPzmo3Ju4OfUbULOklSsWo_oystxCW0o,13640
@@ -404,8 +404,8 @@ sycommon/tools/usercache.py,sha256=Zu2oiXISUOojleEYCAS9t06ZzgWSNHCIhCjv4yTtkRw,4
404
404
  sycommon/xxljob/__init__.py,sha256=7eoBlQxv-B39IfRSCY2bkqdGYs1QRe1umAWd88VMEEM,86
405
405
  sycommon/xxljob/sharding.py,sha256=LJ0tle7qSUS32S5ntjzri1aOcPzwL5CFde3W4Rf1AUE,2560
406
406
  sycommon/xxljob/xxljob_service.py,sha256=1yifwIBNGsCIxLnQjHKiBlbsigc_zvPH-dMTZcNxe-Q,7649
407
- sycommon_python_lib-0.2.12a12.dist-info/METADATA,sha256=hpmvEAe7lam_KxEK2nqN5UxJHVayxIm5ji02LZGBv-I,8029
408
- sycommon_python_lib-0.2.12a12.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
409
- sycommon_python_lib-0.2.12a12.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
410
- sycommon_python_lib-0.2.12a12.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
411
- sycommon_python_lib-0.2.12a12.dist-info/RECORD,,
407
+ sycommon_python_lib-0.2.12a14.dist-info/METADATA,sha256=lQZd9radv8yEse6LsaAEEjhZbsnrAS2GcMelWMudZZs,8028
408
+ sycommon_python_lib-0.2.12a14.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
409
+ sycommon_python_lib-0.2.12a14.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
410
+ sycommon_python_lib-0.2.12a14.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
411
+ sycommon_python_lib-0.2.12a14.dist-info/RECORD,,