Skip to content

Upload HTTP(S) outputs as bytes and escape names in directory uploads - #61

Merged
uniqueg merged 3 commits into
masterfrom
fix/http-upload-bytes
Oct 23, 2026
Merged

uniqueg merged 3 commits into
masterfrom
fix/http-upload-bytes

Conversation

@anuragxxd

@anuragxxd anuragxxd commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Fixes elixir-cloud-aai/TESK#215. That issue is filed in TESK, but the filer image is built from this repo.

HTTPTransput had two bugs that break HTTP(S) outputs, for example uploads to presigned URLs.

1. Outputs were uploaded as decoded text (Upload HTTP(S) outputs as bytes). upload_file opened the file in text mode, so:

  • binary outputs such as gzip or BAM raised UnicodeDecodeError and weren't uploaded;
  • CRLF line endings arrived as LF;
  • with urllib3 1.x, as in the v0.10.2 images, non-ASCII text was re-encoded as Latin-1 or failed to encode. Current master pins urllib3 2.x, which sends text as UTF-8.

The file is now opened in binary mode and passed to requests, which streams it instead of reading it into memory, and sets Content-Length from its size. An empty file is sent as b'', because requests sends an empty file object with chunked encoding, which presigned upload URLs such as S3's reject.

2. File names in directory uploads weren't escaped (Escape file names in HTTP(S) directory uploads). upload_dir appended each name to the URL as a plain string. result#1.txt was uploaded as result and a?b.txt as a, and both reported success. For a directory URL with a query, such as a token for a server that signs uploads, every file went to the directory's own URL with its name in the query. Names are now escaped and appended to the URL's path, and the query is kept.

Testing

New tests, using a local HTTP server:

  • ASCII, gzip, UTF-8 and CRLF content, and an empty file, each arrive byte for byte, with Content-Length and without chunked encoding;
  • http_join escapes #, ? and % and keeps the query;
  • every file of a directory, including one in a subdirectory, reaches the server under its own name with the query intact.

test_upload_dir now reads the file object it's given. On master, the gzip, CRLF and directory tests fail.

With Python 3.12 on Linux: 83 passed, 1 failed. The failure, test_ftp_upload_dir, fails on master too with the current test dependencies (pytest 9.1.1, pyftpdlib 2.2.0), so it's unrelated.

End to end, I uploaded with HTTPTransput through a small server that answers each PUT with a 307 to a fresh MinIO presigned URL:

Output master This branch
gzip file UnicodeDecodeError, not uploaded Byte-identical in MinIO
CRLF text Uploaded with LF Byte-identical
UTF-8 text, empty file Byte-identical Byte-identical
Directory of 6 files (result#1.txt, result#2.txt, a?b.txt, 50%25.txt, a b.txt, sub/y.txt) with ?token=abc in its URL upload_dir returned 0, yet all 6 PUTs went to the key dir, leaving one object, and the server saw queries such as token=abc/result All 6 under their own names, each with token=abc

To reach deployments

The TESK chart pins tesk-core-filer:v0.10.2 in charts/tesk/values.yaml, so this needs a new tag here and a chart bump. TESK's source/tesk-core has the same code; I can mirror the change there if that copy is still used.

Noticed, not changed

  • A 301, 302 or 303 response to an upload passes for success. requests follows a 302 or 303 with a GET, and a 301 with a PUT without the body, so upload_file returns 0 while nothing, or an empty object, is stored. Following only 307 and 308 for uploads would fix it.
  • download_file holds the whole response in memory (req.content). stream=True with iter_content would avoid that.

I can send either as a follow-up.

Summary by Sourcery

Preserve output bytes and safely construct HTTP(S) upload URLs for files and directories.

Bug Fixes:

  • Upload HTTP(S) outputs as their original bytes, including binary, UTF-8, CRLF, and empty files, while preserving content length requirements.
  • Escape file names in HTTP(S) directory uploads and preserve directory URL query parameters, including for non-UTF-8 names.

Enhancements:

  • Add HTTP server coverage for byte-accurate uploads, URL joining, query preservation, and directory uploads with special-character file names.

Tests:

  • Expand HTTP filer tests to verify streamed uploads use Content-Length without chunked transfer encoding and preserve directory file names.

HTTPTransput.upload_file read the output in text mode and uploaded the
decoded string, so binary outputs such as gzip or BAM failed with a
UnicodeDecodeError and CRLF line endings arrived as LF. With urllib3 1.x,
as in the v0.10.2 images, non-ASCII text was also re-encoded as Latin-1
or failed to encode.

The file is now opened in binary mode and passed to requests, which
streams it and sets Content-Length from its size. An empty file is sent
as b'', because requests sends an empty file object with chunked
encoding, which presigned upload URLs such as S3's reject.
HTTPTransput.upload_dir built each file's URL by appending the name as a
plain string. A file named result#1.txt was uploaded as result, the rest
becoming a fragment, a?b.txt was uploaded as a with b.txt as the query,
and both uploads reported success. For a directory URL with a query,
such as a token for a server that signs uploads, the name ended up in
the query.

The name is now escaped and appended to the URL's path, and the query is
kept.
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Fixes HTTP(S) output uploads by preserving file bytes and avoiding chunked encoding for empty files, and fixes directory uploads by safely escaping names into the URL path while retaining query tokens. Tests validate exact request bodies, headers, URL construction, and end-to-end directory routing.

Sequence diagram for byte-preserving HTTP output upload

sequenceDiagram
    participant Caller
    participant HTTPTransput
    participant File
    participant Requests
    participant HTTPServer
    Caller->>HTTPTransput: upload_file()
    HTTPTransput->>File: open(path, rb)
    HTTPTransput->>File: os.fstat(file.fileno())
    alt non-empty file
        HTTPTransput->>Requests: requests.put(url, data=file)
        Requests->>HTTPServer: PUT streamed bytes with Content-Length
    else empty file
        HTTPTransput->>Requests: requests.put(url, data=b'')
        Requests->>HTTPServer: PUT empty body with Content-Length: 0
    end
Loading

Sequence diagram for escaped HTTP directory upload

sequenceDiagram
    participant Caller
    participant HTTPTransput
    participant http_join
    participant Requests
    participant HTTPServer
    Caller->>HTTPTransput: upload_dir()
    loop each directory file
        HTTPTransput->>http_join: http_join(url, listing)
        http_join-->>HTTPTransput: escaped path with query preserved
        HTTPTransput->>HTTPTransput: upload_file()
        HTTPTransput->>Requests: requests.put(escaped_url, data=file)
        Requests->>HTTPServer: PUT file under escaped name with query token
    end
Loading

Flow diagram for HTTP directory URL construction

flowchart LR
    A[Directory URL with query token] --> B[Split URL]
    B --> C[Quote file name for path]
    C --> D[Append escaped name to path]
    D --> E[Reassemble URL with query]
    E --> F[Upload file to its own URL]
Loading

File-Level Changes

Change Details Files
Upload HTTP(S) files as exact bytes with deterministic non-chunked request sizing.
  • Open non-empty files in binary mode and stream the file object to requests.
  • Send empty files as b'' so requests emits Content-Length: 0 instead of chunked encoding.
  • Add coverage for binary, UTF-8, CRLF, empty-file, content-length, and transfer-encoding behavior.
src/tesk_core/filer.py
tests/test_filer_http_pytest.py
Construct directory-upload URLs by escaping file names in the path while preserving query parameters.
  • Add http_join using URL parsing and component-wise quoting.
  • Use the helper for every directory file, including nested paths.
  • Test reserved characters, percent signs, spaces, nested files, and upload query tokens against a local HTTP server.
src/tesk_core/filer.py
tests/test_filer_http_pytest.py

Assessment against linked issues

Issue Objective Addressed Explanation
elixir-cloud-aai/TESK#215 Upload HTTP(S) output files byte-for-byte, including binary files and text with non-ASCII characters or CRLF line endings, while streaming file contents rather than loading them into memory. ✅
elixir-cloud-aai/TESK#215 Send empty HTTP(S) output files with a content length rather than chunked encoding so presigned upload URLs can accept them. ✅

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/tesk_core/filer.py" line_range="30" />
<code_context>
+    so characters such as # and ? stay part of it, and the URL's query, which
+    may carry a token, is kept.'''
+    parts = urlsplit(url)
+    path = parts.path.rstrip('/') + '/' + quote(name, safe='')
+    return urlunsplit(parts._replace(path=path))
+
</code_context>
<issue_to_address>
**Non-UTF-8 filenames abort uploads**

When a directory contains a filename with non-UTF-8 bytes on a POSIX filesystem, `quote(name, safe='')` uses strict UTF-8 encoding, so a POSIX filename represented by `os.listdir` with surrogate escapes raises `UnicodeEncodeError` while `upload_dir` builds its upload list; the directory upload aborts instead of uploading that file.

Encode filesystem names with `os.fsencode` and percent-encode those bytes, or otherwise handle surrogate-escaped names before quoting.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the byte handling or URL construction is wrong, a PUT could leave incorrect content at a remote object or store it under the wrong name; reverting cannot undo a completed upload, though uploading the corrected file can usually repair it.

Blocking findings: src/tesk_core/filer.py:30


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/tesk_core/filer.py Resolved
@anuragxxd
anuragxxd requested a review from uniqueg October 23, 2026 20:59
os.listdir returns a name that isn't valid UTF-8 with surrogate escapes,
and quote encodes a string as strict UTF-8, so http_join raised
UnicodeEncodeError and the whole directory upload stopped. Before
http_join, such a file was uploaded under a mangled name.

http_join now quotes the bytes of the name from os.fsencode, so the URL
carries the name as it is on disk.

Found by Sourcery's review.
@uniqueg
uniqueg merged commit 17ab19b into master Oct 23, 2026
1 of 7 checks passed
@uniqueg

uniqueg commented Oct 23, 2026

Copy link
Copy Markdown
Member

Merged as (at least most) linting issues are clearly not from this PR.

@uniqueg
uniqueg deleted the fix/http-upload-bytes branch November 6, 2026 01:44
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.

fix(filer): HTTP(S) uploads read outputs in text mode, so binary files fail and some text is altered

2 participants