Open
test(出站TLS): 添加大模型 TLS 探测脚本 #9
jaxAdd on Sep 11
test(出站TLS): 添加大模型 TLS 探测脚本 #9
Open
Merged fromtest/probe-outbound-tls-modesintobr_release_930
Total: 2 files changed+618-0
| @@ -1552,6 +1552,7 @@ class LLMClient: | |||
| 1552 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT) | 1552 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT) |
| 1553 | max_attempts = self._resolve_max_attempts(kwargs) | 1553 | max_attempts = self._resolve_max_attempts(kwargs) |
| 1554 | logger.debug("invoke.request model={} payload_keys={}", self._model, sorted(payload.keys())) | 1554 | logger.debug("invoke.request model={} payload_keys={}", self._model, sorted(payload.keys())) |
| 1555 | + self._log_outbound_request(payload, stream=False) | ||
| 1555 | verify = httpx_verify() | 1556 | verify = httpx_verify() |
| 1556 | 1557 | ||
| 1557 | def _call() -> LLMClientMessage: | 1558 | def _call() -> LLMClientMessage: |
| @@ -1577,6 +1578,7 @@ class LLMClient: | |||
| 1577 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT) | 1578 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT) |
| 1578 | max_attempts = self._resolve_max_attempts(kwargs) | 1579 | max_attempts = self._resolve_max_attempts(kwargs) |
| 1579 | logger.debug("ainvoke.request model={} payload_keys={}", self._model, sorted(payload.keys())) | 1580 | logger.debug("ainvoke.request model={} payload_keys={}", self._model, sorted(payload.keys())) |
| 1581 | + self._log_outbound_request(payload, stream=False) | ||
| 1580 | verify = httpx_verify() | 1582 | verify = httpx_verify() |
| 1581 | 1583 | ||
| 1582 | async def _call() -> LLMClientMessage: | 1584 | async def _call() -> LLMClientMessage: |
| @@ -1602,6 +1604,7 @@ class LLMClient: | |||
| 1602 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_STREAM_TIMEOUT) | 1604 | timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_STREAM_TIMEOUT) |
| 1603 | max_attempts = self._resolve_max_attempts(kwargs) | 1605 | max_attempts = self._resolve_max_attempts(kwargs) |
| 1604 | request_url = self._endpoint() | 1606 | request_url = self._endpoint() |
| 1607 | + self._log_outbound_request(payload, stream=True) | ||
| 1605 | 1608 | ||
| 1606 | for attempt in range(max_attempts + 1): | 1609 | for attempt in range(max_attempts + 1): |
| 1607 | stream_state = _AStreamState() | 1610 | stream_state = _AStreamState() |
| @@ -1877,6 +1880,23 @@ class LLMClient: | |||
| 1877 | """Build the ``/chat/completions`` endpoint URL from the configured api_base.""" | 1880 | """Build the ``/chat/completions`` endpoint URL from the configured api_base.""" |
| 1878 | return f"{self._api_base.rstrip('/')}/chat/completions" | 1881 | return f"{self._api_base.rstrip('/')}/chat/completions" |
| 1879 | 1882 | ||
| 1883 | + def _log_outbound_request(self, payload: Mapping[str, Any], *, stream: bool) -> None: | ||
| 1884 | + """打印完整出站报文;Authorization 脱敏。控制台默认 WARNING,故打 WARNING。""" | ||
| 1885 | + headers = dict(self._headers()) | ||
| 1886 | + if "Authorization" in headers: | ||
| 1887 | + headers["Authorization"] = "Bearer ***" | ||
| 1888 | + try: | ||
| 1889 | + body = json.dumps(payload, ensure_ascii=False, default=str) | ||
| 1890 | + except TypeError: | ||
| 1891 | + body = str(payload) | ||
| 1892 | + logger.warning( | ||
| 1893 | + "llm.request method=POST url={} stream={} headers={} body={}", | ||
| 1894 | + self._endpoint(), | ||
| 1895 | + stream, | ||
| 1896 | + headers, | ||
| 1897 | + body, | ||
| 1898 | + ) | ||
| 1899 | + | ||
| 1880 | def _headers(self) -> dict[str, str]: | 1900 | def _headers(self) -> dict[str, str]: |
| 1881 | """Build the Authorization + Content-Type request headers.""" | 1901 | """Build the Authorization + Content-Type request headers.""" |
| 1882 | headers = { | 1902 | headers = { |
| @@ -0,0 +1,598 @@ | |||
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); | ||
| 2 | +# you may not use this file except in compliance with the License. | ||
| 3 | +# You may obtain a copy of the License at | ||
| 4 | +# | ||
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 | ||
| 6 | +# | ||
| 7 | +# Unless required by applicable law or agreed to in writing, software | ||
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, | ||
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| 10 | +# See the License for the specific language governing permissions and | ||
| 11 | +# limitations under the License. | ||
| 12 | +# ============================================================================ | ||
| 13 | +"""验证大模型出站 TLS:Catalog「验链、关 hostname」+ Ferry mode 2。 | ||
| 14 | + | ||
| 15 | +只依赖运行时已有的 ``httpx`` 和标准库;自测用本机 ``openssl`` 出证书, | ||
| 16 | +不引入 requests / urllib3 / cryptography。 | ||
| 17 | + | ||
| 18 | +Catalog 语义(用 httpx 复现,不走 urllib3): | ||
| 19 | + verify_ssl=True, verify_hostname=False | ||
| 20 | + CERT_REQUIRED + check_hostname=False + 出示客户端证 | ||
| 21 | + Agent 出站是 httpx,没有 urllib3 的 assert_hostname 第二层 | ||
| 22 | + | ||
| 23 | +Ferry mode 2(主仓 0930): | ||
| 24 | + CERT_REQUIRED + 出示客户端证 + check_hostname=False | ||
| 25 | + | ||
| 26 | + .venv/bin/python scripts/probe_outbound_tls_modes.py --self-test | ||
| 27 | + | ||
| 28 | + .venv/bin/python scripts/probe_outbound_tls_modes.py \\ | ||
| 29 | + --url https://10.x.x.x:8443/v1/chat/completions \\ | ||
| 30 | + --ca /path/ca.crt --cert /path/client.crt --key /path/client.key \\ | ||
| 31 | + --model your-model --api-key EMPTY | ||
| 32 | +""" | ||
| 33 | + | ||
| 34 | +from __future__ import annotations | ||
| 35 | + | ||
| 36 | +import argparse | ||
| 37 | +import ssl | ||
| 38 | +import sys | ||
| 39 | +import tempfile | ||
| 40 | +import threading | ||
| 41 | +from collections.abc import Iterator | ||
| 42 | +from contextlib import contextmanager | ||
| 43 | +from dataclasses import dataclass | ||
| 44 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| 45 | +from pathlib import Path | ||
| 46 | +from typing import Any, NamedTuple | ||
| 47 | + | ||
| 48 | +import httpx | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +class Policy(NamedTuple): | ||
| 52 | + verify_server: bool | ||
| 53 | + present_client_cert: bool | ||
| 54 | + check_hostname: bool | ||
| 55 | + label: str | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +# 与主仓 0930 ``outbound_tls._OUTBOUND_CERT_MODE`` 一致。 | ||
| 59 | +POLICIES: dict[int, Policy] = { | ||
| 60 | + 0: Policy(False, False, False, "不验、不出示证"), | ||
| 61 | + 1: Policy(True, False, True, "验链+hostname、不出示证"), | ||
| 62 | + 2: Policy(True, True, False, "验链、不验 hostname、出示证"), | ||
| 63 | + 3: Policy(True, True, True, "验链+hostname、出示证"), | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +@dataclass(frozen=True) | ||
| 68 | +class ProbeResult: | ||
| 69 | + name: str | ||
| 70 | + ok: bool | ||
| 71 | + detail: str | ||
| 72 | + verify_mode: int | ||
| 73 | + check_hostname: bool | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def make_ferry_context( | ||
| 77 | + mode: int, | ||
| 78 | + *, | ||
| 79 | + ca_file: str | None, | ||
| 80 | + client_cert: str | None, | ||
| 81 | + client_key: str | None, | ||
| 82 | + key_password: str | None = None, | ||
| 83 | +) -> ssl.SSLContext: | ||
| 84 | + """Ferry / httpx:按 0930 mode 构造 ``SSLContext``。""" | ||
| 85 | + if mode not in POLICIES: | ||
| 86 | + raise ValueError(f"unsupported mode={mode}; expected {sorted(POLICIES)}") | ||
| 87 | + policy = POLICIES[mode] | ||
| 88 | + if policy.present_client_cert and (not client_cert or not client_key): | ||
| 89 | + raise ValueError(f"mode {mode} requires --cert and --key") | ||
| 90 | + if policy.verify_server and not ca_file: | ||
| 91 | + raise ValueError(f"mode {mode} requires --ca") | ||
| 92 | + | ||
| 93 | + ctx = ssl.create_default_context(cafile=ca_file if policy.verify_server else None) | ||
| 94 | + ctx.check_hostname = policy.check_hostname | ||
| 95 | + ctx.verify_mode = ssl.CERT_REQUIRED if policy.verify_server else ssl.CERT_NONE | ||
| 96 | + if policy.present_client_cert: | ||
| 97 | + ctx.load_cert_chain(certfile=client_cert, keyfile=client_key, password=key_password) | ||
| 98 | + return ctx | ||
| 99 | + | ||
| 100 | + | ||