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:解决配置华为OBS后附件上传失败问题
meizi6437e9c9c4f54
diff --git a/jiuwenswarm/channels/web/minio_upload.py b/jiuwenswarm/channels/web/minio_upload.pyindex c9ae8d2dff..c56c2a38f5 100644--- a/jiuwenswarm/channels/web/minio_upload.py+++ b/jiuwenswarm/channels/web/minio_upload.py@@ -77,6 +77,38 @@ def _parse_bool(value: str | bool | None, default: bool = False) -> bool:return default+def normalize_minio_host(host: str) -> str:+ """Normalize endpoint / URL host for OBS comparisons (strip, lower, drop trailing ``.``)."""+ return (host or "").strip().lower().rstrip(".")+++def huawei_obs_needs_virtual_style(endpoint: str, bucket: str = "") -> bool:+ """Whether Huawei OBS should use virtual-hosted-style addressing.++ True only for Huawei OBS regional endpoints. False when ``OBS_URL`` already+ embeds the bucket (legacy ``{bucket}.{endpoint}`` workaround) so minio-py+ does not double-prefix the host as ``{bucket}.{bucket}.{endpoint}``.+ """+ endpoint_n = normalize_minio_host(endpoint)+ bucket_n = normalize_minio_host(bucket)+ if not endpoint_n or "myhuaweicloud." not in endpoint_n:+ return False+ if bucket_n and (endpoint_n == bucket_n or endpoint_n.startswith(f"{bucket_n}.")):+ return False+ return True+++def huawei_obs_virtual_hosted_bucket_host(endpoint: str, bucket: str) -> str | None:+ """Return ``{bucket}.{endpoint}`` when virtual-hosted object URLs apply."""+ if not huawei_obs_needs_virtual_style(endpoint, bucket):+ return None+ endpoint_n = normalize_minio_host(endpoint)+ bucket_n = normalize_minio_host(bucket)+ if not bucket_n:+ return None+ return normalize_minio_host(f"{bucket_n}.{endpoint_n}")++def load_minio_upload_config() -> MinioUploadConfig:"""Load object-store settings from ``OBS_*`` env or ``config.yaml`` ``minio``.@@ -160,6 +192,9 @@ def upload_local_file_to_minio(secure=config.secure,region=config.region,)+ # Huawei OBS requires virtual-hosted style (skip if OBS_URL already embeds bucket).+ if huawei_obs_needs_virtual_style(config.endpoint, config.bucket):+ client.enable_virtual_style_endpoint()if not client.bucket_exists(config.bucket):client.make_bucket(config.bucket)diff --git a/jiuwenswarm/gateway/message_handler/outbound_file_materialize.py b/jiuwenswarm/gateway/message_handler/outbound_file_materialize.pyindex 91a1faf0fe..408b97a8d0 100644--- a/jiuwenswarm/gateway/message_handler/outbound_file_materialize.py+++ b/jiuwenswarm/gateway/message_handler/outbound_file_materialize.py@@ -95,33 +95,41 @@ def _is_obs_proxy_download_url(download_url: str) -> bool:return path.rstrip("/").endswith("/file-api/download") and "url=" in query-def _normalize_host(host: str) -> str:- return (host or "").strip().lower().rstrip(".")--def allowed_minio_hosts() -> set[str]:"""Exact ``host`` / ``host:port`` values allowed for OBS proxy (SSRF).Does **not** add bare hostname aliases when the configured endpoint includesa port — otherwise ``minio:9000`` would also allow ``minio:8080``.++ For Huawei OBS, also allows the virtual-hosted object URL host+ ``{OBS_BUCKET}.{OBS_URL}`` when upload enables virtual-hosted style."""+ from jiuwenswarm.channels.web.minio_upload import (+ huawei_obs_virtual_hosted_bucket_host,+ load_minio_upload_config,+ normalize_minio_host,+ )+hosts: set[str] = set()try:- from jiuwenswarm.channels.web.minio_upload import load_minio_upload_config-cfg = load_minio_upload_config()except Exception:logger.debug("[OutboundFile] load_minio_upload_config failed", exc_info=True)return hosts- endpoint = _normalize_host(str(getattr(cfg, "endpoint", "") or ""))+ endpoint = normalize_minio_host(str(getattr(cfg, "endpoint", "") or ""))if endpoint:hosts.add(endpoint)+ bucket = str(getattr(cfg, "bucket", "") or "").strip()+ virtual_host = huawei_obs_virtual_hosted_bucket_host(endpoint, bucket)+ if virtual_host:+ hosts.add(virtual_host)+public = str(getattr(cfg, "public_base_url", "") or "").strip()if public:parsed = urlparse(public if "://" in public else f"http://{public}")- netloc = _normalize_host(parsed.netloc or parsed.path)+ netloc = normalize_minio_host(parsed.netloc or parsed.path)if netloc:hosts.add(netloc)return {h for h in hosts if h}@@ -129,10 +137,12 @@ def allowed_minio_hosts() -> set[str]:def assert_minio_url_allowed(url: str) -> None:"""Raise ValueError if url host is not a configured MinIO host (SSRF guard)."""+ from jiuwenswarm.channels.web.minio_upload import normalize_minio_host+parsed = urlparse(url)if parsed.scheme not in ("http", "https"):raise ValueError(f"unsupported url scheme: {parsed.scheme!r}")- host = _normalize_host(parsed.netloc)+ host = normalize_minio_host(parsed.netloc)if not host:raise ValueError("url missing host")allowed = allowed_minio_hosts()diff --git a/tests/unit_tests/test_minio_upload_config.py b/tests/unit_tests/test_minio_upload_config.pyindex 6da8b7645a..f688bb81a4 100644--- a/tests/unit_tests/test_minio_upload_config.py+++ b/tests/unit_tests/test_minio_upload_config.py@@ -4,11 +4,17 @@from __future__ import annotations-from unittest.mock import patch+from unittest.mock import MagicMock, patchimport pytest-from jiuwenswarm.channels.web.minio_upload import load_minio_upload_config+from jiuwenswarm.channels.web.minio_upload import (+ MinioUploadConfig,+ huawei_obs_needs_virtual_style,+ huawei_obs_virtual_hosted_bucket_host,+ load_minio_upload_config,+ upload_local_file_to_minio,+)def test_load_from_obs_env(monkeypatch):@@ -68,3 +74,97 @@ def test_load_raises_when_missing(monkeypatch):with patch("jiuwenswarm.common.config.get_config", return_value={}):with pytest.raises(RuntimeError, match="OBS_URL"):load_minio_upload_config()+++def test_huawei_obs_enables_virtual_style_endpoint(tmp_path):+ cfg = MinioUploadConfig(+ endpoint="obs.cn-north-4.myhuaweicloud.com",+ access_key="ak",+ secret_key="sk",+ bucket="jiuwenswarm-ee",+ secure=True,+ region="cn-north-4",+ )+ local = tmp_path / "a.txt"+ local.write_bytes(b"hi")++ fake_client = MagicMock()+ fake_client.bucket_exists.return_value = True+ fake_client.presigned_get_object.return_value = (+ "https://jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com/uploads/x"+ )++ with patch(+ "minio.Minio",+ return_value=fake_client,+ ) as minio_cls:+ result = upload_local_file_to_minio(cfg, str(local), filename="a.txt")++ minio_cls.assert_called_once()+ fake_client.enable_virtual_style_endpoint.assert_called_once_with()+ fake_client.fput_object.assert_called_once()+ assert result["name"] == "a.txt"+ assert "url" in result+++def test_self_hosted_minio_skips_virtual_style_endpoint(tmp_path):+ cfg = MinioUploadConfig(+ endpoint="minio-headless.default:9000",+ access_key="ak",+ secret_key="sk",+ bucket="b",+ secure=False,+ )+ local = tmp_path / "a.txt"+ local.write_bytes(b"hi")++ fake_client = MagicMock()+ fake_client.bucket_exists.return_value = True+ fake_client.presigned_get_object.return_value = "http://minio/uploads/x"++ with patch("minio.Minio", return_value=fake_client):+ upload_local_file_to_minio(cfg, str(local), filename="a.txt")++ fake_client.enable_virtual_style_endpoint.assert_not_called()+++def test_huawei_obs_virtual_style_helpers_aligned():+ endpoint = "obs.cn-north-4.myhuaweicloud.com"+ bucket = "jiuwenswarm-ee"+ assert huawei_obs_needs_virtual_style(endpoint, bucket) is True+ assert (+ huawei_obs_virtual_hosted_bucket_host(endpoint, bucket)+ == "jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com"+ )+ # Case-insensitive Huawei marker.+ assert huawei_obs_needs_virtual_style(+ "OBS.CN-NORTH-4.MYHUAWEICLOUD.COM", bucket+ ) is True+ # Legacy OBS_URL already embeds bucket: do not double-prefix.+ legacy = "jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com"+ assert huawei_obs_needs_virtual_style(legacy, bucket) is False+ assert huawei_obs_virtual_hosted_bucket_host(legacy, bucket) is None+++def test_huawei_obs_skips_virtual_style_when_url_embeds_bucket(tmp_path):+ cfg = MinioUploadConfig(+ endpoint="jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com",+ access_key="ak",+ secret_key="sk",+ bucket="jiuwenswarm-ee",+ secure=True,+ region="cn-north-4",+ )+ local = tmp_path / "a.txt"+ local.write_bytes(b"hi")++ fake_client = MagicMock()+ fake_client.bucket_exists.return_value = True+ fake_client.presigned_get_object.return_value = (+ "https://jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com/uploads/x"+ )++ with patch("minio.Minio", return_value=fake_client):+ upload_local_file_to_minio(cfg, str(local), filename="a.txt")++ fake_client.enable_virtual_style_endpoint.assert_not_called()diff --git a/tests/unit_tests/test_outbound_file_materialize.py b/tests/unit_tests/test_outbound_file_materialize.pyindex 67635e901a..56c369b306 100644--- a/tests/unit_tests/test_outbound_file_materialize.py+++ b/tests/unit_tests/test_outbound_file_materialize.py@@ -126,6 +126,7 @@ def test_materialize_outbound_files_rewrites_to_proxy_href():def test_assert_minio_url_allowed_rejects_foreign_host():class _Cfg:endpoint = "127.0.0.1:9000"+ bucket = "jiuwenclaw"public_base_url = ""with patch(@@ -142,6 +143,46 @@ def test_assert_minio_url_allowed_rejects_foreign_host():assert_minio_url_allowed("http://127.0.0.1/bucket/obj")+def test_assert_minio_url_allowed_accepts_huawei_obs_virtual_host():+ class _Cfg:+ endpoint = "obs.cn-north-4.myhuaweicloud.com"+ bucket = "jiuwenswarm-ee"+ public_base_url = ""++ with patch(+ "jiuwenswarm.channels.web.minio_upload.load_minio_upload_config",+ return_value=_Cfg(),+ ):+ assert_minio_url_allowed(+ "https://jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com/uploads/x"+ )+ assert_minio_url_allowed("https://obs.cn-north-4.myhuaweicloud.com/uploads/x")+ with pytest.raises(ValueError, match="not allowed"):+ assert_minio_url_allowed(+ "https://other-bucket.obs.cn-north-4.myhuaweicloud.com/uploads/x"+ )+++def test_assert_minio_url_allowed_legacy_bucket_embedded_endpoint():+ class _Cfg:+ endpoint = "jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com"+ bucket = "jiuwenswarm-ee"+ public_base_url = ""++ with patch(+ "jiuwenswarm.channels.web.minio_upload.load_minio_upload_config",+ return_value=_Cfg(),+ ):+ # Endpoint itself remains allowed; do not require double-prefixed host.+ assert_minio_url_allowed(+ "https://jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com/uploads/x"+ )+ with pytest.raises(ValueError, match="not allowed"):+ assert_minio_url_allowed(+ "https://jiuwenswarm-ee.jiuwenswarm-ee.obs.cn-north-4.myhuaweicloud.com/x"+ )++class _Upstream:status_code = 200headers = {"Content-Type": "text/markdown", "Content-Length": "4"}