Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions agent-harness/cli_anything/hiagent_sdk/tests/test_up_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
6 changes: 3 additions & 3 deletions libs/api/examples/up/up_full.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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 = {}
Expand Down
6 changes: 3 additions & 3 deletions libs/api/examples/up/up_uploadraw.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import uuid

from dotenv import load_dotenv

from hiagent_api.up import UpService
from hiagent_api.up_types import UploadRawRequest

Expand All @@ -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"
162 changes: 162 additions & 0 deletions libs/api/hiagent_api/_up_signer.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading