From 3920cbe0df066f69a9d3e10143f65566966b1d29 Mon Sep 17 00:00:00 2001 From: Utkarsh patwa Date: Mon, 23 Nov 2026 14:14:31 +0530 Subject: [PATCH] fix(streaming): reject negative SEEK_SET offset and clamp negative relative seek Closes #8885 S3Object is documented as a seekable, file-like object, but seek() previously accepted negative offsets for io.SEEK_SET, storing a negative position and causing subsequent read() calls to issue a malformed HTTP Range header (e.g. 'bytes=-5-'). In addition, negative relative seeks (io.SEEK_CUR and io.SEEK_END) that landed before the beginning of the object were not clamped. Following Python file-like semantics (io.BytesIO): - Raises ValueError for negative seek values when whence is io.SEEK_SET. - Clamps position to 0 for io.SEEK_CUR and io.SEEK_END. Signed-off-by: Utkarsh patwa --- .../utilities/streaming/_s3_seekable_io.py | 6 ++++-- .../streaming/_boto3/test_s3_seekable_io.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/aws_lambda_powertools/utilities/streaming/_s3_seekable_io.py b/aws_lambda_powertools/utilities/streaming/_s3_seekable_io.py index c3773e80d47..8d46a23c103 100644 --- a/aws_lambda_powertools/utilities/streaming/_s3_seekable_io.py +++ b/aws_lambda_powertools/utilities/streaming/_s3_seekable_io.py @@ -124,11 +124,13 @@ def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: current_position = self._position if whence == io.SEEK_SET: + if offset < 0: + raise ValueError(f"negative seek value {offset}") self._position = offset elif whence == io.SEEK_CUR: - self._position += offset + self._position = max(0, self._position + offset) elif whence == io.SEEK_END: - self._position = self.size + offset + self._position = max(0, self.size + offset) else: raise ValueError(f"invalid whence ({whence}, should be {io.SEEK_SET}, {io.SEEK_CUR}, {io.SEEK_END})") diff --git a/tests/functional/streaming/_boto3/test_s3_seekable_io.py b/tests/functional/streaming/_boto3/test_s3_seekable_io.py index abf1e593bcc..9ad7ae3457c 100644 --- a/tests/functional/streaming/_boto3/test_s3_seekable_io.py +++ b/tests/functional/streaming/_boto3/test_s3_seekable_io.py @@ -63,6 +63,23 @@ def test_seek_end(s3_seekable_obj, s3_client_stub): assert s3_seekable_obj.tell() == 1000 +def test_seek_set_negative_raises(s3_seekable_obj): + with pytest.raises(ValueError, match="negative seek value -5"): + s3_seekable_obj.seek(-5, io.SEEK_SET) + + +def test_seek_cur_negative_clamps_to_zero(s3_seekable_obj): + s3_seekable_obj.seek(10, io.SEEK_SET) + assert s3_seekable_obj.seek(-20, io.SEEK_CUR) == 0 + assert s3_seekable_obj.tell() == 0 + + +def test_seek_end_negative_clamps_to_zero(s3_seekable_obj, s3_client_stub): + s3_client_stub.add_response("head_object", {"ContentLength": 10}) + assert s3_seekable_obj.seek(-20, io.SEEK_END) == 0 + assert s3_seekable_obj.tell() == 0 + + def test_size(s3_seekable_obj, s3_client_stub): s3_client_stub.add_response("head_object", {"ContentLength": 1000})