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})