JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:第三方命名空间logger打印的api_key加密
Lexie-7d238c6aa713f
diff --git a/jiuwenswarm/common/utils.py b/jiuwenswarm/common/utils.pyindex b22153386c..b580d5d354 100644--- a/jiuwenswarm/common/utils.py+++ b/jiuwenswarm/common/utils.py@@ -1894,6 +1894,75 @@ class JsonOnlyFormatter(logging.Formatter):return record.getMessage()+# 源头脱敏是否已安装(全局,避免重复设置 LogRecordFactory)。+_source_record_masking_installed = False+# 源头脱敏失败计数(脱敏异常时递增;运维可通过此值监控脱敏失效,避免静默泄露)。+_source_masking_failures = 0+++def install_source_record_masking() -> None:+ """在 LogRecord 创建层(``logging.setLogRecordFactory``)安装源头脱敏。++ 这是比 handler 上挂 ``SensitiveDataFilter`` 更彻底的兜底层:无论哪个 logger+ 发出的 record——包括 **jiuwenswarm 命名空间之外**的第三方库(openjiuwen /+ openai / httpx / urllib3 等,它们自带 handler、不 propagate 到 jiuwenswarm+ 根 logger),在 LogRecord **创建瞬间**就被脱敏 message 与 traceback,+ 保证任何来源的 api_key 都不明文落盘。++ 覆盖场景:+ - ``app_agentserver.py`` 用 ``logging.getLogger("openjiuwen.harness.security")``+ 等 openjiuwen 命名空间 logger;+ - clawee(yuanrong faas)拉起的 AgentServer 内 openjiuwen SDK 自有 logger;+ - httpx/openai SDK 在 DEBUG 级别打印请求头(含 Authorization)。++ 复用带指纹的 ``_sanitize_log_text``,与 handler 层 ``SensitiveDataFilter``+ 共存为双保险:若 record 已在源头脱敏,handler 层的 ``_is_already_masked``+ 会跳过重算,不破坏指纹。幂等,重复调用安全。+ """+ global _source_record_masking_installed+ if _source_record_masking_installed:+ return++ old_factory = logging.getLogRecordFactory()++ def _sanitizing_record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord:+ record = old_factory(*args, **kwargs)+ try:+ # message 脱敏(含 %s/format 格式化后的最终文本)。+ msg = record.getMessage()+ record.msg = _sanitize_log_text(msg)+ record.args = ()+ # traceback 脱敏:traceback 由 Formatter.formatException 从+ # record.exc_text 单独渲染,getMessage 覆盖不到。此处提前渲染并脱敏,+ # 清空 exc_info 使 Formatter 复用已脱敏的 exc_text。+ exc_info = record.exc_info+ if exc_info and not record.exc_text:+ import traceback as _tb++ formatted = "".join(_tb.format_exception(exc_info[1]))+ record.exc_text = _sanitize_log_text(formatted)+ record.exc_info = None+ elif record.exc_text:+ record.exc_text = _sanitize_log_text(record.exc_text)+ except Exception:+ # 永不因脱敏失败而阻断日志输出。但记录失败(计数 + 首次 stderr 提示),+ # 避免静默吞掉异常导致 api_key 在无感知下明文泄露。+ global _source_masking_failures+ _source_masking_failures += 1+ if _source_masking_failures == 1:+ # 仅首次打 stderr(不用 logging,避免自循环),提示运维脱敏失效。+ # 后续仅靠计数器累积,避免高频失败刷屏。+ print(+ "[jiuwenswarm] source record masking failed — secrets may be "+ "exposed in logs; check _source_masking_failures counter",+ file=sys.stderr,+ )+ return record++ logging.setLogRecordFactory(_sanitizing_record_factory)+ _source_record_masking_installed = True++def setup_logger(log_level: Optional[str] = None) -> logging.Logger:"""配置 ``jiuwenswarm`` 根日志:控制台 + 分组件文件 + 汇总 full.log。@@ -1957,6 +2026,10 @@ def setup_logger(log_level: Optional[str] = None) -> logging.Logger:stream_handler.setFormatter(formatter)stream_handler.addFilter(privacy_filter)root.addHandler(stream_handler)++ # 源头脱敏:覆盖 jiuwenswarm 命名空间之外的第三方 logger(openjiuwen/openai/+ # httpx 等),在 LogRecord 创建时统一脱敏,保证任何来源的 api_key 都不明文落盘。+ install_source_record_masking()return rootdiff --git a/tests/unit_tests/test_utils.py b/tests/unit_tests/test_utils.pyindex 9d0950ed80..0247c555ac 100644--- a/tests/unit_tests/test_utils.py+++ b/tests/unit_tests/test_utils.py@@ -127,6 +127,153 @@ class TestLoggerSetup:assert handler_types.count("SafeRotatingFileHandler") == 5+class TestSourceRecordMasking:+ """Test install_source_record_masking (source-level LogRecord factory masking).++ Covers the security-critical paths called out in review:+ - third-party (non-jiuwenswarm) logger message masking,+ - traceback-embedded secret masking,+ - double-masking safety (_is_already_masked keeps fingerprint stable),+ - idempotency.+ """++ PLAINTEXT_KEY = "sk-epignnbeppwjigp932ngefebnof"++ @staticmethod+ def _capture_logger(name):+ """Build a logger with its own handler (no SensitiveDataFilter), so any+ masking observed must come from the source record factory, not handler filter.+ """+ import io+ import logging++ lg = logging.getLogger(name)+ for h in lg.handlers[:]:+ lg.removeHandler(h)+ buf = io.StringIO()+ handler = logging.StreamHandler(buf)+ # Formatter 默认在 message 后自动追加 traceback(若 record 有 exc_info/exc_text),+ # 无需显式 %(exc_text)s,否则会与生产行为不一致导致 traceback 重复。+ handler.setFormatter(logging.Formatter("%(name)s: %(message)s"))+ lg.addHandler(handler)+ lg.setLevel(logging.DEBUG)+ lg.propagate = False+ return lg, buf++ @staticmethod+ def _save_state():+ """Snapshot the global LogRecord factory + install flag for later restore."""+ import logging++ return logging.getLogRecordFactory(), utils._source_record_masking_installed++ @staticmethod+ def _restore_state(state):+ """Restore the global factory + install flag (avoid cross-test pollution)."""+ import logging++ factory, flag = state+ logging.setLogRecordFactory(factory)+ utils._source_record_masking_installed = flag++ def test_third_party_logger_message_masked(self):+ """Source factory masks messages from non-jiuwenswarm loggers (openjiuwen/+ openai/httpx style) that bypass the jiuwenswarm handler-level filter."""+ import logging++ state = self._save_state()+ try:+ # Reset to plain factory, then install — proves masking comes from install.+ logging.setLogRecordFactory(logging.LogRecord)+ utils._source_record_masking_installed = False+ utils.install_source_record_masking()++ lg, buf = self._capture_logger("openjiuwen.harness.security")+ key = self.PLAINTEXT_KEY+ lg.info("config: api_key=%s, base=https://x.com", key)+ out = buf.getvalue()+ assert key not in out, "plaintext api_key leaked from third-party logger"+ assert "******" in out, "api_key not masked"+ assert "https://x.com" in out, "non-sensitive api_base should be preserved"+ finally:+ self._restore_state(state)++ def test_traceback_embedded_secret_masked(self):+ """logger.exception masks api_key embedded in the rendered traceback."""+ import logging++ state = self._save_state()+ try:+ logging.setLogRecordFactory(logging.LogRecord)+ utils._source_record_masking_installed = False+ utils.install_source_record_masking()++ lg, buf = self._capture_logger("openai._base_client")+ key = self.PLAINTEXT_KEY+ try:+ raise ValueError("build failed: api_key=" + key)+ except ValueError:+ lg.exception("init error")+ out = buf.getvalue()+ assert key not in out, "plaintext api_key leaked via traceback"+ assert "Traceback" in out, "traceback should still be rendered"+ assert "******" in out, "api_key in traceback not masked"+ finally:+ self._restore_state(state)++ def test_double_masking_preserves_fingerprint(self):+ """A record masked at source, then re-processed by _sanitize_log_text (handler+ layer), keeps the same fingerprint — _is_already_masked prevents 'fingerprint+ of fingerprint' corruption."""+ import logging+ import re++ state = self._save_state()+ try:+ logging.setLogRecordFactory(logging.LogRecord)+ utils._source_record_masking_installed = False+ utils.install_source_record_masking()++ lg, buf = self._capture_logger("httpx")+ key = self.PLAINTEXT_KEY+ lg.info("api_key=%s", key)+ source_out = buf.getvalue()++ # Re-run the handler-layer sanitizer on the already-masked text.+ double_masked = utils._sanitize_log_text(source_out)++ fp_source = re.search(r"fp:([0-9a-f]+)", source_out)+ fp_double = re.search(r"fp:([0-9a-f]+)", double_masked)+ assert fp_source, "source masking should produce a fingerprint"+ assert fp_double, "double-masked text should still carry a fingerprint"+ assert fp_source.group(1) == fp_double.group(1), (+ "fingerprint changed after double masking — _is_already_masked not effective"+ )+ # True fingerprint of the plaintext key (cross-check).+ assert fp_source.group(1) == utils._fingerprint(key)+ finally:+ self._restore_state(state)++ def test_install_is_idempotent(self):+ """Repeated install_source_record_masking calls are safe (no-op after first)."""+ import logging++ state = self._save_state()+ try:+ logging.setLogRecordFactory(logging.LogRecord)+ utils._source_record_masking_installed = False+ utils.install_source_record_masking()+ factory_after_first = logging.getLogRecordFactory()+ utils.install_source_record_masking()+ factory_after_second = logging.getLogRecordFactory()+ assert factory_after_first is factory_after_second, (+ "second install should not replace the factory (idempotent)"+ )+ assert utils._source_record_masking_installed is True+ finally:+ self._restore_state(state)++class TestUserWorkspace:"""Test user workspace functions."""