Repository navigation
Upload HTTP(S) outputs as bytes and escape names in directory uploads - #61
Conversation
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.
Reviewer's GuideFixes 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 uploadsequenceDiagram
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
Sequence diagram for escaped HTTP directory uploadsequenceDiagram
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
Flow diagram for HTTP directory URL constructionflowchart 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]
File-Level Changes
Assessment against linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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
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.
|
Merged as (at least most) linting issues are clearly not from this PR. |
Fixes elixir-cloud-aai/TESK#215. That issue is filed in TESK, but the filer image is built from this repo.
HTTPTransputhad 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_fileopened the file in text mode, so:UnicodeDecodeErrorand weren't uploaded;masterpins 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-Lengthfrom its size. An empty file is sent asb'', 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_dirappended each name to the URL as a plain string.result#1.txtwas uploaded asresultanda?b.txtasa, 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:
Content-Lengthand without chunked encoding;http_joinescapes#,?and%and keeps the query;test_upload_dirnow reads the file object it's given. Onmaster, the gzip, CRLF and directory tests fail.With Python 3.12 on Linux: 83 passed, 1 failed. The failure,
test_ftp_upload_dir, fails onmastertoo with the current test dependencies (pytest 9.1.1, pyftpdlib 2.2.0), so it's unrelated.End to end, I uploaded with
HTTPTransputthrough a small server that answers each PUT with a 307 to a fresh MinIO presigned URL:masterUnicodeDecodeError, not uploadedresult#1.txt,result#2.txt,a?b.txt,50%25.txt,a b.txt,sub/y.txt) with?token=abcin its URLupload_dirreturned 0, yet all 6 PUTs went to the keydir, leaving one object, and the server saw queries such astoken=abc/resulttoken=abcTo reach deployments
The TESK chart pins
tesk-core-filer:v0.10.2incharts/tesk/values.yaml, so this needs a new tag here and a chart bump. TESK'ssource/tesk-corehas the same code; I can mirror the change there if that copy is still used.Noticed, not changed
upload_filereturns 0 while nothing, or an empty object, is stored. Following only 307 and 308 for uploads would fix it.download_fileholds the whole response in memory (req.content).stream=Truewithiter_contentwould 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:
Enhancements:
Tests: