Skip to content

Commit 7210084

Browse files
badGarnetclaude
andcommitted
fix: harden the NDJSON elements-file path
Two defects found in review of the elements-file mode. The elements-file marker was an `x-unstructured-elements-file` response header, and any response carrying it was trusted as an SDK-created path. Headers come off the wire, so a server could name an arbitrary local file -- and callers are documented to open `elements_file` and then delete it, making this an arbitrary-file delete rather than just a disclosure. The marker is now an httpx response extension, which is populated by the transport and cannot be set remotely; a real server body is always copied to a file this client creates. Recombination also wrote straight to its final UUID path while recording that path only on success, so a malformed chunk left a partial file behind under a name nothing owned -- the combined file is deliberately outside the operation's TemporaryDirectory, so nothing else cleaned it up. It now writes to a staging file renamed into place atomically, and unlinks it on any exception. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent fce575a commit 7210084

4 files changed

Lines changed: 83 additions & 15 deletions

File tree

‎_test_unstructured_client/unit/test_ndjson_elements_file.py‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,13 @@
1818
import httpx
1919

2020
from unstructured_client._hooks.custom.request_utils import (
21-
ELEMENTS_FILE_HEADER,
21+
ELEMENTS_FILE_EXTENSION_KEY,
2222
combine_chunk_files_to_ndjson,
2323
create_elements_file_response,
2424
write_chunk_body_to_temp,
2525
)
2626
from unstructured_client._hooks.custom.split_pdf_hook import SplitPdfHook
27+
from unstructured_client.general import _ndjson_elements_file
2728

2829

2930
def _elements(prefix, count):
@@ -205,17 +206,43 @@ def test_spilled_body_is_released_from_the_response(tmp_path):
205206
assert len(response.content) < 512
206207

207208

208-
def test_elements_file_response_carries_path_in_header_and_body(tmp_path):
209+
def test_elements_file_response_carries_path_in_extension_and_body(tmp_path):
209210
path = str(tmp_path / "combined.ndjson")
210211
response = create_elements_file_response(path)
211212

212213
assert response.status_code == 200
213-
assert response.headers[ELEMENTS_FILE_HEADER] == path
214+
assert response.extensions[ELEMENTS_FILE_EXTENSION_KEY] == path
214215
assert response.headers["Content-Type"] == "application/x-ndjson"
215216
# Body-as-path mirrors the existing cached-chunk convention in the split hook.
216217
assert response.text == path
217218

218219

220+
def test_server_cannot_name_a_local_file_via_a_response_header(tmp_path):
221+
"""The elements-file marker must not be reachable from the wire.
222+
223+
Callers are documented to open `elements_file` and then delete it, so trusting a
224+
server-supplied path would hand a hostile server an arbitrary local file to destroy.
225+
A header must be ignored and the body copied to a file this client created.
226+
"""
227+
victim = tmp_path / "victim"
228+
victim.write_text("do not touch", encoding="utf-8")
229+
response = httpx.Response(
230+
200,
231+
headers={
232+
"content-type": "application/x-ndjson",
233+
"x-unstructured-elements-file": str(victim),
234+
},
235+
content=b'{"safe": true}\n',
236+
)
237+
238+
resolved = _ndjson_elements_file(response)
239+
240+
assert resolved != str(victim)
241+
assert victim.read_text(encoding="utf-8") == "do not touch"
242+
assert _read_ndjson(resolved) == [{"safe": True}]
243+
os.unlink(resolved)
244+
245+
219246
# --- hook-level temp-file lifecycle ------------------------------------------------
220247

221248

@@ -282,7 +309,7 @@ def test_combined_file_is_returned_on_success(tmp_path):
282309
)
283310
response = hook._build_after_success_response(operation_id, httpx.Response(200), [])
284311

285-
combined = response.headers[ELEMENTS_FILE_HEADER]
312+
combined = response.extensions[ELEMENTS_FILE_EXTENSION_KEY]
286313
assert os.path.exists(combined)
287314
assert _read_ndjson(combined) == elements
288315

@@ -311,6 +338,25 @@ def test_combined_file_is_discarded_when_a_failure_response_is_returned(tmp_path
311338
assert _ndjson_files_in(tmp_path) == []
312339

313340

341+
def test_malformed_chunk_leaves_no_partial_output_behind(tmp_path):
342+
"""Regression guard: recombination that raises must not orphan a partial file.
343+
344+
The combined file is the one artifact here that no temp directory owns, so a partial
345+
one would outlive the failed operation.
346+
"""
347+
operation_id = "op-malformed"
348+
hook = _hook_in_ndjson_mode(operation_id, tmp_path)
349+
350+
with pytest.raises(json.JSONDecodeError):
351+
hook._elements_from_task_responses(
352+
operation_id, [(0, httpx.Response(200, content=b"[not-json"))], started_at=0.0
353+
)
354+
355+
assert operation_id not in hook.ndjson_output_path
356+
assert _ndjson_files_in(tmp_path) == []
357+
assert list(Path(tmp_path).glob("*.partial")) == []
358+
359+
314360
def test_no_combined_file_is_created_when_every_chunk_failed(tmp_path):
315361
operation_id = "op-all-failed"
316362
hook = _hook_in_ndjson_mode(operation_id, tmp_path)

‎src/unstructured_client/_hooks/custom/request_utils.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,12 @@ def create_response(elements: list) -> httpx.Response:
279279
return response
280280

281281

282-
ELEMENTS_FILE_HEADER = "x-unstructured-elements-file"
282+
# Marks a response this client synthesized, whose body is a path to a local file rather
283+
# than elements. It is deliberately an httpx extension and NOT a response header: a
284+
# header is wire-controlled, so a server could name any local path and have the SDK hand
285+
# it to the caller, who then opens and (per the documented usage) deletes it. Extensions
286+
# are populated by the transport, so a remote server cannot set this key.
287+
ELEMENTS_FILE_EXTENSION_KEY = "unstructured_elements_file"
283288
NDJSON_MEDIA_TYPE = "application/x-ndjson"
284289

285290
_SNIFF_BLOCK_SIZE = 64
@@ -364,8 +369,9 @@ def create_elements_file_response(elements_file: str) -> httpx.Response:
364369
"""Create a synthetic 200 response whose payload is a path to an NDJSON file.
365370
366371
Mirrors the split hook's existing convention of a cached chunk response carrying its
367-
temp-file path as the body. The path is also set as a header so the SDK can tell this
368-
apart from a real NDJSON body streamed from the server.
372+
temp-file path as the body. The path is also recorded in `ELEMENTS_FILE_EXTENSION_KEY`
373+
so the SDK can tell this apart from a real NDJSON body streamed from the server
374+
without trusting anything that came off the wire.
369375
370376
Args:
371377
elements_file: Path to the combined NDJSON file of elements.
@@ -379,8 +385,8 @@ def create_elements_file_response(elements_file: str) -> httpx.Response:
379385
headers={
380386
"Content-Type": NDJSON_MEDIA_TYPE,
381387
"Content-Length": str(len(content)),
382-
ELEMENTS_FILE_HEADER: elements_file,
383388
},
389+
extensions={ELEMENTS_FILE_EXTENSION_KEY: elements_file},
384390
)
385391
setattr(response, "_content", content)
386392
return response

‎src/unstructured_client/_hooks/custom/split_pdf_hook.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1510,10 +1510,23 @@ def _combine_chunks_to_ndjson(self, operation_id: str, chunk_paths: list[str]) -
15101510
after_success returns, which would delete the file before the caller could read
15111511
it. The combined file therefore outlives the operation and the caller owns
15121512
deleting it (see `PartitionResponse.elements_file`).
1513+
1514+
Recombination writes to a staging file that is renamed into place only once it
1515+
completes. A malformed chunk makes the parse raise partway through, and since the
1516+
combined file is the one thing here nothing else owns, a partial one would survive
1517+
the failed operation as an orphan under the final name.
15131518
"""
15141519
temp_dir_path = self.cache_tmp_data_dir.get(operation_id) or tempfile.gettempdir()
15151520
out_path = f"{temp_dir_path}/{uuid.uuid4()}.ndjson"
1516-
written = request_utils.combine_chunk_files_to_ndjson(chunk_paths, out_path)
1521+
fd, staging_path = tempfile.mkstemp(suffix=".ndjson.partial", dir=temp_dir_path)
1522+
os.close(fd)
1523+
try:
1524+
written = request_utils.combine_chunk_files_to_ndjson(chunk_paths, staging_path)
1525+
# Same directory, so this is atomic; the caller never sees a partial file.
1526+
os.replace(staging_path, out_path)
1527+
except BaseException:
1528+
_unlink_quietly([staging_path])
1529+
raise
15171530
self.ndjson_output_path[operation_id] = out_path
15181531
logger.info(
15191532
"split_pdf event=ndjson_combined operation_id=%s chunk_count=%d element_count=%d out_file=%s",

‎src/unstructured_client/general.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from unstructured_client.models import errors, operations, shared
1111
from unstructured_client.types import BaseModel, OptionalNullable, UNSET
1212
from unstructured_client._hooks.custom.clean_server_url_hook import clean_server_url
13-
from unstructured_client._hooks.custom.request_utils import ELEMENTS_FILE_HEADER
13+
from unstructured_client._hooks.custom.request_utils import ELEMENTS_FILE_EXTENSION_KEY
1414
from unstructured_client.utils.unmarshal_json_response import unmarshal_json_response
1515

1616

@@ -35,11 +35,14 @@ def _ndjson_elements_file(http_res: httpx.Response) -> str:
3535
"""Resolve an NDJSON response to a path on disk, without parsing the elements.
3636
3737
When the split-PDF hook ran it has already combined the per-chunk temp files into one
38-
NDJSON file and passes the path through `ELEMENTS_FILE_HEADER`, so there is nothing to
39-
do but read the header. Otherwise this is a real body from the server, which is
40-
streamed to a temp file.
38+
NDJSON file and records the path in `ELEMENTS_FILE_EXTENSION_KEY`. Otherwise this is a
39+
real body from the server, which is written to a temp file we create.
40+
41+
Only the extension is trusted. A path taken from a response header would be
42+
server-controlled, letting a hostile server name any local file for the caller to open
43+
and then delete.
4144
"""
42-
existing_path = http_res.headers.get(ELEMENTS_FILE_HEADER)
45+
existing_path = http_res.extensions.get(ELEMENTS_FILE_EXTENSION_KEY)
4346
if existing_path:
4447
return existing_path
4548

@@ -51,7 +54,7 @@ def _ndjson_elements_file(http_res: httpx.Response) -> str:
5154

5255
async def _ndjson_elements_file_async(http_res: httpx.Response) -> str:
5356
"""Async counterpart of `_ndjson_elements_file`."""
54-
existing_path = http_res.headers.get(ELEMENTS_FILE_HEADER)
57+
existing_path = http_res.extensions.get(ELEMENTS_FILE_EXTENSION_KEY)
5558
if existing_path:
5659
return existing_path
5760

0 commit comments

Comments
 (0)