diff --git a/agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py b/agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py index 0539d45..273c813 100644 --- a/agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py +++ b/agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py @@ -59,3 +59,61 @@ def Download(self, req): assert result["saved_to"] == str(out) assert out.read_bytes() == b"ok" + + +def test_backend_helpers_work_with_real_up_service(tmp_path, monkeypatch): + import hashlib + import io + import json + from urllib.parse import parse_qsl, urlsplit + + import requests + from hiagent_api.up import UpService + from requests.adapters import BaseAdapter + + content = b"harness round trip" + digest = hashlib.sha256(content).hexdigest() + sent = [] + + class _Adapter(BaseAdapter): + def send(self, request, **kwargs): + body = request.body.read() if hasattr(request.body, "read") else request.body + query = dict(parse_qsl(urlsplit(request.url).query)) + sent.append((request, query, body or b"")) + resp = requests.Response() + resp.status_code = 200 + if query["Action"] == "UploadRaw": + payload = {"Result": {"Path": "/p", "Sha256": digest, "Size": len(content)}} + resp.raw = io.BytesIO(json.dumps(payload).encode()) + elif query["Action"] == "DownloadKey": + resp.raw = io.BytesIO(json.dumps({"Result": {"Key": "k"}}).encode()) + else: + resp.headers["Content-Length"] = str(len(content)) + resp.raw = io.BytesIO(content) + resp.request = request + return resp + + def close(self): + pass + + monkeypatch.setattr(hiagent_backend, "ensure_volc_credentials", lambda: None) + service = UpService(endpoint="https://up.example.com", region="cn-north-1") + service.set_ak("AKLTharness") + service.set_sk("harness-secret") + service.session.mount("https://", _Adapter()) + + source = tmp_path / "in.txt" + source.write_bytes(content) + uploaded = hiagent_backend.upload_raw_file(service, source, file_id="cli-0001") + assert uploaded == {"id": "cli-0001", "path": "/p", "sha256": digest, "size": len(content)} + + out = tmp_path / "out" / "file.txt" + hiagent_backend.download_file(service, path="/p", save_to=out) + assert out.read_bytes() == content + + assert [q["Action"] for _, q, _ in sent] == ["UploadRaw", "DownloadKey", "Download"] + upload_request, upload_query, upload_body = sent[0] + assert upload_body == content + assert upload_request.headers["X-Content-Sha256"] == digest + assert "Sha256" not in upload_query + assert all(r.method == "POST" and "Authorization" in r.headers for r, _, _ in sent) diff --git a/libs/api/examples/up/up_full.py b/libs/api/examples/up/up_full.py index 6b0d73a..342a82c 100644 --- a/libs/api/examples/up/up_full.py +++ b/libs/api/examples/up/up_full.py @@ -15,10 +15,10 @@ import hashlib import os import uuid -from dotenv import load_dotenv -from hiagent_api.up import UpService +from dotenv import load_dotenv from hiagent_api import up_types +from hiagent_api.up import UpService load_dotenv() @@ -37,7 +37,7 @@ os.path.abspath(__file__)), "test_data/test.txt") test_file_hash = hashlib.sha256(open(test_file, 'rb').read()).hexdigest() req_params = up_types.UploadRawRequest(Id=uuid.uuid4().hex, - ContentType="plain/text", + ContentType="text/plain", Expire="15h", Sha256=test_file_hash) uploadraw_resp = {} diff --git a/libs/api/examples/up/up_uploadraw.py b/libs/api/examples/up/up_uploadraw.py index 289cda0..d4c84bf 100644 --- a/libs/api/examples/up/up_uploadraw.py +++ b/libs/api/examples/up/up_uploadraw.py @@ -17,7 +17,6 @@ import uuid from dotenv import load_dotenv - from hiagent_api.up import UpService from hiagent_api.up_types import UploadRawRequest @@ -30,10 +29,11 @@ test_file = os.path.join(os.path.dirname( os.path.abspath(__file__)), "test_data/test.txt") test_file_hash = hashlib.sha256(open(test_file, 'rb').read()).hexdigest() + # Sha256 可以省略,SDK 会先流式计算一遍;ContentType 建议填文件的真实类型 req_params = UploadRawRequest(Id=uuid.uuid4().hex, - ContentType="plain/text", + ContentType="text/plain", Expire="15h", - Sha256=test_file_hash) + Filename="test.txt") with open(test_file, "rb") as f: resp = up.UploadRaw(req_params, file=f) assert resp.Sha256 == test_file_hash, "SHA256 mismatch" diff --git a/libs/api/hiagent_api/_up_signer.py b/libs/api/hiagent_api/_up_signer.py new file mode 100644 index 0000000..8362775 --- /dev/null +++ b/libs/api/hiagent_api/_up_signer.py @@ -0,0 +1,162 @@ +# coding:utf-8 +# Copyright (c) 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Signs UP requests the way UP verifies them. + +UP rebuilds the canonical request from what it received, so the signer only +reads the method, URL and ``X-Content-Sha256`` of the request that is about to +be sent. ``host`` is not signed, so a gateway that rewrites Host does not break +verification. Ported from the Java SDK's ``UpSigner``. +""" + +import hashlib +import hmac +import re +from datetime import datetime, timezone +from typing import Dict, List, Optional, Tuple +from urllib.parse import quote, unquote, unquote_plus, urlsplit + +SERVICE = "up" +HEADER_DATE = "X-Date" +HEADER_CONTENT_SHA256 = "X-Content-Sha256" +HEADER_SECURITY_TOKEN = "X-Security-Token" +HEADER_AUTHORIZATION = "Authorization" + +_ALGORITHM = "HMAC-SHA256" +_SIGNED_HEADERS = "x-content-sha256;x-date" +_X_DATE_FORMAT = "%Y%m%dT%H%M%SZ" +_SHORT_DATE_LENGTH = 8 +_UNRESERVED = "-_.~" +_HEADER_SAFE = re.compile(r"[\x21-\x7e]+") + + +def sign( + method: str, + url: str, + payload_hash: str, + *, + ak: Optional[str], + sk: Optional[str], + region: str, + session_token: Optional[str] = None, + now: Optional[datetime] = None, +) -> Dict[str, str]: + """Return the headers to add to the request: ``X-Date``, ``Authorization`` + and, for STS credentials, ``X-Security-Token``. + + ``payload_hash`` must be the value sent as ``X-Content-Sha256``. Raises + ValueError when the credentials are unusable; error messages never contain + credential values. + """ + ak, sk, token = check_credentials(ak, sk, session_token) + signed_at = (now or datetime.now(timezone.utc)).astimezone(timezone.utc) + x_date = signed_at.strftime(_X_DATE_FORMAT) + short_date = x_date[:_SHORT_DATE_LENGTH] + + canonical = canonical_request(method, url, payload_hash, x_date) + signature = hmac.new( + _signing_key(sk, short_date, region), + string_to_sign(x_date, region, canonical).encode("utf-8"), + hashlib.sha256, + ).hexdigest() + + signed = { + HEADER_DATE: x_date, + HEADER_AUTHORIZATION: ( + f"{_ALGORITHM} Credential={ak}/{_credential_scope(short_date, region)}, " + f"SignedHeaders={_SIGNED_HEADERS}, Signature={signature}" + ), + } + if token: + signed[HEADER_SECURITY_TOKEN] = token + return signed + + +def canonical_request(method: str, url: str, payload_hash: str, x_date: str) -> str: + parts = urlsplit(url) + path = unquote(parts.path) or "/" + payload_hash = payload_hash.strip() + return "\n".join( + [ + method.upper(), + path, + canonical_query_string(parts.query), + f"x-content-sha256:{payload_hash}", + f"x-date:{x_date}", + "", + _SIGNED_HEADERS, + payload_hash, + ] + ) + + +def string_to_sign(x_date: str, region: str, canonical: str) -> str: + return "\n".join( + [ + _ALGORITHM, + x_date, + _credential_scope(x_date[:_SHORT_DATE_LENGTH], region), + hashlib.sha256(canonical.encode("utf-8")).hexdigest(), + ] + ) + + +def canonical_query_string(raw_query: str) -> str: + """Decode every pair the way Go's url.ParseQuery does ("+" is a space), + sort by name keeping the order of repeated names, and re-encode.""" + grouped: Dict[str, List[str]] = {} + for pair in raw_query.split("&"): + if not pair: + continue + name, _, value = pair.partition("=") + grouped.setdefault(unquote_plus(name), []).append(unquote_plus(value)) + return "&".join( + f"{sign_encode(name)}={sign_encode(value)}" + for name in sorted(grouped) + for value in grouped[name] + ) + + +def sign_encode(value: str) -> str: + """RFC 3986: only A-Z a-z 0-9 - _ . ~ stay literal; space is %20.""" + return quote(value, safe=_UNRESERVED) + + +def check_credentials( + ak: Optional[str], sk: Optional[str], session_token: Optional[str] +) -> Tuple[str, str, str]: + """Validate credentials and return (ak, sk, stripped session token).""" + if not ak or not ak.strip() or not sk or not sk.strip(): + raise ValueError("UP request signing requires both AccessKey and SecretKey") + # Checked here because requests would quote the whole header value in its + # InvalidHeader message. + if not _HEADER_SAFE.fullmatch(ak): + raise ValueError("AccessKey contains characters not allowed in an HTTP header") + token = (session_token or "").strip() + if token and not _HEADER_SAFE.fullmatch(token): + raise ValueError( + "session token contains characters not allowed in an HTTP header" + ) + return ak, sk, token + + +def _credential_scope(short_date: str, region: str) -> str: + return f"{short_date}/{region}/{SERVICE}/request" + + +def _signing_key(sk: str, short_date: str, region: str) -> bytes: + key = sk.encode("utf-8") + for part in (short_date, region, SERVICE, "request"): + key = hmac.new(key, part.encode("utf-8"), hashlib.sha256).digest() + return key diff --git a/libs/api/hiagent_api/up.py b/libs/api/hiagent_api/up.py index 5cae5de..eb6e5e3 100644 --- a/libs/api/hiagent_api/up.py +++ b/libs/api/hiagent_api/up.py @@ -12,21 +12,43 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import contextlib +import hashlib import json -from typing import BinaryIO +import os +import shutil +import stat +import uuid +from typing import Any, BinaryIO, Dict, Optional, Tuple from urllib.parse import urlparse +import requests +from requests.structures import CaseInsensitiveDict +from volcengine import VERSION as VOLC_SDK_VERSION from volcengine.ApiInfo import ApiInfo -from volcengine.auth.SignerV4 import SignerV4 from volcengine.base.Service import Service from volcengine.Credentials import Credentials from volcengine.ServiceInfo import ServiceInfo -from hiagent_api import up_types +from hiagent_api import _up_signer, up_types from hiagent_api.product_code import PRODUCT_CODE_HEADER, normalize_product_code +_API_VERSION = "2022-01-01" +_JSON = "application/json" +_OCTET_STREAM = "application/octet-stream" +_EMPTY_SHA256 = hashlib.sha256(b"").hexdigest() +_CHUNK_SIZE = 64 * 1024 + class UpService(Service): + """Client for the UP (upload) service. + + Every request is a POST signed in headers by ``_up_signer`` from the exact + method, URL and ``X-Content-Sha256`` that go on the wire. Without any + AK/SK configured, requests are sent unsigned and the UP deployment decides + whether to serve them. + """ + def __init__(self, endpoint="https://open.volcengineapi.com", region="cn-north-1"): self.service_info = UpService.get_service_info(endpoint, region) self.api_info = UpService.get_api_info() @@ -65,202 +87,303 @@ def get_service_info(endpoint, region): @staticmethod def get_api_info(): - api_info = { - "UploadRaw": ApiInfo( - "POST", "/up", {"Action": "UploadRaw", "Version": "2022-01-01"}, {}, {} - ), - "LongLive": ApiInfo( - "POST", "/up", {"Action": "LongLive", "Version": "2022-01-01"}, {}, {} - ), - "DownloadKey": ApiInfo( - "POST", - "/up", - {"Action": "DownloadKey", "Version": "2022-01-01"}, - {}, - {}, - ), - "Download": ApiInfo( - "POST", "/down", {"Action": "Download", "Version": "2022-01-01"}, {}, {} - ), - "Delete": ApiInfo( - "POST", "/up", {"Action": "Delete", "Version": "2022-01-01"}, {}, {} - ), + def api(path: str, action: str) -> ApiInfo: + return ApiInfo("POST", path, {"Action": action, "Version": _API_VERSION}, {}, {}) + + return { + "UploadRaw": api("/up", "UploadRaw"), + "LongLive": api("/up", "LongLive"), + "DownloadKey": api("/up", "DownloadKey"), + "Download": api("/down", "Download"), + "Delete": api("/up", "Delete"), } - return api_info def UploadRaw( self, params: up_types.UploadRawRequest, file: BinaryIO ) -> up_types.UploadRawResponse: - """不分片的上传接口 + """不分片上传文件,UP 会同时完成长期化。 Args: - params (Dict): - - `File (BinaryIO)`: 必选, 文件流 - `Id (str)`: 必选, 文件 ID - `ContentType (str)`: 可选, 文件类型 - `Expire (str)`: 可选, 文件过期时间,格式为 15h + params: `Id` 必填;`Sha256` 不传或为空白时 SDK 先从文件当前位置流式 + 计算一遍(此时文件对象必须可 seek);`ContentType` 不传时按 + application/octet-stream 上传;`Expire`、`Filename`、`ImageCompress` 可选。 + file: 文件对象,从当前位置读到末尾,流式发送。 Returns: - Dict: - - `Path (str)`: 文件路径 - 示例值: path/to/file - - `Sha256 (str)`: 文件的哈希值 - 示例值: xxxx - - `Size (int)`: 文件的大小,单位为字节 - 示例值: 1024 - + UploadRawResponse: `Path`、`Sha256`、`Size`、`ShortLink`、`PresignKey`。 """ - api = "UploadRaw" - if api not in self.api_info: - raise Exception("no such api") - api_info = self.api_info[api] - r = self.prepare_request(api_info, params.model_dump()) - if params.ContentType != "": - r.headers["Content-Type"] = params.ContentType - else: - r.headers["Content-Type"] = "application/octet-stream" - r.headers["X-Content-Sha256"] = params.Sha256 - SignerV4.sign_url(r, self.service_info.credentials) - - url = r.build() - - resp = self.session.post( - url, - headers=r.headers, - data=file, - timeout=( - self.service_info.connection_timeout, - self.service_info.socket_timeout, - ), - ) - if resp.status_code == 200: - res_json = json.loads(resp.text) - if "Result" not in res_json.keys(): - Exception(f"no Result in response: {resp.text}") - return up_types.UploadRawResponse.model_validate(res_json["Result"]) - else: - raise Exception(resp.text) + _require(params.Id, "UploadRawRequest.Id") + self._credentials() + content_sha256 = _normalize_sha256(params.Sha256) or _sha256_from_here(file) + query = { + "Expire": params.Expire, + "Id": params.Id, + "Filename": params.Filename, + "ImageCompress": params.ImageCompress, + } + content_type = params.ContentType or _OCTET_STREAM + resp = self._send("UploadRaw", query, file, content_type, content_sha256) + return up_types.UploadRawResponse.model_validate(_result(resp)) def LongLive(self, params: up_types.LongLiveRequest) -> up_types.LongLiveResponse: """将某个文件转换成长效存储的文件。 Args: - params (Dict): - - `Path (str)`: 文件路径 - 示例值: path/to/file - - `Id (str)`: 必选, 文件 ID + params: `Path`、`Id` 必填(请求体中以 `ID` 发送),`Filename` 可选。 Returns: - Dict: - - `Path (str)`: 文件路径 - 示例值: path/to/file - - `Size (int)`: 文件的大小,单位为字节 - 示例值: 1024 - + LongLiveResponse: `Path`、`Size`、`Sha256`、`ShortLink`。 """ - return up_types.LongLiveResponse.model_validate( - self.__request("LongLive", params.model_dump()) - ) + _require(params.Id, "LongLiveRequest.ID") + resp = self._send_json("LongLive", params.model_dump(by_alias=True, exclude_none=True)) + return up_types.LongLiveResponse.model_validate(_result(resp)) def DownloadKey( self, params: up_types.DownloadKeyRequest ) -> up_types.DownloadKeyResponse: - """将某个文件转换成长效存储的文件。 + """获取下载文件用的 Key。 Args: - params (Dict): - - `Path (str)`: 文件路径 - 示例值: path/to/file + params: `Path` 与 `Sha256` 二选一。 Returns: - Dict: + DownloadKeyResponse: `Key`、`Size`、`ContentType`。 + """ + query = {"Path": params.Path, "Sha256": _normalize_sha256(params.Sha256)} + resp = self._send("DownloadKey", query, b"", _JSON, _EMPTY_SHA256) + return up_types.DownloadKeyResponse.model_validate(_result(resp)) - `Key (str)`: 文件下载时可用的 key - 示例值: xxxx + def Download(self, params: up_types.DownloadRequest) -> None: + """下载文件到 `SaveTo`。 - """ - api = "DownloadKey" - res = self.get(api, params.model_dump(), dict()) - if res == "": - raise Exception("empty response") - res_json = json.loads(res) - if "Result" not in res_json.keys(): - Exception(f"no Result in response: {res}") - return up_types.DownloadKeyResponse.model_validate(res_json["Result"]) - - def Download(self, params: up_types.DownloadRequest) -> up_types.DownloadResponse: - """下载某个文件 + 先写入同目录下的临时文件,完整收到后再原子替换目标;失败时不留下临时 + 文件,也不改动已有的目标文件。参数都放在 query 中(`SaveTo` 除外), + 与 UP 按 query 中的 `Key` 放行下载的方式一致。 Args: - params (Dict): + params: `Key`、`SaveTo` 必填;`Path` 与 `Sha256` 二选一; + `ID`、`Filename`、`ImageCompress` 可选。 + """ + if not params.SaveTo or not params.SaveTo.strip(): + raise ValueError("DownloadRequest.SaveTo must be set") + target = _download_target(params.SaveTo) + # SaveTo is excluded from model_dump, so the dump is exactly the query. + query = { + **params.model_dump(by_alias=True, exclude_none=True), + "Sha256": _normalize_sha256(params.Sha256), + } + with self._send("Download", query, b"", _JSON, _EMPTY_SHA256, stream=True) as resp: + _check_status(resp) + _save_atomically(resp, target) - `Path (str)`: 文件路径 - 示例值: path/to/file + def Delete(self, params: up_types.DeleteRequest) -> Dict[str, Any]: + """删除文件的一条关联;关联全部删除后文件在下次回收时删除。 - `Key (str)`: 文件下载时可用的 key - 示例值: xxxx + Args: + params: `Id`、`Sha256` 必填。 - `SaveTo (str)`: 文件保存路径` Returns: - Dict: + UP 返回的 `Result`(成功时为空 dict)。 """ - api = "Download" - if api not in self.api_info: - raise Exception("no such api") - api_info = self.api_info[api] - - r = self.prepare_request(api_info, params.model_dump(), 0) - - SignerV4.sign(r, self.service_info.credentials) - - url = r.build(0) - resp = self.session.get( + body = params.model_dump(by_alias=True, exclude_none=True) + # Required field: a blank value is sent as "" for UP to reject, not + # dropped like the optional Sha256 fields elsewhere. + body["Sha256"] = params.Sha256.strip().lower() + return _result(self._send_json("Delete", body)) + + def _send_json(self, action: str, body: Dict[str, Any]) -> requests.Response: + payload = json.dumps(body, ensure_ascii=False).encode("utf-8") + return self._send(action, {}, payload, _JSON, hashlib.sha256(payload).hexdigest()) + + def _send( + self, + action: str, + query: Dict[str, Any], + body: Any, + content_type: str, + content_sha256: str, + stream: bool = False, + ) -> requests.Response: + api_info = self.api_info[action] + url = ( + f"{self.service_info.scheme}://{self.service_info.host}{api_info.path}" + f"?{_encode_query({**api_info.query, **query})}" + ) + headers = CaseInsensitiveDict(self.service_info.header) + headers["Content-Type"] = content_type + headers[_up_signer.HEADER_CONTENT_SHA256] = content_sha256 + headers["User-Agent"] = f"volc-sdk-python/{VOLC_SDK_VERSION}" + + credentials = self._credentials() + if credentials is not None: + ak, sk, token = credentials + signing_headers = _up_signer.sign( + api_info.method, + url, + content_sha256, + ak=ak, + sk=sk, + region=self.service_info.credentials.region, + session_token=token, + ) + headers.update(signing_headers) + return self.session.request( + api_info.method, url, - headers=r.headers, + headers=headers, + data=body, timeout=( self.service_info.connection_timeout, self.service_info.socket_timeout, ), - stream=True, + stream=stream, + # A redirect would resend the request with a signature for the old + # URL (as GET for 301/302) and carry X-Security-Token to another host. + allow_redirects=False, ) - if resp.status_code == 200: - with open(params.SaveTo, "wb") as f: - for chunk in resp.iter_content(chunk_size=1024): - if chunk: - f.write(chunk) - else: - raise Exception(resp.text) - - def Delete(self, params: up_types.DeleteRequest) -> up_types.DeleteResponse: - """删除某个文件 - - Args: - params (Dict): - `Id (str)`: 必选, 文件 ID + def _credentials(self) -> Optional[Tuple[str, str, str]]: + """None when no AK, SK or STS token is configured (send unsigned); + raises ValueError for half-configured or malformed credentials.""" + credentials = self.service_info.credentials + if ( + _is_blank(credentials.ak) + and _is_blank(credentials.sk) + and _is_blank(credentials.session_token) + ): + return None + return _up_signer.check_credentials( + credentials.ak, credentials.sk, credentials.session_token + ) - `Sha256 (str)`: 文件的哈希值 - 示例值: xxxx - Returns: - Dict: - """ - return self.__request("Delete", params.model_dump()) - - def __request(self, action, params): - res = self.json(action, dict(), json.dumps(params)) - if res == "": - raise Exception("empty response") - res_json = json.loads(res) - if "Result" not in res_json.keys(): - return res_json - return res_json["Result"] +def _encode_query(params: Dict[str, Any]) -> str: + pairs = [] + for name, value in params.items(): + if value is None: + continue + if isinstance(value, bool): + value = "true" if value else "false" + pairs.append(f"{_up_signer.sign_encode(name)}={_up_signer.sign_encode(str(value))}") + return "&".join(pairs) + + +def _check_status(resp: requests.Response) -> None: + if resp.status_code == 200: + return + if resp.is_redirect: + raise Exception( + f"UP answered HTTP {resp.status_code} redirecting to " + f"{resp.headers['Location']}; redirects are not followed, " + "check the endpoint" + ) + raise Exception(resp.text or f"UP answered HTTP {resp.status_code}") + + +def _result(resp: requests.Response) -> Any: + _check_status(resp) + data = resp.json() + if not isinstance(data, dict) or "Result" not in data: + raise Exception(f"no Result in response: {resp.text}") + return data["Result"] + + +def _require(value: Optional[str], name: str) -> None: + # Same test as UP's validate:"required": only None and "" are rejected. + if value is None or value == "": + raise ValueError(f"{name} must be set") + + +def _is_blank(value: Optional[str]) -> bool: + return not value or not value.strip() + + +def _normalize_sha256(value: Optional[str]) -> Optional[str]: + if _is_blank(value): + return None + return value.strip().lower() + + +def _sha256_from_here(file: BinaryIO) -> str: + """Hash the file from its current position to the end, then seek back so + the upload sends exactly the hashed bytes.""" + # Probe tell()/seek() rather than seekable(): Python 3.10's + # SpooledTemporaryFile (FastAPI's UploadFile.file) seeks fine but has no + # seekable(). + try: + start = file.tell() + file.seek(start) + except (AttributeError, OSError, ValueError): + raise ValueError( + "UploadRawRequest.Sha256 must be set when the file object cannot seek" + ) from None + digest = hashlib.sha256() + for chunk in iter(lambda: file.read(_CHUNK_SIZE), b""): + digest.update(chunk) + file.seek(start) + return digest.hexdigest() + + +def _download_target(save_to: str) -> str: + """Resolve SaveTo and reject what an atomic replace must not touch, before + anything is downloaded.""" + # realpath drops a trailing separator, which would turn "newdir/" into a + # file called newdir; open("newdir/", "wb") refused it. + if save_to.endswith(tuple(sep for sep in (os.sep, os.altsep) if sep)): + raise IsADirectoryError(f"DownloadRequest.SaveTo is a directory: {save_to}") + # realpath: a symlinked SaveTo gets its target replaced, as open(SaveTo) did. + target = os.path.realpath(save_to) + if not os.path.isdir(os.path.dirname(target)): + raise FileNotFoundError( + f"DownloadRequest.SaveTo's directory does not exist: {save_to}" + ) + try: + mode = os.stat(target).st_mode + except FileNotFoundError: + return target + if stat.S_ISDIR(mode): + raise IsADirectoryError(f"DownloadRequest.SaveTo is a directory: {save_to}") + if not stat.S_ISREG(mode): + # Replacing a device or FIFO (e.g. /dev/null as root) would swap the + # node itself for a regular file. + raise ValueError(f"DownloadRequest.SaveTo is not a regular file: {save_to}") + return target + + +def _save_atomically(resp: requests.Response, target: str) -> None: + directory = os.path.dirname(target) + # Fixed length: appending to the target's name could exceed NAME_MAX. + temp = os.path.join(directory, f".up-{uuid.uuid4().hex}.part") + exists = os.path.exists(target) + # Overwriting: stay private until the old mode is copied over, so a 0600 + # file's content is never readable through the partial file. New file: + # 0o666 & ~umask, like open(). + mode = 0o600 if exists else 0o666 + # Outside the try: on a name collision there is nothing of ours to remove. + out = open(temp, "xb", opener=lambda path, flags: os.open(path, flags, mode)) + try: + written = 0 + with out: + for chunk in resp.iter_content(chunk_size=_CHUNK_SIZE): + out.write(chunk) + written += len(chunk) + _check_length(resp, written) + if exists: + shutil.copymode(target, temp) + os.replace(temp, target) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.remove(temp) + raise + + +def _check_length(resp: requests.Response, written: int) -> None: + """urllib3 1.26 does not enforce Content-Length, so a short read would + otherwise be installed as a complete download.""" + declared = resp.headers.get("Content-Length") + if declared is None or "Content-Encoding" in resp.headers: + return + if written != int(declared): + raise Exception( + f"download incomplete: received {written} bytes, Content-Length is {declared}" + ) diff --git a/libs/api/hiagent_api/up_types.py b/libs/api/hiagent_api/up_types.py index c6b37fa..b8eeb97 100644 --- a/libs/api/hiagent_api/up_types.py +++ b/libs/api/hiagent_api/up_types.py @@ -12,40 +12,71 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +from typing import Optional + from pydantic import BaseModel, Field +_SHA256_EXAMPLE = "84add60e154d3625fa5424bfb98bdc5782a078853a4a2c0845b906985ebceb8c" + class UploadRawRequest(BaseModel): - Expire: str = Field( - title="文件的过期时间", description="文件的过期时间", example="15h" - ) Id: str = Field( - title="文件 ID", description="文件 ID", example="wcxxxxxxxxxxxxxxxxxxx" + title="文件 ID", + description="文件 ID,必填。删除文件时需要传同一个 ID", + example="wcxxxxxxxxxxxxxxxxxxx", ) - ContentType: str = Field( + Expire: Optional[str] = Field( + default=None, + title="关联的过期时间", + description="Go duration 格式,如 15h;不传、空串、0 或 -1 表示不过期", + example="15h", + ) + ContentType: Optional[str] = Field( + default=None, title="content type", - description="content type", - example="application/octet-stream", + description="文件的真实类型;不传时按 application/octet-stream 上传", + example="image/png", ) - Sha256: str = Field( - title="文件的哈希值", description="文件的哈希值", example="sha256hashvalue" + Sha256: Optional[str] = Field( + default=None, + title="文件的哈希值", + description="文件的 SHA-256;不传或为空白时 SDK 先流式计算一遍", + example=_SHA256_EXAMPLE, + ) + Filename: Optional[str] = Field( + default=None, title="文件名", description="文件名", example="hello.pdf" + ) + ImageCompress: Optional[bool] = Field( + default=None, title="图片压缩", description="是否开启图片压缩", example=True ) class UploadRawResponse(BaseModel): Path: str = Field(title="文件路径", description="文件路径", example="/path/to/file") Sha256: str = Field( - title="文件的哈希值", description="文件的哈希值", example="sha256hashvalue" + title="文件的哈希值", description="文件的哈希值", example=_SHA256_EXAMPLE ) Size: int = Field( title="文件的大小", description="文件的大小,单位为字节", example=1024 ) + ShortLink: Optional[str] = Field( + default=None, title="文件短链", description="文件短链", example="JAVwLYB3XVr" + ) + PresignKey: Optional[str] = Field( + default=None, title="presign key", description="presign key", example="xxxxxxx" + ) class LongLiveRequest(BaseModel): Path: str = Field(title="文件路径", description="文件路径", example="/path/to/file") Id: str = Field( - title="文件 ID", description="文件 ID", example="wcxxxxxxxxxxxxxxxxxxx" + title="文件 ID", + description="文件 ID,必填。请求体中按 UP 契约以 ID 发送", + example="wcxxxxxxxxxxxxxxxxxxx", + serialization_alias="ID", + ) + Filename: Optional[str] = Field( + default=None, title="文件名", description="文件名", example="hello.pdf" ) @@ -54,21 +85,70 @@ class LongLiveResponse(BaseModel): Size: int = Field( title="文件的大小", description="文件的大小,单位为字节", example=1024 ) + Sha256: Optional[str] = Field( + default=None, title="文件的哈希值", description="文件的哈希值", example=_SHA256_EXAMPLE + ) + ShortLink: Optional[str] = Field( + default=None, title="文件短链", description="文件短链", example="JAVwLYB3XVr" + ) class DownloadKeyRequest(BaseModel): - Path: str = Field(title="文件路径", description="文件路径", example="/path/to/file") + Path: Optional[str] = Field( + default=None, + title="文件路径", + description="文件路径,与 Sha256 二选一", + example="/path/to/file", + ) + Sha256: Optional[str] = Field( + default=None, + title="文件的哈希值", + description="文件的 SHA-256,与 Path 二选一", + example=_SHA256_EXAMPLE, + ) class DownloadKeyResponse(BaseModel): Key: str = Field(title="文件 key", description="文件 key", example="filekey") + Size: Optional[int] = Field( + default=None, title="文件的大小", description="文件的大小,单位为字节", example=1024 + ) + ContentType: Optional[str] = Field( + default=None, title="content type", description="content type", example="image/png" + ) class DownloadRequest(BaseModel): Key: str = Field(title="文件 key", description="文件 key", example="filekey") - Path: str = Field(title="文件路径", description="文件路径", example="/path/to/file") + Path: Optional[str] = Field( + default=None, + title="文件路径", + description="文件路径,与 Sha256 二选一", + example="/path/to/file", + ) + Sha256: Optional[str] = Field( + default=None, + title="文件的哈希值", + description="文件的 SHA-256,与 Path 二选一", + example=_SHA256_EXAMPLE, + ) + ID: Optional[str] = Field( + default=None, + title="文件 ID", + description="文件 ID,影响响应中的文件名", + example="wcxxxxxxxxxxxxxxxxxxx", + ) + Filename: Optional[str] = Field( + default=None, title="文件名", description="文件名", example="hello.pdf" + ) + ImageCompress: Optional[bool] = Field( + default=None, title="图片压缩", description="是否下载压缩后的图片", example=True + ) SaveTo: str = Field( - title="保存路径", description="保存路径", example="/path/to/file" + title="保存路径", + description="本地保存路径,只在本地使用,不会发送给 UP", + example="/path/to/file", + exclude=True, ) @@ -81,7 +161,7 @@ class DeleteRequest(BaseModel): title="文件 ID", description="文件 ID", example="wcxxxxxxxxxxxxxxxxxxx" ) Sha256: str = Field( - title="文件的哈希值", description="文件的哈希值", example="sha256hashvalue" + title="文件的哈希值", description="文件的哈希值", example=_SHA256_EXAMPLE ) diff --git a/libs/api/tests/data/up_signature_vectors.json b/libs/api/tests/data/up_signature_vectors.json new file mode 100644 index 0000000..30ad416 --- /dev/null +++ b/libs/api/tests/data/up_signature_vectors.json @@ -0,0 +1,64 @@ +{ + "_comment": "Generated offline by UP's own signature verifier (auth.Signing over the materials CheckSignature takes from the received request). Credentials are fixtures, not real.", + "accessKey": "AKLTFIXTUREONLY0000000000", + "secretKey": "fixture-secret-key-not-a-real-credential", + "region": "cn-north-1", + "service": "up", + "vectors": [ + { + "name": "upload-raw-text-root-path", + "method": "POST", + "url": "http://127.0.0.1:31010/?Action=UploadRaw&Version=2023-08-01&Expire=15h&Id=0f3c2a9e", + "xDate": "20261106T080000Z", + "contentSha256": "28212f4b8184bdc7545fe2f7122040bc25bc2dea90533da0752762f07f159053", + "signedHeaders": "x-content-sha256;x-date", + "canonicalRequest": "POST\n/\nAction=UploadRaw&Expire=15h&Id=0f3c2a9e&Version=2023-08-01\nx-content-sha256:28212f4b8184bdc7545fe2f7122040bc25bc2dea90533da0752762f07f159053\nx-date:20261106T080000Z\n\nx-content-sha256;x-date\n28212f4b8184bdc7545fe2f7122040bc25bc2dea90533da0752762f07f159053", + "stringToSign": "HMAC-SHA256\n20261106T080000Z\n20261106/cn-north-1/up/request\n521e7b70960ac5214b7975c406ff241e14938c4ec1652c136e6bacc808d9222a", + "signature": "e967cad0298be59ff6d8e82e5491c06c8fcf25caa6682f4a563e27fbc05aa940" + }, + { + "name": "upload-raw-binary-up-path", + "method": "POST", + "url": "http://127.0.0.1:31010/up/?Action=UploadRaw&Version=2023-08-01&Id=bin-01", + "xDate": "20261106T080000Z", + "contentSha256": "fba2286f9b2db5b8e06a47532f88d8b9f99bb60f9edb1e4c09d1bbf4843120ff", + "signedHeaders": "x-content-sha256;x-date", + "canonicalRequest": "POST\n/up/\nAction=UploadRaw&Id=bin-01&Version=2023-08-01\nx-content-sha256:fba2286f9b2db5b8e06a47532f88d8b9f99bb60f9edb1e4c09d1bbf4843120ff\nx-date:20261106T080000Z\n\nx-content-sha256;x-date\nfba2286f9b2db5b8e06a47532f88d8b9f99bb60f9edb1e4c09d1bbf4843120ff", + "stringToSign": "HMAC-SHA256\n20261106T080000Z\n20261106/cn-north-1/up/request\n8184503230976008c89c581c293dd79a5986e1d12b44bec15aa8cc6c1cbe5549", + "signature": "15e63e2ccadd7bf1d484add1de143ed5236151bcbcb0a33b819a3d4b8eaf6c76" + }, + { + "name": "download-key-reserved-and-unicode-query", + "method": "POST", + "url": "http://127.0.0.1:31010/?Action=DownloadKey&Version=2023-08-01&path=temp%2F%E4%B8%AD%E6%96%87%20%E6%8A%A5%E5%91%8A%20a%2Bb%3Dc%26d%21%27%28%29%2A~.pdf&sha256=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "xDate": "20261106T080000Z", + "contentSha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "signedHeaders": "x-content-sha256;x-date", + "canonicalRequest": "POST\n/\nAction=DownloadKey&Version=2023-08-01&path=temp%2F%E4%B8%AD%E6%96%87%20%E6%8A%A5%E5%91%8A%20a%2Bb%3Dc%26d%21%27%28%29%2A~.pdf&sha256=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\nx-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\nx-date:20261106T080000Z\n\nx-content-sha256;x-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stringToSign": "HMAC-SHA256\n20261106T080000Z\n20261106/cn-north-1/up/request\nac041df9300caf0ba331985d43e91b80c956c0e5c6ae2ecda40dfe7dd2adf4fe", + "signature": "ecc3b2d2895e896d7505b1d118d0039cbb79feb1fffd7180b023cbdc11df8c59" + }, + { + "name": "long-live-json-body", + "method": "POST", + "url": "http://127.0.0.1:31010/?Action=LongLive&Version=2023-08-01", + "xDate": "20261106T080000Z", + "contentSha256": "eba0fe6ff54a0403d21fbb7fdccc8c08a380b53f59d96bb774ac0beecd573519", + "signedHeaders": "x-content-sha256;x-date", + "canonicalRequest": "POST\n/\nAction=LongLive&Version=2023-08-01\nx-content-sha256:eba0fe6ff54a0403d21fbb7fdccc8c08a380b53f59d96bb774ac0beecd573519\nx-date:20261106T080000Z\n\nx-content-sha256;x-date\neba0fe6ff54a0403d21fbb7fdccc8c08a380b53f59d96bb774ac0beecd573519", + "stringToSign": "HMAC-SHA256\n20261106T080000Z\n20261106/cn-north-1/up/request\nddf501d9c7e215cd8c9dd8723acaab78dda1cdf4ddd8ad6af2bb42d0a9dfbe62", + "signature": "e6b624b2d841aef6b99c2f4b289beda01667f36688f4fa5805862a0ca65ba703" + }, + { + "name": "delete-https-domain-up-path", + "method": "POST", + "url": "https://up.example.com/up/?Action=Delete&Version=2023-08-01", + "xDate": "20261231T235959Z", + "contentSha256": "8415acfd048f0ba37e7187effee3d06295ed60c8a0d04355a6b16aefa120a333", + "signedHeaders": "x-content-sha256;x-date", + "canonicalRequest": "POST\n/up/\nAction=Delete&Version=2023-08-01\nx-content-sha256:8415acfd048f0ba37e7187effee3d06295ed60c8a0d04355a6b16aefa120a333\nx-date:20261231T235959Z\n\nx-content-sha256;x-date\n8415acfd048f0ba37e7187effee3d06295ed60c8a0d04355a6b16aefa120a333", + "stringToSign": "HMAC-SHA256\n20261231T235959Z\n20261231/cn-north-1/up/request\nb5df3da4514aecd03d492bf957b1ef2c1519ac82ef71099da0e086731faa2db4", + "signature": "0801a3cceaa46eff77f33ef71d218fc8480a9f5e0c1ebca0e74389cd55ac3845" + } + ] +} diff --git a/libs/api/tests/test_up_download.py b/libs/api/tests/test_up_download.py new file mode 100644 index 0000000..7bd5cdb --- /dev/null +++ b/libs/api/tests/test_up_download.py @@ -0,0 +1,241 @@ +import io +import os +import stat +import sys + +import pytest +from hiagent_api import up_types +from up_fakes import BrokenStream, assert_signed_as_sent, make_service, response + +CONTENT = b"downloaded bytes " * 1024 +OLD = b"previous content that must survive" +UPPER_SHA = "AB" * 32 +LOWER_SHA = "ab" * 32 + + +def _serve(body=CONTENT, status=200, headers=None, raw=None): + if headers is None: + headers = {"Content-Length": str(len(body))} + served = [] + + def respond(sent): + resp = response(status, body, headers, raw) + served.append(resp) + return resp + + respond.served = served + return respond + + +def _download(service, save_to, **fields): + req = up_types.DownloadRequest(Key="k", Path="/p", SaveTo=str(save_to), **fields) + return service.Download(req) + + +def _listing(directory): + return sorted(os.listdir(directory)) + + +def test_writes_file(tmp_path): + service, adapter = make_service(_serve()) + target = tmp_path / "file.bin" + assert _download(service, target) is None + assert target.read_bytes() == CONTENT + assert _listing(tmp_path) == ["file.bin"] + assert_signed_as_sent(adapter.sent[0]) + + +def test_missing_parent_directory_fails_before_sending(tmp_path): + service, adapter = make_service(_serve()) + with pytest.raises(FileNotFoundError): + _download(service, tmp_path / "missing" / "file.bin") + assert adapter.sent == [] + assert _listing(tmp_path) == [] + + +def test_trailing_separator_is_a_directory_path_even_if_missing(tmp_path): + service, adapter = make_service(_serve()) + with pytest.raises(IsADirectoryError): + _download(service, str(tmp_path / "newdir") + os.sep) + assert adapter.sent == [] + assert _listing(tmp_path) == [] + + +def test_long_target_name_within_name_max(tmp_path): + # 234 characters: a legal name, but too long once 39 more are added + # (NAME_MAX is 255 bytes on Linux, 255 characters on macOS). + name = "a" * 230 + ".bin" + service, _ = make_service(_serve()) + _download(service, tmp_path / name) + assert (tmp_path / name).read_bytes() == CONTENT + assert _listing(tmp_path) == [name] + + +def test_parameters_go_in_query_with_empty_body_and_no_save_to(tmp_path): + service, adapter = make_service(_serve()) + req = up_types.DownloadRequest( + Key="k", + Sha256=UPPER_SHA, + ID="file-0001", + Filename="a.pdf", + ImageCompress=False, + SaveTo=str(tmp_path / "f"), + ) + service.Download(req) + sent = adapter.sent[0] + assert sent.path == "/down" + assert sent.query == { + "Action": "Download", + "Version": "2022-01-01", + "Key": "k", + "Sha256": LOWER_SHA, + "ID": "file-0001", + "Filename": "a.pdf", + "ImageCompress": "false", + } + assert sent.body == b"" + assert str(tmp_path) not in sent.url + assert req.Sha256 == UPPER_SHA + + +@pytest.mark.parametrize("save_to", ["", " "]) +def test_blank_save_to_fails_before_sending(save_to): + service, adapter = make_service(_serve()) + with pytest.raises(ValueError, match="SaveTo"): + service.Download(up_types.DownloadRequest(Key="k", Path="/p", SaveTo=save_to)) + assert adapter.sent == [] + + +def test_error_response_creates_no_file(tmp_path): + service, _ = make_service(_serve(body=b'{"error":"key expired"}', status=403, headers={})) + target = tmp_path / "f" + with pytest.raises(Exception, match="key expired"): + _download(service, target) + assert _listing(tmp_path) == [] + + +def test_short_body_keeps_old_file_and_leaves_nothing_behind(tmp_path): + target = tmp_path / "f" + target.write_bytes(OLD) + service, _ = make_service(_serve(headers={"Content-Length": str(len(CONTENT) + 10)})) + with pytest.raises(Exception, match="Content-Length"): + _download(service, target) + assert target.read_bytes() == OLD + assert _listing(tmp_path) == ["f"] + + +def test_interrupted_stream_keeps_old_file_and_leaves_nothing_behind(tmp_path): + target = tmp_path / "f" + target.write_bytes(OLD) + respond = _serve(headers={}, raw=BrokenStream(CONTENT[:100])) + service, _ = make_service(respond) + with pytest.raises(ConnectionResetError): + _download(service, target) + assert target.read_bytes() == OLD + assert _listing(tmp_path) == ["f"] + assert respond.served[0].raw.closed + + +@pytest.mark.parametrize( + "headers", + [{}, {"Content-Length": "1", "Content-Encoding": "gzip"}], + ids=["no-content-length", "content-encoded"], +) +def test_length_check_only_applies_to_plain_declared_bodies(tmp_path, headers): + service, _ = make_service( + lambda sent: response(200, CONTENT, headers, io.BytesIO(CONTENT)) + ) + target = tmp_path / "f" + _download(service, target) + assert target.read_bytes() == CONTENT + + +def test_symlink_target_is_replaced_and_link_kept(tmp_path): + real = tmp_path / "real.bin" + real.write_bytes(OLD) + link = tmp_path / "link.bin" + link.symlink_to(real) + service, _ = make_service(_serve()) + _download(service, link) + assert link.is_symlink() + assert real.read_bytes() == CONTENT + + +def test_existing_file_mode_is_kept(tmp_path): + target = tmp_path / "private.bin" + target.write_bytes(OLD) + target.chmod(0o600) + service, _ = make_service(_serve()) + _download(service, target) + assert stat.S_IMODE(target.stat().st_mode) == 0o600 + assert target.read_bytes() == CONTENT + + +def test_new_file_mode_follows_umask_like_open(tmp_path): + reference = tmp_path / "reference" + reference.write_bytes(b"") + service, _ = make_service(_serve()) + target = tmp_path / "new.bin" + _download(service, target) + assert stat.S_IMODE(target.stat().st_mode) == stat.S_IMODE(reference.stat().st_mode) + + +def test_directory_save_to_fails_before_sending(tmp_path): + service, adapter = make_service(_serve()) + with pytest.raises(IsADirectoryError): + _download(service, tmp_path) + assert adapter.sent == [] + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs mkfifo") +def test_non_regular_save_to_fails_before_sending(tmp_path): + fifo = tmp_path / "pipe" + os.mkfifo(fifo) + service, adapter = make_service(_serve()) + with pytest.raises(ValueError, match="regular file"): + _download(service, fifo) + assert adapter.sent == [] + assert stat.S_ISFIFO(os.lstat(fifo).st_mode) + + +def test_redirect_is_not_followed_and_creates_no_file(tmp_path): + location = "https://elsewhere.example.com/down" + service, adapter = make_service( + _serve(body=b"", status=302, headers={"Location": location}) + ) + with pytest.raises(Exception, match="302"): + _download(service, tmp_path / "f") + assert len(adapter.sent) == 1 + assert _listing(tmp_path) == [] + + +class _ModeProbe(io.RawIOBase): + """Records the modes of partial files present while the body is read.""" + + def __init__(self, directory, body): + self.directory = directory + self.body = body + self.modes = [] + + def readable(self): + return True + + def read(self, size=-1): + for name in os.listdir(self.directory): + if name.endswith(".part"): + self.modes.append(stat.S_IMODE(os.stat(self.directory / name).st_mode)) + body, self.body = self.body, b"" + return body + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes") +def test_partial_file_is_private_while_overwriting_private_file(tmp_path): + target = tmp_path / "private.bin" + target.write_bytes(OLD) + target.chmod(0o600) + probe = _ModeProbe(tmp_path, CONTENT) + service, _ = make_service(_serve(raw=probe)) + _download(service, target) + assert probe.modes and set(probe.modes) == {0o600} + assert stat.S_IMODE(target.stat().st_mode) == 0o600 + assert target.read_bytes() == CONTENT diff --git a/libs/api/tests/test_up_e2e.py b/libs/api/tests/test_up_e2e.py new file mode 100644 index 0000000..4301c9a --- /dev/null +++ b/libs/api/tests/test_up_e2e.py @@ -0,0 +1,88 @@ +"""Real UP round trip. Opt in explicitly: + + HIAGENT_UP_E2E=1 HIAGENT_UP_UPLOAD_ENDPOINT=... HIAGENT_UP_DOWNLOAD_ENDPOINT=... \ + VOLC_ACCESSKEY=... VOLC_SECRETKEY=... uv run pytest libs/api/tests/test_up_e2e.py -q + +Best run against a UP with anonymous access disabled, so signatures are checked. +""" + +import hashlib +import io +import os +import uuid + +import pytest +from hiagent_api import up_types +from hiagent_api.up import UpService + +_REQUIRED = ( + "HIAGENT_UP_UPLOAD_ENDPOINT", + "HIAGENT_UP_DOWNLOAD_ENDPOINT", + "VOLC_ACCESSKEY", + "VOLC_SECRETKEY", +) + +pytestmark = [ + pytest.mark.e2e, + pytest.mark.skipif( + os.environ.get("HIAGENT_UP_E2E") != "1" + or not all(os.environ.get(name) for name in _REQUIRED), + reason="set HIAGENT_UP_E2E=1 plus " + ", ".join(_REQUIRED), + ), +] + + +def _service(endpoint_env: str) -> UpService: + service = UpService(endpoint=os.environ[endpoint_env], region="cn-north-1") + service.set_ak(os.environ["VOLC_ACCESSKEY"]) + service.set_sk(os.environ["VOLC_SECRETKEY"]) + # UP copies each upload inside object storage before answering; the 5 s + # default can expire first on a slow deployment. + service.set_socket_timeout(30) + return service + + +def test_upload_long_live_download_delete(tmp_path): + upload = _service("HIAGENT_UP_UPLOAD_ENDPOINT") + download = _service("HIAGENT_UP_DOWNLOAD_ENDPOINT") + content = f"hiagent-python-sdk up e2e {uuid.uuid4()}\n".encode() + digest = hashlib.sha256(content).hexdigest() + upload_id = f"sdk-e2e-{uuid.uuid4().hex}" + long_live_id = f"sdk-e2e-{uuid.uuid4().hex}" + uploaded = False + long_lived = False + + try: + raw = upload.UploadRaw( + up_types.UploadRawRequest( + Id=upload_id, ContentType="text/plain", Expire="1h", Filename="e2e.txt" + ), + io.BytesIO(content), + ) + uploaded = True + assert raw.Sha256 == digest + assert raw.Size == len(content) + assert raw.PresignKey is not None + + live = upload.LongLive( + up_types.LongLiveRequest(Path=raw.Path, Id=long_live_id, Filename="e2e.txt") + ) + long_lived = True + assert live.Path == raw.Path + + key = upload.DownloadKey(up_types.DownloadKeyRequest(Sha256=digest.upper())) + assert key.Size == len(content) + + target = tmp_path / "e2e.txt" + download.Download( + up_types.DownloadRequest(Key=key.Key, Sha256=digest, SaveTo=str(target)) + ) + assert target.read_bytes() == content + finally: + # Nested so a failure deleting one association still deletes the other. + try: + if long_lived: + upload.Delete(up_types.DeleteRequest(Id=long_live_id, Sha256=digest)) + finally: + if uploaded: + upload.Delete(up_types.DeleteRequest(Id=upload_id, Sha256=digest)) diff --git a/libs/api/tests/test_up_service.py b/libs/api/tests/test_up_service.py new file mode 100644 index 0000000..c721ba3 --- /dev/null +++ b/libs/api/tests/test_up_service.py @@ -0,0 +1,413 @@ +import io +import json +import tempfile + +import pytest +import volcengine +from hiagent_api import up_types +from hiagent_api.product_code import PRODUCT_CODE_HEADER +from up_fakes import ( + AK, + assert_signed_as_sent, + envelope, + make_service, + response, + sha256_hex, +) +from volcengine.ApiInfo import ApiInfo + +CONTENT = b"hello up service\n" * 64 +UPPER_SHA = "AB" * 32 +LOWER_SHA = "ab" * 32 +UPLOAD_RESULT = {"Path": "/upload/full/x", "Sha256": LOWER_SHA, "Size": 3} +LONG_LIVE_RESULT = {"Path": "/upload/full/x", "Size": 3} + + +def _ok(result): + return lambda sent: envelope(result) + + +class Untouchable(io.RawIOBase): + """A file object the SDK must not read, seek or inspect.""" + + def read(self, *args): + raise AssertionError("file was read") + + def seekable(self): + raise AssertionError("file was inspected") + + def tell(self): + raise AssertionError("file was inspected") + + +class NoSeekableMethod: + """Can tell() and seek() but has no seekable(), like Python 3.10's + SpooledTemporaryFile (FastAPI's UploadFile.file).""" + + def __init__(self, data: bytes): + self._buffer = io.BytesIO(data) + + def read(self, size=-1): + return self._buffer.read(size) + + def tell(self): + return self._buffer.tell() + + def seek(self, offset, whence=0): + return self._buffer.seek(offset, whence) + + +def _spooled(data: bytes): + file = tempfile.SpooledTemporaryFile() + file.write(data) + file.seek(0) + return file + + +class OneShotStream(io.RawIOBase): + """A readable, non-seekable stream.""" + + def __init__(self, data: bytes): + self._buffer = io.BytesIO(data) + + def readable(self): + return True + + def seekable(self): + return False + + def readinto(self, b): + chunk = self._buffer.read(len(b)) + b[: len(chunk)] = chunk + return len(chunk) + + +def _call_each_action(service): + service.UploadRaw(up_types.UploadRawRequest(Id="file-0001"), io.BytesIO(CONTENT)) + service.LongLive(up_types.LongLiveRequest(Path="/p", Id="file-0001")) + service.DownloadKey(up_types.DownloadKeyRequest(Path="/p")) + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + + +def _respond_by_action(sent): + action = sent.query["Action"] + if action == "UploadRaw": + return envelope(UPLOAD_RESULT) + if action == "LongLive": + return envelope(LONG_LIVE_RESULT) + if action == "DownloadKey": + return envelope({"Key": "k"}) + if action == "Delete": + return envelope({}) + return response(body=CONTENT, headers={"Content-Length": str(len(CONTENT))}) + + +# --- signing and the shared request shape ----------------------------------- + + +def test_every_action_is_a_signed_post(tmp_path): + service, adapter = make_service(_respond_by_action) + _call_each_action(service) + service.Download( + up_types.DownloadRequest(Key="k", Path="/p", SaveTo=str(tmp_path / "f")) + ) + + assert [s.query["Action"] for s in adapter.sent] == [ + "UploadRaw", + "LongLive", + "DownloadKey", + "Delete", + "Download", + ] + for sent in adapter.sent: + assert sent.method == "POST" + assert sent.query["Version"] == "2022-01-01" + assert sent.headers["User-Agent"] == "volc-sdk-python/" + volcengine.VERSION + assert "Signature" not in sent.query and "X-Signature" not in sent.query + assert "SignedHeaders=x-content-sha256;x-date," in sent.headers["Authorization"] + assert_signed_as_sent(sent) + assert [s.path for s in adapter.sent] == ["/up", "/up", "/up", "/up", "/down"] + + +def test_method_comes_from_api_info_for_both_signing_and_sending(): + service, adapter = make_service(_ok({})) + query = {"Action": "Delete", "Version": "2022-01-01"} + service.api_info["Delete"] = ApiInfo("PUT", "/up", query, {}, {}) + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + sent = adapter.sent[0] + assert sent.method == "PUT" + assert_signed_as_sent(sent) + + +def test_product_code_is_sent_but_not_signed(): + service, adapter = make_service(_respond_by_action, product_code=" maas ") + _call_each_action(service) + for sent in adapter.sent: + assert sent.headers[PRODUCT_CODE_HEADER] == "maas" + assert_signed_as_sent(sent) + + +def test_no_product_code_header_by_default(): + service, adapter = make_service(_respond_by_action) + _call_each_action(service) + assert all(PRODUCT_CODE_HEADER not in s.headers for s in adapter.sent) + + +def test_merges_default_headers_case_insensitively_without_mutating_them(): + service, adapter = make_service(_ok({})) + service.service_info.header["content-type"] = "text/html" + before = dict(service.service_info.header) + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + sent = adapter.sent[0] + content_types = [k for k in sent.headers if k.lower() == "content-type"] + assert len(content_types) == 1 + assert sent.headers["Content-Type"] == "application/json" + assert service.service_info.header == before + + +def test_reads_credentials_at_call_time(): + service, adapter = make_service(_ok({})) + service.set_ak("AKLTrotated") + service.set_sk("rotated-secret") + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + sent = adapter.sent[0] + assert "Credential=AKLTrotated/" in sent.headers["Authorization"] + assert_signed_as_sent(sent, ak="AKLTrotated", sk="rotated-secret") + + +def test_sts_token_is_sent_stripped(): + service, adapter = make_service(_ok({})) + service.set_session_token("sts-token\n") + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + sent = adapter.sent[0] + assert sent.headers["X-Security-Token"] == "sts-token" + assert_signed_as_sent(sent, token="sts-token") + + +def test_without_any_credentials_requests_go_out_unsigned(): + service, adapter = make_service(_respond_by_action, ak="", sk="") + _call_each_action(service) + for sent in adapter.sent: + assert "Authorization" not in sent.headers + assert "X-Date" not in sent.headers + assert sent.headers["X-Content-Sha256"] == sha256_hex(sent.body) + + +@pytest.mark.parametrize("ak, sk", [(AK, ""), ("", "secret"), (" ", "secret")]) +def test_half_configured_credentials_fail_before_sending(ak, sk): + service, adapter = make_service(_ok({}), ak=ak, sk=sk) + with pytest.raises(ValueError): + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + assert adapter.sent == [] + + +def test_session_token_without_keys_fails_before_sending(): + service, adapter = make_service(_ok({}), ak="", sk="") + service.set_session_token("sts-token") + with pytest.raises(ValueError): + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + assert adapter.sent == [] + + +@pytest.mark.parametrize("ak", ["AKLTleaked\n", "AKLT\nleaked"]) +def test_invalid_access_key_does_not_leak(ak): + service, adapter = make_service(_ok({}), ak=ak) + with pytest.raises(ValueError) as excinfo: + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + assert "leaked" not in str(excinfo.value) + assert adapter.sent == [] + + +def test_non_200_raises_with_body(): + service, _ = make_service(lambda sent: response(400, b'{"error":"bad"}')) + with pytest.raises(Exception, match="bad"): + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + + +def test_non_200_without_body_raises_with_status(): + service, _ = make_service(lambda sent: response(503)) + with pytest.raises(Exception, match="503"): + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + + +@pytest.mark.parametrize("status", [301, 302, 307, 308]) +def test_redirect_is_not_followed(status): + location = "https://elsewhere.example.com/up" + service, adapter = make_service( + lambda sent: response(status, b"moved", {"Location": location}) + ) + service.set_session_token("sts-token") + with pytest.raises(Exception) as excinfo: + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA)) + assert len(adapter.sent) == 1 + assert str(status) in str(excinfo.value) + assert location in str(excinfo.value) + + +@pytest.mark.parametrize("action", ["UploadRaw", "LongLive", "DownloadKey", "Delete"]) +def test_missing_result_raises(action): + service, _ = make_service(_ok(None)) + calls = { + "UploadRaw": lambda: service.UploadRaw( + up_types.UploadRawRequest(Id="file-0001"), io.BytesIO(CONTENT) + ), + "LongLive": lambda: service.LongLive( + up_types.LongLiveRequest(Path="/p", Id="file-0001") + ), + "DownloadKey": lambda: service.DownloadKey(up_types.DownloadKeyRequest(Path="/p")), + "Delete": lambda: service.Delete( + up_types.DeleteRequest(Id="file-0001", Sha256=LOWER_SHA) + ), + } + with pytest.raises(Exception, match="no Result in response"): + calls[action]() + + +# --- UploadRaw -------------------------------------------------------------- + + +def test_upload_raw_old_form_sends_header_values_and_query_params(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + req = up_types.UploadRawRequest( + Expire="15h", Id="file-0001", ContentType="text/plain", Sha256=" " + UPPER_SHA + ) + result = service.UploadRaw(req, io.BytesIO(CONTENT)) + + sent = adapter.sent[0] + assert sent.query == { + "Action": "UploadRaw", + "Version": "2022-01-01", + "Expire": "15h", + "Id": "file-0001", + } + assert sent.headers["Content-Type"] == "text/plain" + assert sent.headers["X-Content-Sha256"] == LOWER_SHA + assert sent.body == CONTENT + assert req.Sha256 == " " + UPPER_SHA + assert result == up_types.UploadRawResponse(**UPLOAD_RESULT) + + +def test_upload_raw_sends_new_query_fields_including_false(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + req = up_types.UploadRawRequest( + Id="file-0001", Filename="中文 a+b.pdf", ImageCompress=False + ) + service.UploadRaw(req, io.BytesIO(CONTENT)) + sent = adapter.sent[0] + assert sent.query["Filename"] == "中文 a+b.pdf" + assert sent.query["ImageCompress"] == "false" + assert "Expire" not in sent.query + assert "Sha256" not in sent.query and "ContentType" not in sent.query + assert sent.headers["Content-Type"] == "application/octet-stream" + assert_signed_as_sent(sent) + + +@pytest.mark.parametrize("sha", [None, "", " "]) +def test_upload_raw_computes_sha256_when_not_given(sha): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + service.UploadRaw(up_types.UploadRawRequest(Id="file-0001", Sha256=sha), io.BytesIO(CONTENT)) + sent = adapter.sent[0] + assert sent.body == CONTENT + assert sent.headers["X-Content-Sha256"] == sha256_hex(CONTENT) + + +def test_upload_raw_hashes_and_sends_from_current_position(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + file = io.BytesIO(CONTENT) + file.seek(5) + service.UploadRaw(up_types.UploadRawRequest(Id="file-0001"), file) + sent = adapter.sent[0] + assert sent.body == CONTENT[5:] + assert sent.headers["X-Content-Sha256"] == sha256_hex(CONTENT[5:]) + + +@pytest.mark.parametrize("make_file", [NoSeekableMethod, _spooled]) +def test_upload_raw_hashes_files_that_can_seek_without_seekable(make_file): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + service.UploadRaw(up_types.UploadRawRequest(Id="file-0001"), make_file(CONTENT)) + sent = adapter.sent[0] + assert sent.body == CONTENT + assert sent.headers["X-Content-Sha256"] == sha256_hex(CONTENT) + + +def test_upload_raw_streams_unseekable_input_when_sha256_given(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + req = up_types.UploadRawRequest(Id="file-0001", Sha256=sha256_hex(CONTENT)) + service.UploadRaw(req, io.BufferedReader(OneShotStream(CONTENT))) + assert adapter.sent[0].body == CONTENT + + +def test_upload_raw_rejects_unseekable_input_without_sha256(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + with pytest.raises(ValueError, match="Sha256"): + service.UploadRaw( + up_types.UploadRawRequest(Id="file-0001"), + io.BufferedReader(OneShotStream(CONTENT)), + ) + assert adapter.sent == [] + + +def test_upload_raw_rejects_empty_id_before_touching_the_file(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + with pytest.raises(ValueError, match="Id"): + service.UploadRaw(up_types.UploadRawRequest(Id=""), Untouchable()) + with pytest.raises(ValueError, match="Id"): + service.UploadRaw(up_types.UploadRawRequest.model_construct(Id=None), Untouchable()) + assert adapter.sent == [] + + +def test_upload_raw_passes_blank_id_through_to_up(): + service, adapter = make_service(_ok(UPLOAD_RESULT)) + service.UploadRaw(up_types.UploadRawRequest(Id=" "), io.BytesIO(CONTENT)) + assert adapter.sent[0].query["Id"] == " " + assert_signed_as_sent(adapter.sent[0]) + + +# --- LongLive / DownloadKey / Delete ----------------------------------------- + + +def test_long_live_sends_upper_id_in_json_body(): + service, adapter = make_service(_ok({**LONG_LIVE_RESULT, "ShortLink": "s"})) + result = service.LongLive( + up_types.LongLiveRequest(Path="/p", Id="file-0001", Filename="a.pdf") + ) + sent = adapter.sent[0] + assert sent.json() == {"Path": "/p", "ID": "file-0001", "Filename": "a.pdf"} + assert sent.headers["Content-Type"] == "application/json" + assert set(sent.query) == {"Action", "Version"} + assert result.ShortLink == "s" + + +def test_long_live_rejects_empty_id_without_sending(): + service, adapter = make_service(_ok(LONG_LIVE_RESULT)) + with pytest.raises(ValueError, match="ID"): + service.LongLive(up_types.LongLiveRequest(Path="/p", Id="")) + assert adapter.sent == [] + + +def test_download_key_sends_lowercased_query_and_empty_body(): + service, adapter = make_service(_ok({"Key": "k", "Size": 3, "ContentType": "text/plain"})) + req = up_types.DownloadKeyRequest(Sha256=UPPER_SHA) + result = service.DownloadKey(req) + sent = adapter.sent[0] + assert sent.query["Sha256"] == LOWER_SHA + assert "Path" not in sent.query + assert sent.body == b"" + assert req.Sha256 == UPPER_SHA + assert (result.Key, result.Size, result.ContentType) == ("k", 3, "text/plain") + + +def test_delete_sends_lowercased_sha256_and_returns_result(): + service, adapter = make_service(_ok({})) + req = up_types.DeleteRequest(Id="file-0001", Sha256=UPPER_SHA) + assert service.Delete(req) == {} + sent = adapter.sent[0] + assert sent.json() == {"Id": "file-0001", "Sha256": LOWER_SHA} + assert json.loads(sent.body) == sent.json() + assert req.Sha256 == UPPER_SHA + + +def test_delete_sends_blank_sha256_as_empty_string_not_null(): + service, adapter = make_service(_ok({})) + service.Delete(up_types.DeleteRequest(Id="file-0001", Sha256=" ")) + assert adapter.sent[0].json() == {"Id": "file-0001", "Sha256": ""} diff --git a/libs/api/tests/test_up_signer.py b/libs/api/tests/test_up_signer.py new file mode 100644 index 0000000..41a7d91 --- /dev/null +++ b/libs/api/tests/test_up_signer.py @@ -0,0 +1,140 @@ +import json +from datetime import datetime, timezone +from pathlib import Path + +import pytest +from hiagent_api import _up_signer + +VECTORS = json.loads( + (Path(__file__).parent / "data" / "up_signature_vectors.json").read_text("utf-8") +) +EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +NOW = datetime(2026, 11, 6, 8, 0, 0, tzinfo=timezone.utc) + + +def _x_date_to_datetime(x_date): + return datetime.strptime(x_date, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc) + + +def _sign(url="https://up.example.com/up?Action=Delete", payload_hash=EMPTY_SHA256, **overrides): + kwargs = { + "ak": "AKLTtest", + "sk": "secret", + "region": "cn-north-1", + "session_token": None, + "now": NOW, + } + kwargs.update(overrides) + return _up_signer.sign("POST", url, payload_hash, **kwargs) + + +@pytest.mark.parametrize("vector", VECTORS["vectors"], ids=lambda v: v["name"]) +def test_matches_vectors_generated_by_up_verifier(vector): + canonical = _up_signer.canonical_request( + vector["method"], vector["url"], vector["contentSha256"], vector["xDate"] + ) + assert canonical == vector["canonicalRequest"] + assert ( + _up_signer.string_to_sign(vector["xDate"], VECTORS["region"], canonical) + == vector["stringToSign"] + ) + + signed = _up_signer.sign( + vector["method"], + vector["url"], + vector["contentSha256"], + ak=VECTORS["accessKey"], + sk=VECTORS["secretKey"], + region=VECTORS["region"], + now=_x_date_to_datetime(vector["xDate"]), + ) + assert signed["X-Date"] == vector["xDate"] + assert signed["Authorization"] == ( + f"HMAC-SHA256 Credential={VECTORS['accessKey']}/{vector['xDate'][:8]}/" + f"{VECTORS['region']}/up/request, SignedHeaders={vector['signedHeaders']}, " + f"Signature={vector['signature']}" + ) + + +def test_query_decodes_plus_as_space_but_path_keeps_literal_plus(): + canonical = _up_signer.canonical_request( + "POST", "https://h/a+b?Name=x+y&Other=1%2B1", EMPTY_SHA256, "20261106T080000Z" + ) + path, query = canonical.split("\n")[1:3] + assert path == "/a+b" + assert query == "Name=x%20y&Other=1%2B1" + + +def test_query_sorted_by_name_keeping_duplicate_order(): + canonical = _up_signer.canonical_request( + "post", "https://h/?b=2&a=z&a=y&B=1", EMPTY_SHA256, "20261106T080000Z" + ) + method, _, query = canonical.split("\n")[:3] + assert method == "POST" + assert query == "B=1&a=z&a=y&b=2" + + +def test_empty_path_is_root(): + canonical = _up_signer.canonical_request( + "POST", "https://h?Action=A", EMPTY_SHA256, "20261106T080000Z" + ) + assert canonical.split("\n")[1] == "/" + + +def test_returns_only_signing_headers_and_does_not_sign_host(): + signed = _sign() + assert set(signed) == {"X-Date", "Authorization"} + assert "SignedHeaders=x-content-sha256;x-date," in signed["Authorization"] + other_host = _sign(url="https://other.example.com/up?Action=Delete") + assert other_host["Authorization"] == signed["Authorization"] + + +def test_default_now_is_current_utc(): + signed = _sign(now=None) + signed_at = _x_date_to_datetime(signed["X-Date"]) + assert abs((datetime.now(timezone.utc) - signed_at).total_seconds()) < 60 + + +def test_session_token_is_stripped_and_not_signed(): + plain = _sign() + with_token = _sign(session_token="token-value\n") + assert with_token["X-Security-Token"] == "token-value" + assert with_token["Authorization"] == plain["Authorization"] + assert "X-Security-Token" not in plain + assert "X-Security-Token" not in _sign(session_token=" \n") + + +@pytest.mark.parametrize("ak", ["", " ", None]) +def test_requires_access_key(ak): + with pytest.raises(ValueError): + _sign(ak=ak) + + +@pytest.mark.parametrize("sk", ["", " ", None]) +def test_requires_secret_key(sk): + with pytest.raises(ValueError): + _sign(sk=sk) + + +@pytest.mark.parametrize( + "field, value", + [ + ("ak", "AKLT\nleak"), + ("ak", "AKLTleak\n"), + ("ak", "AKLT\rleak"), + ("ak", "AKLT leak"), + ("ak", "AKLT\x01leak"), + ("ak", "AKLTlé"), + ("session_token", "tok\nleak-secret"), + ("session_token", "tok\x7fleak-secret"), + ("session_token", "tok中leak-secret"), + ], +) +def test_invalid_credential_error_hides_value(field, value): + with pytest.raises(ValueError) as excinfo: + _sign(**{field: value}) + message = str(excinfo.value) + assert "leak" not in message + assert value not in message + assert excinfo.value.__cause__ is None + assert excinfo.value.__context__ is None diff --git a/libs/api/tests/test_up_types.py b/libs/api/tests/test_up_types.py new file mode 100644 index 0000000..c4c33ce --- /dev/null +++ b/libs/api/tests/test_up_types.py @@ -0,0 +1,91 @@ +import pydantic +import pytest +from hiagent_api import up_types + + +def test_upload_raw_request_old_form_still_works(): + req = up_types.UploadRawRequest( + Expire="15h", Id="file-0001", ContentType="text/plain", Sha256="ab" * 32 + ) + assert (req.Expire, req.Id, req.ContentType, req.Sha256) == ( + "15h", + "file-0001", + "text/plain", + "ab" * 32, + ) + + +def test_upload_raw_request_only_requires_id(): + req = up_types.UploadRawRequest(Id="file-0001") + assert req.Expire is None + assert req.ContentType is None + assert req.Sha256 is None + assert req.Filename is None + assert req.ImageCompress is None + with pytest.raises(pydantic.ValidationError): + up_types.UploadRawRequest() + + +def test_validation_error_is_a_value_error(): + assert issubclass(pydantic.ValidationError, ValueError) + + +def test_long_live_request_serializes_id_as_upper_id(): + req = up_types.LongLiveRequest(Path="/p", Id="file-0001", Filename="a.pdf") + assert req.Id == "file-0001" + assert req.model_dump(by_alias=True, exclude_none=True) == { + "Path": "/p", + "ID": "file-0001", + "Filename": "a.pdf", + } + with pytest.raises(pydantic.ValidationError): + up_types.LongLiveRequest(Path="/p") + + +def test_download_key_request_accepts_path_or_sha256(): + assert up_types.DownloadKeyRequest(Path="/p").Sha256 is None + assert up_types.DownloadKeyRequest(Sha256="ab" * 32).Path is None + + +def test_download_request_never_dumps_save_to(): + req = up_types.DownloadRequest( + Key="k", Sha256="ab" * 32, ID="file-0001", SaveTo="/tmp/x", ImageCompress=False + ) + dumped = req.model_dump(by_alias=True, exclude_none=True) + assert "SaveTo" not in dumped + assert dumped == { + "Key": "k", + "Sha256": "ab" * 32, + "ID": "file-0001", + "ImageCompress": False, + } + assert req.SaveTo == "/tmp/x" + assert up_types.DownloadRequest(Key="k", Path="/p", SaveTo="x").Path == "/p" + + +def test_responses_parse_new_fields_and_default_to_none(): + upload = up_types.UploadRawResponse.model_validate( + { + "Path": "/p", + "Sha256": "ab" * 32, + "Size": 3_000_000_000, + "ShortLink": "s", + "PresignKey": "pk", + } + ) + assert (upload.Size, upload.ShortLink, upload.PresignKey) == (3_000_000_000, "s", "pk") + assert up_types.UploadRawResponse.model_validate( + {"Path": "/p", "Sha256": "ab" * 32, "Size": 1} + ).ShortLink is None + + long_live = up_types.LongLiveResponse.model_validate( + {"Path": "/p", "Size": 1, "Sha256": "ab" * 32, "ShortLink": "s"} + ) + assert (long_live.Sha256, long_live.ShortLink) == ("ab" * 32, "s") + assert up_types.LongLiveResponse.model_validate({"Path": "/p", "Size": 1}).Sha256 is None + + key = up_types.DownloadKeyResponse.model_validate( + {"Key": "k", "Size": 1, "ContentType": "text/plain"} + ) + assert (key.Size, key.ContentType) == (1, "text/plain") + assert up_types.DownloadKeyResponse.model_validate({"Key": "k"}).Size is None diff --git a/libs/api/tests/up_fakes.py b/libs/api/tests/up_fakes.py new file mode 100644 index 0000000..5770585 --- /dev/null +++ b/libs/api/tests/up_fakes.py @@ -0,0 +1,123 @@ +"""Offline fakes for UpService tests: a requests adapter that records what was +actually sent and replays canned responses.""" + +import hashlib +import io +import json +from datetime import datetime, timezone +from typing import Callable, List, Optional +from urllib.parse import parse_qsl, urlsplit + +import requests +from hiagent_api import _up_signer +from hiagent_api.up import UpService +from requests.adapters import BaseAdapter + +ENDPOINT = "https://up.example.com" +AK = "AKLTtestaccesskey" +SK = "test-secret-key" + + +class Sent: + def __init__(self, prepared: requests.PreparedRequest, body: bytes): + self.method = prepared.method + self.url = prepared.url + self.headers = prepared.headers + self.body = body + parts = urlsplit(prepared.url) + self.path = parts.path + self.query = dict(parse_qsl(parts.query, keep_blank_values=True)) + + def json(self): + return json.loads(self.body) + + +class FakeAdapter(BaseAdapter): + def __init__(self, respond: Callable[[Sent], requests.Response]): + super().__init__() + self.respond = respond + self.sent: List[Sent] = [] + + def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): + body = request.body + if hasattr(body, "read"): + body = body.read() + elif body is None: + body = b"" + elif isinstance(body, str): + body = body.encode("utf-8") + sent = Sent(request, bytes(body)) + self.sent.append(sent) + response = self.respond(sent) + response.request = request + response.url = request.url + return response + + def close(self): + pass + + +class BrokenStream(io.RawIOBase): + """A response body that fails after the first chunk.""" + + def __init__(self, first: bytes): + self.first = first + self.done = False + + def readable(self): + return True + + def read(self, size=-1): + if not self.done: + self.done = True + return self.first + raise ConnectionResetError("connection reset by peer") + + +def response(status=200, body=b"", headers=None, raw=None) -> requests.Response: + resp = requests.Response() + resp.status_code = status + resp.headers.update(headers or {}) + resp.raw = raw if raw is not None else io.BytesIO(body) + resp.encoding = "utf-8" + return resp + + +def envelope(result) -> requests.Response: + payload = {"ResponseMetadata": {"RequestId": "req-1"}} + if result is not None: + payload["Result"] = result + return response(body=json.dumps(payload).encode("utf-8")) + + +def make_service(respond, *, ak=AK, sk=SK, product_code=None): + service = UpService(endpoint=ENDPOINT, region="cn-north-1") + service.set_ak(ak) + service.set_sk(sk) + service.set_session_token("") + if product_code is not None: + service.set_product_code(product_code) + adapter = FakeAdapter(respond) + service.session.mount("https://", adapter) + return service, adapter + + +def sha256_hex(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def assert_signed_as_sent(sent: Sent, ak: str = AK, sk: str = SK, token: Optional[str] = None): + """Recompute the signature from what was received, the way UP does.""" + assert sent.headers["X-Content-Sha256"] == sha256_hex(sent.body) + x_date = sent.headers["X-Date"] + expected = _up_signer.sign( + sent.method, + sent.url, + sent.headers["X-Content-Sha256"], + ak=ak, + sk=sk, + region="cn-north-1", + session_token=token, + now=datetime.strptime(x_date, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc), + ) + assert sent.headers["Authorization"] == expected["Authorization"] diff --git a/openspec/changes/align-up-service/.openspec.yaml b/openspec/changes/align-up-service/.openspec.yaml new file mode 100644 index 0000000..462e04d --- /dev/null +++ b/openspec/changes/align-up-service/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-25 diff --git a/openspec/changes/align-up-service/design.md b/openspec/changes/align-up-service/design.md new file mode 100644 index 0000000..03a644c --- /dev/null +++ b/openspec/changes/align-up-service/design.md @@ -0,0 +1,263 @@ +## 背景 + +### UP 怎么验签 + +UP 不比对客户端交来的签名材料,而是用**自己收到的请求**重算签名,再与 `Authorization` 里的签名比较(iam-server `sdk/helper.go:CheckSignature`): + +```text +Method 收到的请求方法 +Path 收到的 URL.Path(Go 按 PathUnescape 解码,"+" 保持字面) +Query 收到的全部 query(含 Action、Version),按 url.ParseQuery 解码("+" 解为空格), + 按参数名排序,名和值只保留 A-Z a-z 0-9 - _ . ~,其余按 UTF-8 字节写成大写 %XX, + 空格写成 %20 +Headers 按 Authorization 中 SignedHeaders 的顺序取 "name:去首尾空白的值" +BodyHash X-Content-Sha256 头;没有这个头时,服务端读完整个请求体自己算 +X-Date 必须在请求头里;缺 X-Date 或 Authorization 直接失败 +``` + +签名串为 `HMAC-SHA256\n\n///request\n`,密钥由 SK 依次对日期、region、service、`request` 做 HMAC-SHA256 派生。 + +`authz.go` 判断"请求是否声明了身份"(`claimsAnIdentity`)也只看请求头里的 `X-Date` 和 `Authorization`,所以 query 签名(`SignerV4.sign_url`)在 UP 看来就是未签名请求。 + +验签之前还有几条放行路径:匿名开启时的短路、`authz.unsignedActions`,以及 `action == "Download" && c.QueryParam("Key") != ""`。最后这一条**只看 query**,`Key` 放在 JSON 请求体里时不生效。 + +### UP 怎么绑定这五个 Action 的参数 + +UP 按 `?Action=` 反射到同名 handler,不按路径路由(`dispatcher.go:RefAction`)。绑定顺序: + +1. 请求体:Action 不在 `skipParseBody` 里时按 JSON 解析;请求体为空时不绑定。`UploadRaw`、`DownloadKey` 在 `skipParseBody` 里,请求体不参与绑定。 +2. query:按 `query` tag 取值,echo 先精确匹配,再不区分大小写匹配。 +3. header:按 `header` tag 取值,请求里没有该 header 时不覆盖前面的值。 +4. 按 `validate` tag 校验,失败返回 400。 + +| Action | 请求字段(来源) | 响应 | +| --- | --- | --- | +| UploadRaw | `X-Content-Sha256`、`Content-Type`(header);`Expire`、`Id`(必填)、`Filename`、`ImageCompress`(query);请求体是文件 | `Path`、`Size`、`Sha256`、`ShortLink`、`PresignKey` | +| LongLive | `Path`、`ID`、`Filename`(JSON) | `Path`、`Size`、`Sha256`、`ShortLink` | +| DownloadKey | `Path`、`Sha256`(query,二选一) | `Key`、`Size`、`ContentType` | +| Download | `Path`、`Sha256`(二选一)、`Key`(必填)、`ID`、`Filename`、`ImageCompress`(JSON 与 query 都有 tag);`Range`(header) | 文件流;失败时为 JSON 错误信封 | +| Delete | `Sha256`(必填,64 位)、`Id`(必填,8 至 256 位)(JSON) | `Result: {}` | + +响应信封是 `{"ResponseMetadata": ..., "Result": ...}`,`Result` 为 `omitempty`,五个 handler 成功时都返回非 nil 响应,所以 `Result` 总是存在(`Delete` 为 `{}`)。 + +`UploadRaw` 用小写十六进制计算文件哈希并与请求值做字符串比较;`DownloadKey`、`Download`、`Delete` 按哈希查库,库里存的也是小写。 + +### 现在的 Python 实现错在哪 + +五个 `ApiInfo` 的方法本来都是 `POST`,问题出在发送路径上: + +| 方法 | 现在的做法 | 问题 | +| --- | --- | --- | +| UploadRaw | `SignerV4.sign_url`,签名在 query;`model_dump()` 全部进 query | UP 视为未签名;`Sha256`、`ContentType` 多余地进了 query | +| LongLive | `Service.json()`,POST + 头签名 | 签了 `host`;请求键是 `Id` | +| DownloadKey | `Service.get()`:按 `ApiInfo` 的 `POST` 签名,发出 `GET` | 方法错配,验签必然失败 | +| Download | 同上,`GET` + query,`SaveTo` 进 query | 方法错配(query 带 `Key` 时被 UP 提前放行);本地路径外泄;边收边写 | +| Delete | `Service.json()`,POST + 头签名 | 签了 `host`;sha256 未规范化 | + +## 方案 + +### 原则:签名只针对最终发出的请求 + +问题的根源是"签名材料"和"发出的请求"是两份东西。新增包内模块 `hiagent_api/_up_signer.py`,从 Java `UpSigner` 移植,只有一个入口: + +```python +def sign(method: str, url: str, payload_hash: str, *, ak: str, sk: str, + region: str, session_token: str | None = None, + now: datetime | None = None) -> dict[str, str] +``` + +- 输入就是要交给 `requests` 的 `method`、完整 `url`,以及要放进 `X-Content-Sha256` 的值;只返回要加到请求上的 `X-Date`、`Authorization`(使用 STS 时再加 `X-Security-Token`,不参与签名),由调用方 `update` 进自己的 Header。 +- path:`urllib.parse.unquote(urlsplit(url).path)`,与 Go 的 `URL.Path` 一致,`+` 保持字面;空路径按 `/`。 +- query:取 `urlsplit(url).query` 原文,按 `&` 拆对,名和值都用 `urllib.parse.unquote_plus` 解码(与 Go `url.ParseQuery`、Java `URLDecoder` 一致,`+` 解为空格),按参数名排序(同名保持原顺序),再用 `urllib.parse.quote(s, safe="-_.~")` 编码,与 Java `signEncode` 等价。 +- payload hash:由调用方传入,`_send` 把同一个变量同时写进 `X-Content-Sha256` 和传给签名器,两者不会不一致;签名器不自己计算请求体哈希。 +- 时间:`now` 只供测试注入固定时间,生产调用不传,取 `datetime.now(timezone.utc)`;传入时先 `astimezone(timezone.utc)`。`X-Date` 格式为 `%Y%m%dT%H%M%SZ`。 +- SignedHeaders 固定为 `x-content-sha256;x-date`。不签 `host`,经网关改写 Host 时不会失配;不签 `X-Trace-Product-Code`,productCode 有无不影响签名。 +- credential scope 的 service 固定为 `up`,与现在 `UpService` 的 `Credentials("", "", "up", region)` 一致。 + +### 凭证校验 + +`requests` 设置含 `\r`、`\n` 或首部空白的 Header 时抛出的 `InvalidHeader` 会把整个 Header 值写进异常信息。会进入 Header 的凭证只有 AK(写进 `Authorization`)和 STS token(`X-Security-Token`);其中真正的秘密是 STS token,常见出错方式是从文件读入时带了尾随换行。所以只做两件事: + +- `session_token` 先去首尾空白,去完为空则视为没有 STS。 +- `ak`、`session_token` 只能包含可打印 ASCII(`0x21`–`0x7e`),否则抛 `ValueError`。用 `re.fullmatch` 判断:`re.match` 加 `$` 时 `$` 会匹配末尾 `\n` 之前的位置,不 strip 的 AK 带尾随换行就会漏过检查。异常信息只说明是哪一项不合法,不包含值。检查不在 `except` 块里进行,抛出的 `ValueError` 的 `__cause__`、`__context__` 都为空,不会通过异常链带出原始异常。 + +不另做的校验:SK 不进入任何 Header,只参与 HMAC;region 来自构造参数,不是凭据,写错只会导致服务端验签失败。AK、SK 是否为空由下一节的规则处理。 + +### 未配置凭证 + +旧版在没有凭证时,volcengine 会用空 AK 照样签名并发出请求。可选的做法有三种,只有"不签名"在所有放行路径上都成立: + +| 做法 | 匿名开启 | `unsignedActions` 放行 | 关闭匿名 | +| --- | --- | --- | --- | +| 用空凭证照样签名(旧版) | 放行,但后台验签观测会记一次失败 | **被拒**:`unsigned.allows(action) && !claimsAnIdentity(...)` 只放行完全不带签名材料的请求 | 被拒 | +| 本地直接报错(Java) | 本可成功的调用失败 | 本可成功的调用失败 | 报错更早 | +| 不签名 | 放行 | 放行 | 被拒,与旧版相同 | + +所以: + +- AK、SK、STS token 都为空(`None` 或空白串):不调用签名器,请求不带 `X-Date`、`Authorization`,其余部分(含 `X-Content-Sha256`)照常发送。UP 的 `claimsAnIdentity` 会把它当作完全未签名的请求,交给部署配置决定是否放行。 +- 配置了其中一部分但 AK、SK 不全(包括只配了 STS token):在发请求前抛 `ValueError`,避免半套配置被静默降级成匿名请求。 +- 两个都配置了:按上文签名,并做凭证校验。 + +### `UpService` 的请求构造 + +五个方法共用一个私有方法 `_send(action, query, body, content_type, content_sha256, stream=False)`: + +```text +URL ://?Action=&Version=2022-01-01&<参数...> + 参数名和值用签名同一套编码写进 URL,发出的字节就是被签名的字节; + 值为 None 的参数不发送;bool 写成 true/false +Method 一律 POST +Headers CaseInsensitiveDict(service_info.header)(Accept、已配置的 X-Trace-Product-Code), + 在这份副本上设置 Content-Type、X-Content-Sha256、User-Agent, + 不会出现同名不同大小写的重复 Header,也不修改 service_info.header + User-Agent 为 "volc-sdk-python/" + volcengine.VERSION(与 volcengine 原逻辑相同,VERSION 自带 v 前缀) +签名 每次调用时读取 service_info.credentials 的 ak、sk、session_token、region, + 所以初始化之后再调用 set_ak/set_sk/set_session_token 也会生效 +Method 签名和发送都取 ApiInfo.method(五个 Action 均为 POST),只有这一个来源 +发送 self.session.request(method, url, headers=..., data=body, + timeout=(connection_timeout, socket_timeout), stream=stream, + allow_redirects=False) +响应 带 Location 的 3xx:raise Exception,信息含状态码和 Location + 其他非 200:raise Exception(resp.text),与现在一致;响应体为空时改为带状态码 + 200:解析 JSON;没有 Result 时 raise Exception("no Result in response: ...") +``` + +- `UpService` 继续继承 volcengine `Service`,`set_ak`、`set_sk`、`set_session_token`、`session`、`set_product_code` 全部照旧可用。`get_api_info()` 的五个 `ApiInfo` 原本就是 `POST`,保持不变,`_send` 从中读取 path 与 `Action`/`Version`。 +- 路径保持现在的 `/up`(`Download` 为 `/down`),endpoint 解析逻辑不变。 +- 不再使用 `Service.get/json/prepare_request` 与 `SignerV4`,避免再次出现"签一份、发一份"。 +- 不跟随重定向。签名只覆盖 path 和 query,跟随后要么带着旧签名请求新 URL(301/302 还会把 POST 改成 GET 并丢掉请求体),要么跨主机时 `requests` 只去掉 `Authorization`、照样带上 `X-Security-Token`。UP 的五个接口本身不返回 3xx,收到 3xx 说明 endpoint 配错或中间有网关,直接报错并给出 `Location` 更容易排查。代价:网关对同一主机做 http→https 的 307/308 时,原先能成功,现在要把 endpoint 改成 https。 + +### 各方法的请求形状 + +| 方法 | query(Action、Version 之外) | 请求体与 Content-Type | 本地检查(按顺序,都在发请求前) | +| --- | --- | --- | --- | +| UploadRaw | `Expire`、`Id`、`Filename`、`ImageCompress` | 文件对象;`ContentType` 或 `application/octet-stream` | `Id` 非空 → 凭证 → 需要自动计算时检查可 seek | +| LongLive | 无 | `{"Path","ID","Filename"}`;`application/json` | `ID` 非空 → 凭证 | +| DownloadKey | `Path`、`Sha256` | `b""`;`application/json` | 凭证 | +| Download | `Key`、`Path`、`Sha256`、`ID`、`Filename`、`ImageCompress` | `b""`;`application/json` | `SaveTo` 非空白 → 凭证 | +| Delete | 无 | `{"Sha256","Id"}`;`application/json` | 凭证 | + +- 只有 `LongLive`、`Delete` 两个 Action 带 JSON 请求体,用 `model_dump(by_alias=True, exclude_none=True)` 生成、规范化 sha256 后,`json.dumps(...).encode("utf-8")`;`X-Content-Sha256` 对这份最终字节计算。 +- `Download` 的参数全部走 query,原因有两个:UP 只在 query 带 `Key` 时于验签前放行,参数放进请求体会让带 `Key` 的下载改走完整验签;这也和旧版 Python 的线上形状一致。请求体为空,UP 不做 JSON 绑定。这一点与 Java(参数放在 JSON 请求体)不同,是有意的取舍。 +- `DownloadKey` 的二选一、`Delete` 的长度约束交给 UP 判断,SDK 不另立规则(与 Java 一致)。 + +### `Id` 的检查口径 + +- `UploadRawRequest.Id`、`LongLiveRequest.Id` 保持 `str` 必填。缺参或传 `None` 时 pydantic 在构造阶段就抛 `ValidationError`,它是 `ValueError` 的子类。 +- 方法入口再检查一次空串(以及 `model_construct` 绕过校验得到的 `None`),抛 `ValueError`。口径与 UP 的 `validate:"required"` 一致:只拒绝 `None` 和空串,不拒绝空白串。 +- `UploadRaw` 的 `Id` 检查排在所有读文件、`seekable()` 判断之前。 + +### 请求体哈希 + +- `UploadRaw`: + - `Sha256` 去首尾空白后非空:转小写后放进 `X-Content-Sha256`,UP 会用它校验文件内容。文件对象不需要可 seek,直接流式上传。 + - `Sha256` 为 `None` 或去空白后为空:视为未提供(与 Java `UpClient` 一致,兼容旧代码传 `""`)。记录 `file.tell()`,按 64 KiB 分块读到末尾算 SHA-256,再 `seek` 回原位置后上传。所以从非零偏移开始的文件对象只会哈希并上传剩余字节。IO 两遍,内存占用固定。不能"边读边算",因为哈希要先写进请求头并参与签名。 + - 未提供 `Sha256` 时,直接试一次 `tell()` 和 `seek(当前位置)`,抛 `AttributeError`、`OSError` 或 `ValueError` 就视为不可 seek,抛 `ValueError` 提示调用方提供 `Sha256`。不调用 `seekable()`:Python 3.10 的 `SpooledTemporaryFile`(FastAPI `UploadFile.file` 的类型)没有这个方法,但能正常 `tell`/`seek`。 +- `DownloadKey`、`Download`:请求体为空,`X-Content-Sha256` 为空串的 SHA-256。 +- JSON 请求:对最终发送的字节计算。 +- 每个请求都发送 `X-Content-Sha256`。不发时 UP 会在鉴权中间件里读完整个请求体来算哈希,大文件会占满服务端内存。 + +### sha256 规范化 + +规则:去首尾空白,转小写。可选的 `Sha256`(`UploadRaw`、`DownloadKey`、`Download`)去空白后为空时视为未提供;`Delete` 的 `Sha256` 是必填,空白时照发 `""`,由 UP 的必填校验报错,而不是发出 `null`。覆盖 SDK 发出的所有 sha256:`UploadRaw` 的 `X-Content-Sha256`、`DownloadKey` 和 `Download` 的 `Sha256` query、`Delete` 请求体里的 `Sha256`。在 dump 出的 dict 上改写,调用方的模型对象不变。 + +只规范化上传会造成不一致:大写哈希的上传从失败变成成功,同一个哈希的 `Delete` 却在大小写敏感的库上什么也没删、也不报错。所以全部规范化。 + +### 模型变更 + +全部基于 pydantic v2,新字段默认 `None`。 + +| 模型 | 变更 | +| --- | --- | +| `UploadRawRequest` | `Expire`、`ContentType`、`Sha256` 改为 `Optional[str] = None`;`Id` 保持 `str` 必填;新增 `Filename: Optional[str]`、`ImageCompress: Optional[bool]`。`ContentType` 为 `None` 或空串时发送 `application/octet-stream`,与现在一致 | +| `UploadRawResponse` | 新增 `ShortLink`、`PresignKey`(可选) | +| `LongLiveRequest` | Python 属性名仍为 `Id`(`str` 必填),只加 `serialization_alias="ID"`,构造方式不变;新增 `Filename`。不额外接受 `ID=` 构造:没有调用方需要,属于过度设计 | +| `LongLiveResponse` | 新增 `Sha256`、`ShortLink`(可选) | +| `DownloadKeyRequest` | `Path` 改为可选;新增 `Sha256` | +| `DownloadKeyResponse` | 新增 `Size`、`ContentType`(可选) | +| `DownloadRequest` | `Path` 改为可选;新增 `Sha256`、`ID`、`Filename`、`ImageCompress`;`SaveTo` 保持 `str` 必填,用 `Field(exclude=True)` 排除,不进入 query | +| `DeleteRequest` | 不变 | + +Python 的 `int` 没有溢出问题,`Size` 不需要 Java 那样的 `Long` 兼容处理。 + +返回值保持现状:`Delete` 返回 `Result` 的内容(UP 返回 `{}`);`Download` 返回 `None`。唯一变化是 `Delete` 收到不含 `Result` 的 200 响应时,和其他方法一样抛异常,不再返回整个响应 JSON。UP 的 `Delete` 成功时总带 `"Result": {}`,这只影响 mock 或非 UP 实现,作为发版说明中的行为变化。 + +### `Download` 落盘 + +1. 发请求前:`SaveTo` 为空白串时抛 `ValueError`。如果不拦,`os.path.realpath("")` 会返回当前目录,整个文件下载完后才在替换时报 `IsADirectoryError`。`SaveTo` 以路径分隔符结尾时抛 `IsADirectoryError`(`realpath` 会去掉末尾分隔符,把 `newdir/` 变成名为 `newdir` 的文件);解析后的父目录不存在时抛 `FileNotFoundError`,不自动创建,与旧版 `open(SaveTo, "wb")` 一致,自动建目录不属于"对齐 UP"的范围,路径写错时还会悄悄建出一串目录。然后 `stat(realpath(SaveTo))`:不存在则继续;是目录抛 `IsADirectoryError`;不是普通文件(设备、FIFO、socket)抛 `ValueError`。原子替换会把设备节点本身换成普通文件,例如容器里以 root 传 `/dev/null`;不为这类目标回退到直接写入,那样会多一条写入路径,FIFO 还会阻塞下载连接。 +2. 用 `with self._send(..., stream=True) as resp:` 包住整个处理过程,非 200 或中途异常时都会释放连接。 +3. 响应非 200:读取响应体作为错误信息抛出,不创建任何文件。 +4. 用 `os.path.realpath(SaveTo)` 得到最终目标,这样 `SaveTo` 是符号链接时,替换的是它指向的文件,与原先 `open(SaveTo, "wb")` 的效果一致。 +5. 在目标同一目录下用 `open(tmp, "xb", opener=...)` 创建定长随机名的临时文件 `.up-.part`。不把目标文件名拼进去:那样会多出 39 字节,接近上限的合法文件名会因 `ENAMETOOLONG` 失败。目标不存在时以 0o666 创建,权限按进程 umask 生成,与普通 `open()` 相同(不用 `mkstemp`,它固定创建 0600);目标已存在时以 0o600 创建,直到第 8 步复制原权限之前都不对其他用户可读,否则覆盖 0600 私有文件时,下载期间以及进程被杀后残留的临时文件都会是 0644。创建放在 `try` 之外:极端情况下随机名撞上已有文件时,不会误删别人的文件。 +6. 用 `resp.iter_content` 按块写入临时文件并累计字节数。 +7. 长度核对:响应带 `Content-Length` 且没有 `Content-Encoding` 时,写入字节数必须等于 `Content-Length`,否则抛异常。不能只依赖 urllib3:本仓库 lock 的是 2.6.3,它默认校验长度;但 requests 允许用户装 urllib3 1.26,1.26 默认不校验,短读会被当成正常结束,残缺文件随后被原子替换上去,"失败不破坏旧文件"就失效了。UP 未加密时总会声明 `Content-Length`(压缩时为压缩后的大小),加密输出不声明,此时跳过核对。 +8. 目标已存在时用 `shutil.copymode` 把原有权限位带到临时文件,然后 `os.replace(tmp, target)` 原子替换。保留权限位不是可有可无:否则一个 0600 的私有文件被替换后会按 umask 变成 0644。不做 `fsync`:它解决的是断电后的持久性,不是这次要解决的"传输失败不破坏旧文件",测不出效果,还会拖慢大文件下载。 +9. 任一步出错(网络中断、长度不符、写盘失败):删除临时文件,原有目标文件保持原样,异常向上抛出。 + +### 与其他签名代码的关系 + +仓库里会有三份 V4 签名实现:volcengine `SignerV4`(其他 TOP 服务继续使用)、`hibot/_signer.py`、`hiagent_api/_up_signer.py`。`hibot` 是独立包,按 AGENTS.md 不能跨包导入它的私有模块,而且它签 `host`、要求传入完整请求体字节,不适合 UP。容易出错的 query 编码由下文的服务端样例固定。 + +### 被否决的方案 + +- **沿用 `SignerV4.sign`,只修方法与 query**:它签 `host`,并且会把 `X-Content-Sha256` 覆盖为 `sha256(request.body)`,上传只能把整个文件读进内存;它的 query 编码也没有经过服务端样例验证。 +- **迁移到 `hiagent_api.base` 的 httpx `Service`**:改动面大,并且会改变 `UpService` 的基类和 `session` 类型,不属于这次对齐的范围。 +- **`Download` 参数放进 JSON 请求体(Java 现状)**:会让带 `Key` 的下载从"验签前放行"变成"完整验签",改变鉴权路径。 +- **`Download` 整体读进内存再写(Java 现状)**:大文件会占满内存;临时文件加原子替换在 Python 里代价很小。 +- **未配置凭证时直接报错(Java 现状)、或用空凭证照样签名(Python 旧版)**:见上文"未配置凭证"中的对比表,两者在 `unsignedActions` 部署上都会失败。 +- **下载后用 `ETag` 校验内容哈希**:UP 把 `ETag` 设为文件哈希,看上去能顺带发现 UP"200 但内容为空或不完整"的已知问题(`docs/oncall/runbooks/download-size-mismatch.md`)。但部署可能开启国密(`useSM`,哈希为 SM3),`ImageCompress` 时返回的是压缩文件的哈希,客户端固定按 sha256 比对会把正常下载判为失败。不做。 +- **用本地 `http.server` 验证截断**:验证的是 urllib3 的行为,不是 SDK 的;而且在 urllib3 1.26 上,这条保证本来就不成立。改为由 SDK 自己核对长度,用 fake adapter 构造虚报 `Content-Length` 的响应来测。 + +## 兼容性 + +- 公开类、方法名、方法签名不变;模型只有新增字段和"必填放宽为可选",旧的构造方式(包括 `LongLiveRequest(Id=...)`)照常可用。 +- 未配置 productCode 时不发送 `X-Trace-Product-Code`。 +- 未配置凭证时仍然发出请求(不签名),与旧版效果一致。 +- 新增的本地检查抛 `ValueError`,它是 `Exception` 的子类,调用方原有的 `except Exception` 仍能捕获。 +- `Download` 的 query 参数与旧版一致,只少了 `SaveTo`,UP 的放行路径不变。 +- `agent-harness` 的 `hiagent_backend.upload_raw_file`、`download_file` 调用方式不变。 +- 依赖不变(`volcengine`、`requests`、`pydantic>=2.11.5`)。 + +## 测试方案 + +默认测试全部离线运行,放在 `libs/api/tests/`: + +1. **服务端签名样例(主验收)**:复制 Java SDK 的 `up-signature-vectors.json` 到 `libs/api/tests/data/up_signature_vectors.json`。这份样例由 UP 服务端验签用的签名库离线生成,覆盖文本与非法 UTF-8 二进制请求体、根路径与 `/up/` 路径、含 `/`、空格、`+`、`=`、`&`、`!'()*`、中文的 query 值、大小写混合的参数名排序。逐条断言 canonical request、待签串、签名完全一致。另补一条:原始 URL 的 query 和 path 中都有字面 `+` 时的解码结果。 +2. **签名器边界**:只返回 `X-Date`、`Authorization`(及 STS 时的 `X-Security-Token`);SignedHeaders 固定,不同 host 签名相同。 +3. **凭证**:`ak`、`session_token` 含 `\n`、`\r`、控制字符、空格或非 ASCII 字符时抛 `ValueError`,异常信息里**不包含**凭证值,`__cause__` 和 `__context__` 都为空;`session_token` 带尾随换行时去掉后正常签名;只配 AK 或只配 SK 时抛 `ValueError` 且没有发请求;AK、SK 都未配置时发出的请求不带 `X-Date`、`Authorization`。 +4. **签的就是发出去的请求**:给 `UpService.session` 挂一个 requests 的 fake adapter,截下五个方法实际发出的 `PreparedRequest`,按**收到的** method、URL、`X-Content-Sha256` 用已被样例验证的签名器重算签名,必须等于收到的 `Authorization`;并校验 `X-Content-Sha256` 等于实际请求体的 SHA-256。初始化后调用 `set_ak`/`set_sk` 会用新凭证签名。 +5. **请求形状**:方法均为 `POST`;`UploadRaw` 的 query 不含 `Sha256`、`ContentType`,`ImageCompress=False` 写成 `false` 照发,`None` 字段不发;`LongLive` 的键是 `ID`;`Download` 的 `Key` 等参数在 query、请求体为空、任何地方都没有 `SaveTo`;大写 sha256 发出时为小写且调用方模型不变;productCode 已配置时发送、未配置时不发送、不在 SignedHeaders 中;`service_info.header` 里已有小写 `content-type` 等键时不产生重复 Header,且 `service_info.header` 本身不被修改;User-Agent 为 `volc-sdk-python/` + `volcengine.VERSION`;STS token 生效;签名不含 `host`。 +6. **兼容与边界**: + - 旧写法(四个字段全传)的 `UploadRaw` 照常工作; + - `Sha256` 为 `None`、`""`、`" "` 时都自动计算,上传内容完整; + - 文件对象已 seek 到非零偏移时,只哈希并上传剩余字节; + - 提供了 `Sha256` 时,不可 seek 的流照常流式上传; + - 未提供 `Sha256` 且流不可 seek 时抛 `ValueError`,没有发请求;没有 `seekable()` 但能 `tell`/`seek` 的文件对象(含 `SpooledTemporaryFile`)照常自动计算;`Delete` 的 `Sha256` 为空白时发出 `""` 而不是 `null`; + - `UploadRaw` 的 `Id` 为空串时抛 `ValueError`,且发生在读文件和 `seekable()` 判断之前(用一个读取即报错的文件对象验证);`Id` 为空白串时照常发送; + - `LongLive` 的 `ID` 为空串时不发请求;`LongLiveRequest(Id=...)` 序列化后的键是 `ID`; + - 响应缺 `Result` 时五个方法都抛含 `no Result in response` 的异常;新响应字段能解析,缺失时为 `None`。 +7. **下载落盘**: + - 内容正确;父目录不存在、`SaveTo` 以分隔符结尾时,都在发请求前报错且不创建任何东西;230 个字符的目标文件名可以正常下载; + - `SaveTo` 为空白串时抛 `ValueError`,没有发请求; + - 非 200 时不创建文件,连接被释放; + - 中途中断,用 fake adapter 构造两种情况:响应体比声明的 `Content-Length` 短(SDK 自己的长度核对会报错,不依赖 urllib3 版本),以及响应流读到一半抛异常。两种情况下旧文件内容都不变,目录里也不残留临时文件; + - 带 `Content-Encoding` 或没有 `Content-Length` 的响应跳过长度核对; + - `SaveTo` 为符号链接时写入链接目标;已有文件的权限位保留;覆盖 0600 文件时,读取响应期间临时文件即为 0600; + - `SaveTo` 为目录或 FIFO 时不发请求; + - 3xx 不跟随(只发出一个请求),错误信息含状态码和 `Location`;空响应体的非 200 错误信息含状态码;只配 STS token 时报错;AK 带尾随换行时报错且不泄漏。 + - 变异验证:把实现改成直接写目标文件,中断用例必须失败。 +8. **真实环境 e2e**:`libs/api/tests/test_up_e2e.py`,标记 `e2e`,只有设置 `HIAGENT_UP_UPLOAD_ENDPOINT`、`HIAGENT_UP_DOWNLOAD_ENDPOINT` 和 AK/SK 时才运行;跑一遍上传、长期化、获取下载 Key、下载、删除,上传之后的断言都放在 `try` 里,`finally` 里删除已上传的文件。最好在关闭匿名访问的 UP 上执行一次。 + +`agent-harness` 不在 uv workspace 里,它的 `test_up_endpoints.py` 补一条用例:通过 fake adapter 验证 `upload_raw_file`、`download_file` 在新实现下仍然正常。运行时需要加 `PYTHONPATH=agent-harness`。 + +## 风险与边界 + +- 只在直连 UP、或中间代理不改写路径时成立。 +- UP 会把 `application/x-www-form-urlencoded` 请求体当作表单参数并入 query,`UploadRaw` 不支持以该类型上传。 +- 国密环境不支持。 +- `DownloadKey`、`Download` 由 `GET` 改为 `POST`:UP 对这两个 Action 不限制方法。`DownloadKey` 的请求体不参与绑定;`Download` 请求体为空,参数全部从 query 绑定,与旧版相同。 +- 临时文件与目标在同一目录,要求该目录可写;原先只要求目标文件可写。目标所在目录只读、但文件本身可写的情况会由成功变为失败,已列入 proposal 的发版说明。 +- 未配置凭证时请求不签名,能否成功取决于部署的匿名和 `unsignedActions` 配置;旧版在这些部署上本来就能发出同样的请求,不是新开的口子。 +- 长度核对只能发现"实际字节少于声明"。UP 的已知问题是声明的长度本身偏小(库里的 size 错了),客户端收到的字节数和声明一致,但内容不完整,SDK 发现不了;这需要在服务端修数据,见 UP 的 `download-size-mismatch` runbook。 +- `hiagent-api` 的 wheel 配置是 `packages = ["."]`,新增的 `tests/data/` 会随 `tests/` 一起进入 wheel。这是既有问题,在 6.4 构建后检查 wheel 内容并记录,不在本次修。 diff --git a/openspec/changes/align-up-service/proposal.md b/openspec/changes/align-up-service/proposal.md new file mode 100644 index 0000000..f0f06ee --- /dev/null +++ b/openspec/changes/align-up-service/proposal.md @@ -0,0 +1,84 @@ +## 为什么 + +`hiagent_api.up.UpService` 的五个公开方法(`UploadRaw`、`LongLive`、`DownloadKey`、`Download`、`Delete`)与 UP 服务端当前的验签方式和接口契约不一致。对照基准是 upload-server `origin/main`(`64723ae0`)的 `idl/upload.thrift`、`idl/download.thrift`、`pkg/server/middlewares/dispatcher/dispatcher.go`、`pkg/server/middlewares/authz/authz.go`,以及它依赖的 iam-server `sdk.CheckSignature`。Java SDK 已在 `fix-up-client-signature`、`align-up-client-models` 两个变更中完成同样的对齐,本变更把 Python 补齐到同一口径;与 Java 不同的取舍在 design 中逐条说明。 + +### 验签失败 + +UP 的 `CheckSignature` 只从请求头取 `X-Date` 和 `Authorization`,用自己收到的请求重算签名。 + +- `UploadRaw` 用 `SignerV4.sign_url` 把签名写进 query,请求头里没有 `X-Date`、`Authorization`。UP 把它当作未签名请求,只有部署开启匿名访问、或 `authz.unsignedActions` 放行 `UploadRaw` 时才成功;关闭匿名(当前安全默认)时被拒。 +- `DownloadKey` 的 `ApiInfo` 方法是 `POST`,`Service.get()` 按 `POST` 计算 canonical request 后却发出 `GET`,UP 按 `GET` 重算,结果是 `signature not match`。 +- `Download` 有同样的方法错配,只是 query 带非空 `Key` 时 UP 在验签之前放行(`authz.go` 中 `action == "Download" && c.QueryParam("Key") != ""`),所以现在能用。 +- 所有方法都使用 volcengine `SignerV4.sign`,它把 `host` 签进去,并对整个请求体重新计算哈希。经域名或七层网关改写 Host 时会失配;上传大文件时只能整个读进内存。 + +### 模型与契约不一致 + +- `UploadRawRequest` 的 `Expire`、`ContentType`、`Sha256` 是没有默认值的必填字段,UP 都是可选的;SDK 也不会自动计算 sha256。缺少 `Filename`、`ImageCompress`。 +- `UploadRaw` 把 `Sha256`、`ContentType` 也拼进 query,UP 只从 header 读取。 +- 响应缺字段:`UploadRaw` 的 `ShortLink`、`PresignKey`;`LongLive` 的 `Sha256`、`ShortLink`;`DownloadKey` 的 `Size`、`ContentType`。pydantic 会静默丢弃这些字段。 +- `DownloadKey`、`Download` 只支持 `Path`,UP 支持 `Path` 和 `Sha256` 二选一。`Download` 缺少 `ID`、`Filename`、`ImageCompress`。 +- `Download` 把本地路径 `SaveTo` 当成 query 参数发给 UP。 +- `LongLive` 的请求键是 `Id`,UP 的 `json` tag 是 `ID`。现在能绑定只是因为 Go `encoding/json` 有不区分大小写的兜底;一旦匹配不上,UP 会建一条 ID 为空、无法通过 `Delete` 释放的关联,且不报错。 +- SDK 原样发送调用方的 sha256。UP 存储和比较的都是小写十六进制,大写值会被判为不匹配或查不到。 + +### 其他缺陷 + +- `UploadRaw`、`DownloadKey` 在响应缺少 `Result` 时写成了 `Exception(...)`,漏了 `raise`,随后因 `KeyError` 失败。 +- `Download` 边收边写 `SaveTo`:传输中断会留下残缺文件,并且已经覆盖了原有文件。 +- `libs/api/tests` 中没有任何 UP 测试。 + +## 变更内容 + +- 新增包内模块 `hiagent_api/_up_signer.py`,移植 Java `UpSigner`:按最终要发出的请求计算签名;SignedHeaders 固定为 `x-content-sha256;x-date`,不签 `host`;payload hash 取请求自带的 `X-Content-Sha256`。AK、STS token 含非法字符时抛出不含凭证值的 `ValueError`。 +- 五个方法统一发 `POST`、请求头签名、每个请求都带 `X-Content-Sha256`。`UploadRaw` 在调用方未提供 sha256(`None` 或空白串)时先流式计算一遍,再流式上传。 +- AK、SK 都未配置时不签名直接发送,由 UP 按部署配置决定是否放行。旧版用空凭证照样签名,在 `unsignedActions` 部署上会被拒;不签名是唯一在所有放行路径上都成立的做法。只配置了其中一个时抛 `ValueError`。 +- 按 UP 契约补齐请求和响应字段,新字段全部可选,原有字段由必填放宽为可选的不影响旧调用。`Download` 的参数(含 `Key`)继续走 query,保持 UP 在验签前按 `Key` 放行的路径;`SaveTo` 不再发送。`LongLive` 的请求键改为 `ID`,Python 属性名和构造方式不变。 +- SDK 发出的所有 sha256 去首尾空白并转小写,不修改调用方的请求对象。 +- `UploadRaw` 缺 `Id`、`LongLive` 缺 `ID`、`Download` 缺 `SaveTo` 时在发请求前抛出 `ValueError`。 +- `Download` 流式写入 `SaveTo` 所在目录的临时文件,核对写入字节数与 `Content-Length` 后用 `os.replace` 原子替换目标(不依赖 urllib3 版本是否校验长度);失败时删除临时文件,不留残缺文件、不破坏已有文件。 +- 响应缺少 `Result` 时抛出明确的 `Exception`。 +- 已配置的 productCode 在五个方法上都发送 `X-Trace-Product-Code`,不参与签名;未配置时不发送。 + +## 非目标 + +- 不新增 Action(`BatchDelete`、`Version`、分片上传、Blob、Artifact、Presign 等),不新增异步接口。 +- 国密(HMAC-SM3 签名、SM3 文件哈希)。 +- 中间代理改写路径(如 ingress `rewrite-target`)的部署形态:UP 按收到的路径验签,客户端无法签对。 +- 不暴露 `Download` 的 `Range` 和 `IsAnonymous`,原因与 Java `align-up-client-models` 相同:续传需要按 `Content-Range` 偏移写入;匿名是部署级开关,不引导调用方依赖它。 +- 不改 `UploadRaw` 未设置 `ContentType` 时的默认值 `application/octet-stream`(UP 开启 `contentType.mustMatch` 时按扩展名推断反而可能被拒)。 +- 不改 `Version` query 参数的值(`2022-01-01`),UP 不校验它。 +- 不迁移到 `hiagent_api.base` 的 httpx 实现,`UpService` 继续继承 volcengine `Service`。 +- 不改 `hibot`、`eva`、`observe`、`components`。不改版本号,随下一个补丁版本发布。 +- 不处理 `hiagent-api` wheel 会带上 `tests/` 的既有打包问题(`packages = ["."]`),只在构建时检查并记录。 + +## 功能 (Capabilities) + +### 新增功能 + +- `python-sdk-up-service`: `UpService` 的请求签名、凭证校验、请求体哈希、字段契约、哈希规范化与下载落盘。 + +### 修改功能 + +无。 + +## 影响 + +- 代码:`libs/api/hiagent_api/up.py`、`up_types.py`,新增 `_up_signer.py`;新增 `libs/api/tests/test_up_*.py` 与测试数据 `libs/api/tests/data/up_signature_vectors.json`(取自 Java SDK,由 UP 服务端验签库离线生成)。 +- 示例与文档:`libs/api/examples/up/*` 说明 `Sha256` 可省略并补充新字段,`ContentType="plain/text"` 改为标准的 `text/plain`;`agent-harness` 调用方式不变,补回归测试。 +- 公开 API:只有新增字段和"必填放宽为可选",原有构造与调用方式保持可用。 +- 线上行为变化(需写进发版说明): + - 所有方法改为 `POST` + 请求头签名;`DownloadKey`、`Download` 由 `GET` 改为 `POST`。 + - `UploadRaw` 的 query 不再携带 `Sha256`、`ContentType`;`Download` 的 query 不再携带 `SaveTo`,其余参数仍在 query。 + - `LongLive` 请求体的键由 `Id` 变为 `ID`。 + - 调用方传入大写 sha256 时,SDK 发出小写;`UploadRawRequest.Sha256` 为空白串时改为自动计算,不再原样发送空值。 + - `UploadRaw` 缺 `Id`、`LongLive` 缺 `ID`、`Download` 的 `SaveTo` 为空白时,本地抛 `ValueError`,不再发请求。 + - `UploadRaw` 未提供 `Sha256` 且文件对象不可 seek 时,本地抛 `ValueError`。 + - 只配置了 AK、SK 其中之一或只配置了 STS token,或 AK、STS token 含控制字符、空格或非 ASCII 字符时,本地抛 `ValueError`。 + - 不再跟随 HTTP 重定向:收到 3xx 时抛出含状态码和 `Location` 的异常。网关对同一主机做 http→https 重定向的部署,需要把 endpoint 改成 https。 + - 非 200 且响应体为空时,异常信息改为包含状态码(原先为空串)。 + - `Download` 的 `SaveTo` 为目录或非普通文件(如 `/dev/null`、FIFO)时,发请求前抛异常;原先目录要下载完才报错,`/dev/null` 可用来丢弃下载内容。 + - 未配置凭证时请求不再带空凭证签名,而是完全不签名。 + - `Delete` 收到不含 `Result` 的 200 响应时改为抛 `Exception`(原先返回整个响应 JSON)。UP 的 `Delete` 成功时总是返回 `"Result": {}`,只影响 mock 或非 UP 实现。 + - `Download` 成功后 `SaveTo` 是一个新文件(经原子替换):`SaveTo` 为符号链接时替换的是链接指向的文件;目标已存在时保留其权限位。 + - `Download` 需要目标文件所在目录可写(要在那里创建临时文件);原先只要求目标文件本身可写。 + - `Download` 收到的字节数少于声明的 `Content-Length` 时抛异常;原先在 urllib3 1.26 上会静默写出残缺文件。 diff --git a/openspec/changes/align-up-service/specs/python-sdk-up-service/spec.md b/openspec/changes/align-up-service/specs/python-sdk-up-service/spec.md new file mode 100644 index 0000000..1e16db8 --- /dev/null +++ b/openspec/changes/align-up-service/specs/python-sdk-up-service/spec.md @@ -0,0 +1,251 @@ +## ADDED Requirements + +### Requirement: 签名只针对实际发出的请求 + +配置了凭证时,`UpService` 的五个方法必须(MUST)对最终发出的请求签名:method、解码后的 path、全部 query 和 `X-Content-Sha256` 都取自实际发出的请求。签名必须放在请求头 `X-Date` 与 `Authorization` 中,SignedHeaders 必须为 `x-content-sha256;x-date`,不得包含 `host`。query 解码必须把 `+` 解为空格,path 解码必须保留字面 `+`。 + +#### Scenario: 与 UP 服务端签名样例一致 + +- **WHEN** 用 `up_signature_vectors.json` 中每条样例的 method、URL、`X-Date`、`X-Content-Sha256` 和凭证计算签名 +- **THEN** canonical request、待签串和签名必须与样例完全一致 + +#### Scenario: 按收到的请求重算签名 + +- **WHEN** 五个方法中的任意一个发出请求 +- **THEN** 按收到的 method、URL 和 `X-Content-Sha256` 重算出的签名必须等于收到的 `Authorization` 中的签名 +- **AND** 请求头中必须有 `X-Date`,query 中不得出现签名参数 + +#### Scenario: 经网关改写 Host + +- **WHEN** 请求的 `Host` 与 endpoint 主机名不同 +- **THEN** 签名结果不受影响 + +#### Scenario: 签名与发送使用同一个 method + +- **WHEN** 某个 Action 的 `ApiInfo` method 被改为 `POST` 以外的值 +- **THEN** 发出的请求使用该 method,按收到的请求重算的签名仍然一致 + +### Requirement: 凭证校验不泄漏凭证 + +签名前必须(MUST)去掉 `session_token` 的首尾空白,并校验 `ak`、`session_token` 只含可打印 ASCII。校验失败抛出的 `ValueError` 不得包含凭证值,也不得关联底层异常。 + +#### Scenario: 凭证含非法字符 + +- **WHEN** `ak` 或 `session_token` 含换行、控制字符、空格或非 ASCII 字符 +- **THEN** SDK 必须在发出请求前抛出 `ValueError` +- **AND** 异常信息中不包含该凭证的值 + +#### Scenario: AK 带尾随换行 + +- **WHEN** `ak` 末尾带换行(AK 不做 strip) +- **THEN** SDK 必须在发出请求前抛出 `ValueError`,而不是把它交给 `requests` 在 `InvalidHeader` 中带出 `Authorization` 的值 + +#### Scenario: STS token 带尾随换行 + +- **WHEN** `session_token` 末尾带换行 +- **THEN** SDK 必须去掉换行后正常发送 `X-Security-Token` + +### Requirement: 未配置凭证时的行为 + +AK、SK、STS token 都未配置时,SDK 必须(MUST)照常发出请求但不签名;配置了其中一部分但 AK、SK 不全时,必须在发请求前抛出 `ValueError`。 + +#### Scenario: 都未配置 + +- **WHEN** AK、SK 都为空时调用任意方法 +- **THEN** 请求照常发出,不带 `X-Date`、`Authorization` +- **AND** 仍然带 `X-Content-Sha256` + +#### Scenario: 只配置一半 + +- **WHEN** 只配置了 AK 或只配置了 SK,或只配置了 STS token +- **THEN** SDK 必须抛出 `ValueError`,且不发出请求 + +### Requirement: 统一使用 POST + +五个方法都必须(MUST)以 `POST` 发出,签名使用的方法必须与发出的方法一致。 + +#### Scenario: DownloadKey 与 Download + +- **WHEN** 调用 `DownloadKey` 或 `Download` +- **THEN** 实际发出的方法必须是 `POST` +- **AND** 签名的 canonical request 必须以 `POST` 开头 + +### Requirement: 请求体哈希与请求体一致 + +每个请求都必须(MUST)发送 `X-Content-Sha256`,值必须等于实际请求体的 SHA-256(小写十六进制)。 + +#### Scenario: UploadRaw 未提供 Sha256 + +- **WHEN** 调用方传入可 seek 的文件对象,且 `Sha256` 为 `None`、空串或空白串 +- **THEN** SDK 必须流式计算文件从当前位置到末尾的 SHA-256,并把这部分内容完整上传 + +#### Scenario: UploadRaw 文件不可 seek + +- **WHEN** 调用方传入不可 seek 的流(`tell()` 或 `seek()` 失败),且未提供 `Sha256` +- **THEN** SDK 必须在发出请求前抛出 `ValueError` + +#### Scenario: UploadRaw 提供 Sha256 时不要求可 seek + +- **WHEN** 调用方提供了 `Sha256`,且传入不可 seek 的流 +- **THEN** SDK 必须正常流式上传 + +#### Scenario: 其他请求 + +- **WHEN** 调用 `LongLive`、`DownloadKey`、`Download` 或 `Delete` +- **THEN** `X-Content-Sha256` 必须等于实际发出的请求体字节(可能为空)的 SHA-256 + +### Requirement: sha256 规范化 + +SDK 发出的所有 sha256 都必须(MUST)去掉首尾空白并转小写,且不得修改调用方的请求对象。必填的 `Delete.Sha256` 为空白时必须发送空串,不得发送 `null`。 + +#### Scenario: 没有 seekable() 的文件对象 + +- **WHEN** 调用方未提供 `Sha256`,传入的文件对象没有 `seekable()` 方法但能 `tell()`、`seek()`(如 Python 3.10 的 `SpooledTemporaryFile`) +- **THEN** SDK 必须照常计算 sha256 并上传 + +#### Scenario: 大写哈希 + +- **WHEN** 调用方向 `UploadRaw`、`DownloadKey`、`Download` 或 `Delete` 传入大写 sha256 +- **THEN** 发出的 `X-Content-Sha256`、`Sha256` query 或请求体中的 `Sha256` 必须是小写 +- **AND** 调用方模型里的值保持不变 + +### Requirement: 请求字段与 UP 契约一致 + +请求参数必须(MUST)按 UP 的绑定方式发送:`UploadRaw` 的 `Expire`、`Id`、`Filename`、`ImageCompress` 放在 query;`DownloadKey` 的 `Path`、`Sha256` 放在 query;`Download` 的 `Key`、`Path`、`Sha256`、`ID`、`Filename`、`ImageCompress` 放在 query 且请求体为空;`LongLive`、`Delete` 的字段放在 JSON 请求体,键名与 UP 的 `json` tag 一致。值为 `None` 的字段不得发送。 + +#### Scenario: UploadRaw 的 query + +- **WHEN** 调用 `UploadRaw` +- **THEN** query 中不得出现 `Sha256` 和 `ContentType` +- **AND** `ImageCompress=False` 必须以 `false` 发送 + +#### Scenario: LongLive 的 ID + +- **WHEN** 用 `LongLiveRequest(Id="x")` 调用 `LongLive` +- **THEN** 请求体的键必须是 `ID` + +#### Scenario: Download 保持 Key 在 query + +- **WHEN** 调用 `Download` +- **THEN** `Key` 必须出现在 query 中,请求体为空 +- **AND** 请求体和 query 中都不得出现 `SaveTo` + +### Requirement: 模型兼容与新字段 + +原有构造与调用方式必须(MUST)保持可用。`UploadRawRequest` 的 `Expire`、`ContentType`、`Sha256` 必须是可选字段;新增的请求和响应字段必须是可选字段,默认值为 `None`。 + +#### Scenario: 旧写法 + +- **WHEN** 调用方像旧版一样传入 `Expire`、`Id`、`ContentType`、`Sha256` 四个字段调用 `UploadRaw` +- **THEN** 请求必须成功发出,`Content-Type` 与 `X-Content-Sha256` 取调用方给的值(sha256 规范化后) + +#### Scenario: 新响应字段 + +- **WHEN** UP 返回 `ShortLink`、`PresignKey`、`Sha256`、`Size`、`ContentType` 等字段 +- **THEN** 对应响应模型必须能读取这些字段 +- **AND** UP 未返回时字段值为 `None` + +#### Scenario: ContentType 缺省 + +- **WHEN** `UploadRawRequest.ContentType` 为 `None` 或空串 +- **THEN** 必须以 `Content-Type: application/octet-stream` 发送 + +### Requirement: 发请求前的必填检查 + +`UploadRaw` 的 `Id`、`LongLive` 的 `ID` 为 `None` 或空串时,`Download` 的 `SaveTo` 为空白串时,SDK 必须(MUST)在读取文件或发出请求前抛出 `ValueError`。 + +#### Scenario: 缺 Id + +- **WHEN** 以空串 `Id` 调用 `UploadRaw`,或以空串 `ID` 调用 `LongLive` +- **THEN** SDK 必须抛出 `ValueError` +- **AND** 不得读取文件、不得发出任何请求 + +#### Scenario: 缺 SaveTo + +- **WHEN** 以空白串 `SaveTo` 调用 `Download` +- **THEN** SDK 必须抛出 `ValueError`,且不发出请求 + +### Requirement: productCode 注入 + +已配置 productCode 时,五个方法都必须(MUST)发送 `X-Trace-Product-Code`,且该 Header 不得进入 SignedHeaders;未配置时不得发送。 + +#### Scenario: 已配置 productCode + +- **WHEN** 调用 `set_product_code("maas")` 后调用任意方法 +- **THEN** 请求必须携带 `X-Trace-Product-Code: maas` +- **AND** 签名仍然有效 + +#### Scenario: 未配置 productCode + +- **WHEN** 未调用 `set_product_code`,或设置为空白串 +- **THEN** 请求不得携带 `X-Trace-Product-Code` + +### Requirement: 响应处理 + +非 200 响应必须(MUST)以 `Exception` 抛出并带上响应体,响应体为空时带上状态码;200 响应缺少 `Result` 时,五个方法都必须抛出说明缺少 `Result` 的 `Exception`。SDK 不得跟随重定向。 + +#### Scenario: 收到重定向 + +- **WHEN** 任意方法收到带 `Location` 的 301/302/307/308 响应 +- **THEN** SDK 只发出这一个请求,不跟随重定向 +- **AND** 抛出的 `Exception` 包含状态码和 `Location` + +#### Scenario: 非 200 且响应体为空 + +- **WHEN** 任意方法收到响应体为空的非 200 响应 +- **THEN** 抛出的 `Exception` 包含状态码 + +#### Scenario: 缺少 Result + +- **WHEN** 任意方法收到不含 `Result` 的 200 JSON 响应 +- **THEN** SDK 必须抛出信息中包含 `no Result in response` 的 `Exception`,而不是 `KeyError`,也不是返回整个响应 + +### Requirement: 下载原子落盘 + +`Download` 必须(MUST)先把响应流式写入 `SaveTo` 目标所在目录的临时文件,完整收到后再原子替换目标,并在任何情况下释放响应连接。失败时不得留下临时文件,也不得改动已有的目标文件。 + +#### Scenario: 下载成功 + +- **WHEN** `Download` 收到 200 响应 +- **THEN** 目标文件内容必须与响应体一致 + +#### Scenario: 父目录不存在 + +- **WHEN** `SaveTo` 的父目录不存在 +- **THEN** SDK 必须在发出请求前抛出 `FileNotFoundError`,不自动创建目录,与旧版 `open(SaveTo, "wb")` 一致 + +#### Scenario: SaveTo 以路径分隔符结尾 + +- **WHEN** `SaveTo` 以路径分隔符结尾,且该路径不存在 +- **THEN** SDK 必须在发出请求前抛出 `IsADirectoryError`,不创建任何文件 + +#### Scenario: 目标文件名很长 + +- **WHEN** `SaveTo` 的文件名合法但接近系统上限 +- **THEN** 下载必须成功,临时文件名的长度不依赖目标文件名 + +#### Scenario: 下载中断 + +- **WHEN** 响应在传输中途中断(实际字节少于未压缩响应声明的 `Content-Length`,或读取时抛出异常),且 `SaveTo` 处已有文件 +- **THEN** SDK 必须抛出异常,且不依赖所装 urllib3 版本是否校验长度 +- **AND** 已有文件内容保持不变,目录中不残留临时文件 + +#### Scenario: 下载失败 + +- **WHEN** `Download` 收到非 200 响应 +- **THEN** SDK 抛出 `Exception`,且不创建目标文件 + +#### Scenario: SaveTo 是符号链接 + +- **WHEN** `SaveTo` 指向一个符号链接 +- **THEN** 写入的必须是链接指向的文件,链接本身保留 + +#### Scenario: SaveTo 不是普通文件 + +- **WHEN** `SaveTo`(解析符号链接后)是目录,或是设备文件、FIFO 等非普通文件 +- **THEN** SDK 必须在发出请求前抛出异常(目录为 `IsADirectoryError`,其余为 `ValueError`),不改动该路径 + +#### Scenario: 覆盖私有文件 + +- **WHEN** `SaveTo` 处已有权限为 0600 的文件 +- **THEN** 下载过程中的临时文件权限必须是 0600,完成后目标权限仍为 0600 diff --git a/openspec/changes/align-up-service/tasks.md b/openspec/changes/align-up-service/tasks.md new file mode 100644 index 0000000..08dbe64 --- /dev/null +++ b/openspec/changes/align-up-service/tasks.md @@ -0,0 +1,56 @@ +## 1. 签名器 + +- [x] 1.1 复制 Java SDK 的 `up-signature-vectors.json` 到 `libs/api/tests/data/up_signature_vectors.json`,先写样例测试并确认失败。 +- [x] 1.2 先写签名器边界测试:query 中字面 `+` 解为空格、path 中字面 `+` 保留;只返回签名相关 Header,不签 host。 +- [x] 1.3 先写凭证校验测试:`ak`/`session_token` 含 `\n`、`\r`、控制字符、空格、非 ASCII 时抛 `ValueError`,异常信息不含凭证值,`__cause__`/`__context__` 为空;`session_token` 尾随换行被去掉。 +- [x] 1.4 新增 `libs/api/hiagent_api/_up_signer.py`:凭证校验、query 规范化与编码(`unquote_plus` / `quote(safe="-_.~")`)、path 解码(`unquote`)、canonical request、待签串、派生密钥、`sign()`。 +- [x] 1.5 1.1–1.3 全部通过。 + +## 2. 模型 + +- [x] 2.1 先写模型测试:旧写法可用、新字段可选、`Id` 仍为必填(缺参时 `ValidationError`)、`LongLiveRequest(Id=...)` 以 `ID` 序列化、`DownloadRequest.SaveTo` 不进入 dump 结果、响应新字段可解析。 +- [x] 2.2 按 design 修改 `libs/api/hiagent_api/up_types.py`,补全字段注释(`Expire` 格式与不过期写法、`ContentType` 建议填真实类型、`Sha256` 可省略)。 + +## 3. UpService + +- [x] 3.1 先写请求测试(requests fake adapter),覆盖 design「测试方案」第 3–6 项,包括: + - 五个方法均为 `POST`,按收到的请求重算签名一致,`X-Content-Sha256` 与请求体一致; + - query 和请求体形状,`Download` 的 `Key` 在 query、请求体为空; + - sha256 转小写,`Sha256` 为 `None`/`""`/空白时自动计算; + - 文件已 seek 到非零偏移时只哈希并上传剩余部分;提供 `Sha256` 时不可 seek 的流也能上传;未提供且不可 seek 时报错; + - `Id` 空串报错且先于读文件和 `seekable()`,空白 `Id` 照发;`LongLive` 缺 `ID` 不发请求; + - productCode 有无;用 `CaseInsensitiveDict` 合并 Header,不重复、不修改 `service_info.header`;User-Agent 取自 `volcengine.VERSION`; + - 初始化后 `set_ak`/`set_sk` 生效;STS token;未配置凭证时不签名照发;只配一半时报错; + - 五个方法缺 `Result` 时都报错。 +- [x] 3.2 实现私有 `_send()`,五个方法改用它;移除对 `SignerV4`、`Service.get/json/prepare_request` 的使用(`ApiInfo` 原本就是 `POST`,保持不变)。 +- [x] 3.3 `UploadRaw` 流式计算 sha256 并 seek 回原位置后上传。 +- [x] 3.4 修正 `DownloadKey` 的 docstring 与各方法 docstring 中的字段说明。 + +## 4. 下载落盘 + +- [x] 4.1 先写落盘测试: + - 成功下载、自动建目录; + - 空白 `SaveTo` 不发请求; + - 非 200 不建文件且释放连接; + - 中途中断两种(fake adapter):响应体短于 `Content-Length`、响应流读到一半抛异常;旧文件都不变且没有残留临时文件; + - 带 `Content-Encoding` 或没有 `Content-Length` 时跳过长度核对; + - 符号链接、已有文件的权限位保留。 +- [x] 4.2 实现:`with` 包住流式响应,临时文件、长度核对、`copymode`、`os.replace`;做两项变异验证:改成直接写目标文件时中断用例必须失败,去掉长度核对时短响应用例必须失败。 +- [x] 4.3 自审补充(先写测试,再实现):AK 尾随换行用 `fullmatch` 拦截;只配 STS token 时报错;不跟随重定向,3xx 和空响应体错误带状态码;`SaveTo` 为目录或非普通文件时发请求前报错;覆盖已有文件时临时文件以 0600 创建。变异验证:临时文件改回 0o666 时 0600 用例失败。 +- [x] 4.4 简化(先改测试,再实现):`sign()` 直接接收 payload hash、只返回签名 Header;签名与发送的 method 都取自 `ApiInfo`;去掉自动创建父目录,父目录不存在时抛 `FileNotFoundError`。 +- [x] 4.5 第三轮 review(先写失败用例,再实现):可 seek 判断改为试 `tell()`/`seek()`,兼容 3.10 的 `SpooledTemporaryFile`;临时文件名改为定长 `.up-.part`;`SaveTo` 以分隔符结尾、父目录不存在都在发请求前报错;`Delete` 空白 `Sha256` 发 `""` 不发 `null`;e2e 清理改为两层 `try/finally`;design 中 `from None` 的描述改正。 + +## 5. 调用方、示例与文档 + +- [x] 5.1 `agent-harness` 的 `test_up_endpoints.py` 补充 `upload_raw_file`、`download_file` 回归用例。 +- [x] 5.2 更新 `libs/api/examples/up/*`:`Sha256` 可省略,补新字段用法;`ContentType="plain/text"` 改为 `text/plain`(`up_uploadraw.py`、`up_full.py`)。 +- [x] 5.3 新增 `libs/api/tests/test_up_e2e.py`(`e2e` 标记,缺环境变量时跳过);`.env-sample` 已有 `HIAGENT_UP_UPLOAD_ENDPOINT`、`HIAGENT_UP_DOWNLOAD_ENDPOINT`,确认无需新增。 +- [x] 5.4 按 proposal「影响」整理发版说明中的行为变化(仓库没有 CHANGELOG,发版说明以 proposal「影响」为准)。 + +## 6. 验证 + +- [x] 6.1 `uv run pytest libs/api/tests -q`。 +- [ ] 6.2 `uv run pytest -q`(workspace 回归)被既有问题阻断:agent-harness 4 个测试文件收集时报 `ModuleNotFoundError: cli_anything`,暂存本次改动后同样复现。替代验证:`uv run pytest libs -q` 158 passed / 4 skipped,`PYTHONPATH=agent-harness uv run pytest agent-harness -q` 52 passed。原文:agent-harness 不在 workspace 内,单独执行 `PYTHONPATH=agent-harness uv run pytest agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py -q`。 +- [x] 6.3 `uv run ruff check .`、`git diff --check`。(workspace 未装 ruff,改用 `uvx ruff` 0.17.6;本次新增和改动的文件无告警,其余既有告警未处理。) +- [x] 6.4 `uv build --package hiagent-api`,检查 wheel 内容并记录 `tests/`(含 `tests/data/`)是否被打入(既有打包问题,本次只记录)。结果:构建成功,wheel 中包含 `tests/` 与 `tests/data/up_signature_vectors.json`。 +- [x] 6.5 在关闭匿名访问的 UP 上跑一次 e2e,记录 UP 版本、各步状态码,不记录凭据。结果(2026-11-30):UP `upload-server:v3.2.1-20261106143046`,临时把 `anonymous.enableIsAnonymous` 改为 `false`(`unsignedActions: []`),跑完已恢复原配置。未签名请求被拒(`missing X-Date header`),错误 SK 被拒(`signature not match`);`test_up_e2e.py` 通过:UploadRaw、LongLive、DownloadKey、Download、两次 Delete 均为 200,UP 日志对每个签名请求都有 `check identity with iam`。测试的 socket timeout 调为 30 s:该环境 UploadRaw 需 1–7 s,超过 SDK 默认的 5 s。