Skip to content

fix(up): align UpService with UP's signature check and Action contract - #63

Merged
hallucigenia merged 6 commits into
mainfrom
fix/align-up-service
Nov 30, 2026
Merged

hallucigenia merged 6 commits into
mainfrom
fix/align-up-service

Conversation

@hallucigenia

@hallucigenia hallucigenia commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

UpService did not match how UP verifies signatures or binds Action parameters. UP recomputes the signature from the request it receives and only reads X-Date / Authorization from headers, so:

  • UploadRaw signed into the query string and was treated as unsigned — it only worked where anonymous access or authz.unsignedActions let it through.
  • DownloadKey signed POST but sent GET → signature not match whenever UP verifies.

This aligns the Python client with UP's contract (same scope as the Java SDK's fix-up-client-signature + align-up-client-models). Design and spec: openspec/changes/align-up-service/.

Changes

  • Signer (hiagent_api/_up_signer.py, ported from the Java UpSigner): signs the exact method, URL and X-Content-Sha256 that go on the wire (method from ApiInfo, used for both signing and sending; the signer takes the payload hash and returns only the signing headers); SignedHeaders=x-content-sha256;x-date (Host not signed). Checked against vectors generated offline by UP's own verifier.
  • Requests: all five actions are header-signed POSTs. No AK/SK → sent unsigned (the only option that works with unsignedActions); half-configured (including an STS token without AK/SK) or malformed AK/STS token → local ValueError that never echoes the value. Redirects are not followed.
  • Models: UploadRawRequest.Expire/ContentType/Sha256 optional; new Filename, ImageCompress, Sha256, ID request fields and ShortLink, PresignKey, Sha256, Size, ContentType response fields; LongLive sends ID; SaveTo is never sent; every sha256 is sent lowercase.
  • UploadRaw computes the sha256 by streaming when it is not given (or blank). Any file object that can tell()/seek() qualifies, including Python 3.10's SpooledTemporaryFile (FastAPI UploadFile.file), which has no seekable().
  • Download keeps Key in the query (UP's pre-signature pass for Download reads only the query), writes to a fixed-length temp file (.up-<uuid>.part) in the target directory (the parent directory must exist, as before; checked before the request is sent), checks the byte count against Content-Length (urllib3 1.26 does not), keeps the existing file mode (the partial file is 0600 while overwriting an existing file), and atomically replaces SaveTo. A directory or non-regular SaveTo (device, FIFO) is rejected before the request is sent. A failed download leaves the old file untouched.
  • Responses without Result now raise instead of KeyError.

Behavior changes (release notes)

  • DownloadKey / Download switch from GET to POST; UploadRaw no longer puts Sha256/ContentType in the query; Download no longer sends SaveTo.
  • LongLive body key Id → ID.
  • Uppercase sha256 is sent lowercase; blank UploadRawRequest.Sha256 is now computed instead of sent empty.
  • Local ValueError for: empty UploadRaw Id / LongLive ID, blank Download.SaveTo, unseekable file without Sha256, half-configured or malformed credentials (including an STS token without AK/SK); IsADirectoryError / ValueError when Download.SaveTo is a directory (including a path ending in /) or not a regular file (e.g. /dev/null, which used to discard the download); FileNotFoundError before the request when its parent directory is missing (previously raised after the response arrived).
  • Redirects are no longer followed: a 3xx raises with the status code and Location. Deployments behind a same-host http→https redirect must use an https endpoint.
  • A non-200 with an empty body now raises with the status code instead of an empty message.
  • Without credentials, requests are sent unsigned instead of signed with an empty AK.
  • Delete raises on a 200 without Result (UP always returns "Result": {}).
  • Download needs the target directory to be writable; a short read now raises.

Test plan

  • uv run pytest libs/api/tests -q — 102 passed, 1 skipped (opt-in e2e)
  • CI workflow (from ci: run package and agent-harness tests on pull requests #64) on this PR: pytest libs -m "not e2e" 161 passed, 3 skipped, 1 deselected; agent-harness 52 passed
  • Signature vectors from UP's verifier reproduce exactly (incl. reserved chars and CJK in the query)
  • Mutation checks: writing the target directly, or dropping the length check, or creating the partial file as 0o666, makes the download tests fail
  • uv run pytest libs -q — 161 passed, 4 skipped
  • PYTHONPATH=agent-harness uv run pytest agent-harness -q — 52 passed (includes a new round trip through the real UpService)
  • uv build --package hiagent-api; uvx ruff check clean on changed files; git diff --check
  • Plain uv run pytest -q is blocked by an existing agent-harness collection error (No module named 'cli_anything'), reproduced on main without this change
  • Real UP round trip with anonymous access disabled (UP v3.2.1, enableIsAnonymous: false, unsignedActions: []; switched off temporarily and restored): unsigned request rejected (missing X-Date header), wrong SK rejected (signature not match), test_up_e2e.py passed — UploadRaw → LongLive → DownloadKey → Download → Delete ×2, each signed call resolved by UP via IAM

Note: the hiagent-api wheel already ships tests/ (packages = ["."]); the new tests/data/ follows it. Pre-existing, not changed here.

sai-bot added 4 commits November 26, 2026 00:22
UP verifies signatures from the request it receives, reading X-Date and
Authorization from headers only. UploadRaw signed into the query (seen as
unsigned) and DownloadKey signed POST but sent GET, so both failed on UP
deployments with anonymous access disabled.

- Add _up_signer, ported from the Java UpSigner: sign the exact method,
  URL and X-Content-Sha256 that are sent; SignedHeaders is
  x-content-sha256;x-date (host not signed). Validated against vectors
  generated by UP's own verifier.
- All five actions are header-signed POSTs. Without AK/SK, requests go
  out unsigned; half-configured or malformed credentials fail locally
  without echoing their values.
- Align models with UP's IDL: optional Expire/ContentType/Sha256, new
  Filename/ImageCompress/Sha256/ID fields and response fields, LongLive
  sends ID, SaveTo never leaves the client, sha256 sent lowercase.
- UploadRaw streams the sha256 when not given. Download keeps Key in the
  query (UP's pre-signature pass for Download), writes a temp file,
  checks Content-Length and atomically replaces SaveTo.
- Raise on responses missing Result instead of KeyError.

OpenSpec: openspec/changes/align-up-service
- Reject an AK with a trailing newline (re.match + $ let it through, and
  requests would then echo the Authorization value in InvalidHeader).
- Treat a session token without AK/SK as half-configured credentials
  instead of silently sending the request unsigned.
- Do not follow redirects: the signature covers the original URL, 301/302
  turn the POST into a GET, and a cross-host redirect keeps
  X-Security-Token. 3xx and empty-body errors now report the status code
  (and Location).
- Check SaveTo before sending: a directory raises IsADirectoryError, a
  non-regular file (device, FIFO) raises ValueError instead of having its
  node replaced by os.replace.
- When overwriting an existing file, create the partial file as 0600 so a
  private file's content is never readable while downloading.
- Build the Download query from the model dump, like Delete.
…ent dirs

- _up_signer.sign() takes the payload hash _send already has and returns
  only X-Date / Authorization / X-Security-Token; _send merges them into
  its CaseInsensitiveDict. Drops the header lookup and the dict copy.
- Sign and send with ApiInfo.method (session.request), so the method has
  a single source instead of three hard-coded "POST"s.
- Download no longer creates missing parent directories: a missing parent
  raises FileNotFoundError, as open(SaveTo, "wb") did before.
The e2e services use a 30 s socket timeout: UploadRaw on a real
deployment can take longer than the SDK's 5 s default.
hallucigenia added a commit that referenced this pull request Nov 30, 2026
## Summary

The repository has no GitHub Actions workflow. The only checks on pull
requests come from CodeQL's default setup, so tests are never run in CI.
For example, #63's green checks say nothing about its tests.

This adds `.github/workflows/ci.yml`. It runs the same commands
contributors run locally, on every pull request and on pushes to `main`:

- `uv sync --locked --all-packages`, so every workspace member is
installed even if the root dev group stops listing it. Python 3.10 comes
from `.python-version`, the lowest supported version. A stale `uv.lock`
fails the job.
- `uv run --no-sync pytest libs -q -m "not e2e"`. Tests marked `e2e`
need a real backend and are deselected explicitly. Unmarked
real-environment tests, like hibot's, still skip themselves.
- `PYTHONPATH=agent-harness uv run --no-sync pytest agent-harness -q`.
agent-harness is not a uv workspace member.

The workflow has read-only `contents` permission and no secrets. It uses
no event payload in `run:` steps. Actions are pinned to commit SHAs
(`actions/checkout` v4.4.0, `astral-sh/setup-uv` v6.8.0), and the
checkout doesn't keep the token. On a pull request, a new push cancels
the run still in progress; every run on `main` finishes.

### Not included

- **agent-harness's own dependencies**: `setup.py` requires `click` and
`prompt-toolkit`, which are not in the lock. `click` arrives only
through `chainlit`/`uvicorn` in the root dev group, and `prompt_toolkit`
isn't imported by any test yet. The fix is to make agent-harness a
workspace member, which also fixes the `cli_anything` collection error
below. That's its own change.

- **`ruff check`**: `main` currently has 39 lint errors that predate
this PR. It can be added once they're fixed.
- **Plain `uv run pytest -q`**: it fails during collection on
agent-harness (`No module named 'cli_anything'`), so the two directories
run as separate steps.

## Test plan

- [x] Clean worktree of `origin/main` + `uv sync --locked`: `uv run
pytest libs -q`: 68 passed, 3 skipped; agent-harness: 51 passed
- [x] `uv lock --check` passes
- [x] The workflow runs green on this PR (first version: run
46377472592; after review: run 46388383326, 68 passed / 3 skipped, 51
passed)
- [x] On #63's code, `-m "not e2e"` deselects `test_up_e2e.py`: 156
passed, 3 skipped, 1 deselected

---------

Co-authored-by: sai-bot <sai-bot@bytedance.com>
sai-bot added 2 commits November 30, 2026 01:51
- Detect seekable input by probing tell()/seek() instead of seekable():
  Python 3.10's SpooledTemporaryFile (FastAPI UploadFile.file) seeks but
  has no seekable(), so auto-hashing rejected it.
- Name the partial download file .up-<uuid>.part: appending 39 bytes to
  the target's name could exceed NAME_MAX for a legal long filename.
- Check SaveTo before sending: a trailing separator raises
  IsADirectoryError (realpath dropped it and created a file), and a
  missing parent directory raises FileNotFoundError instead of failing
  after a 200.
- Delete sends a blank required Sha256 as "" rather than null.
- e2e cleanup deletes the second association even if the first fails.
- design.md: describe how credential errors avoid exception chaining.
@hallucigenia
hallucigenia merged commit 9a93fb0 into main Nov 30, 2026
3 checks passed
@hallucigenia hallucigenia mentioned this pull request Dec 1, 2026
3 tasks
hallucigenia added a commit that referenced this pull request Dec 1, 2026
## Summary

This PR prepares the release candidate **hiagent-api 3.1.1rc1**. Of the
published packages, only hiagent-api has changed since 3.1.0, through
the UpService alignment in #63. hiagent-eva, hiagent-components,
hiagent-observe and hibot keep their current versions.

- `dfd8e60` **fix(api): build wheels with only the `hiagent_api`
package.** The wheel config said `packages = ["."]`, so every file went
in under a `./` prefix. Installing the wheel also put `pyproject.toml`,
`README.md`, `.gitignore`, `PKG-INFO` and a top-level `tests` package
into site-packages. The published 3.1.0 wheel has this problem too. The
fix is the one hiagent-observe got in 3.2.1.
- `7fb70f5` **release:** sets version `3.1.1rc1` in
`libs/api/pyproject.toml`, in `VERSION` in `hiagent_api/base.py` (which
goes into the User-Agent), and on the hiagent-api line of `uv.lock`. I
edited only that lock line so the lockfile keeps its existing format
revision; `uv lock --check` passes.
- `f028803` **fix(api): ship license metadata and keep test names
unique.**
- Adds `libs/api/LICENSE`, `license = "Apache-2.0"`, `license-files`,
`hatchling>=1.27.0` and a real description. Workspace packages don't
inherit the root LICENSE (observe fixed the same gap in #60). This goes
in now so that rc1 already has the final metadata.
- Merges the two distribution tests into `test_api_distribution.py`. The
old file names were the same as the tests `release-3.2.1` adds under
`libs/observe/tests`, and with neither directory having an
`__init__.py`, merging that branch made `pytest libs` stop with "import
file mismatch".
- `9a9e1db` **test(api): build distributions in-process with the locked
hatchling.** The test no longer runs `uv build --offline` as a
subprocess. It calls hatchling's PEP 517 `build_wheel` and `build_sdist`
hooks from the package's own directory, and `hatchling>=1.27.0` is now
in the root `dev` group, so `uv.lock` pins it. Before this, the test
failed whenever the uv cache had been emptied, because hatchling wasn't
cached, and it also failed when run from an unpacked sdist, because the
build ran from the directory two levels above the package, which only
exists in the repository. Running `uv lock` also rewrote the lockfile to
format revision 5 and normalized a few markers. No existing package
changed version.

The other packages' `hiagent-api>=3.1.0` lower bounds are unchanged.

## Tests

- `libs/api/tests/test_api_distribution.py` builds the package
in-process with the locked hatchling and checks the wheel and the sdist.
It passes with an empty uv cache and no `uv` on PATH, and from an
unpacked sdist. Both of those failed before the last commit.
- **Wheel:** contains only `hiagent_api/` and
`hiagent_api-<VERSION>.dist-info/`, with normalized paths. In its
metadata, `Version` equals `base.VERSION`, `Summary` is set,
`License-Expression` is `Apache-2.0`, and the packaged LICENSE is
byte-identical to the source copy.
- **Sdist:** has a single root directory, normalized paths, includes
LICENSE, and leaves out `examples/`.
- It failed before each fix, and fails again if `base.VERSION` is
changed so it no longer matches the version in `pyproject.toml`.
- `pytest libs -m "not e2e"`: 163 passed, 3 skipped, 1 deselected.
- agent-harness: 52 passed.
- In a scratch worktree where `release-3.2.1` was merged on top of this
branch, `pytest libs --collect-only` collects with no errors.
- `uv build --package hiagent-api` and `twine check`: both pass.
- I installed the wheel into a clean Python 3.10 environment.
`hiagent_api.up` imports, `VERSION` and the installed metadata both say
`3.1.1rc1`, and site-packages gains only `hiagent_api` and its
`dist-info` besides dependencies.

## Merge

Please **squash-merge**. The branch commits carry a bot author from the
environment they were made in, and the squash commit takes the merger's
GitHub identity, as #63 and #64 did.

## After merge

- [ ] Tag the release and publish `hiagent-api==3.1.1rc1` to PyPI
(manual).
- [ ] Smoke-test UpService against a UP that has anonymous access
disabled, using the published rc.
- [ ] Separately: merge `release-3.2.1` back into `main`. Until then,
`main` still has observe at 3.1.0 with `packages = ["."]`.

---------

Co-authored-by: sai-bot <sai-bot@bytedance.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant