Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pyiceberg/catalog/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations

import hashlib
import logging
import os
import platform
Expand Down Expand Up @@ -1161,9 +1162,14 @@ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: # pylin
# remove the connection header as it will be updated after signing
if "connection" in request.headers:
del request.headers["connection"]
# For empty bodies, explicitly set the content hash header to the SHA256 of an empty string
# Send x-amz-content-sha256 on every request (Iceberg Java does too): some SigV4
# servers reject requests without it. botocore signs this header's value as the
# payload hash, so it must be the hex SHA256 of the body.
if not request.body:
request.headers["x-amz-content-sha256"] = EMPTY_BODY_SHA256
else:
body = request.body.encode("utf-8") if isinstance(request.body, str) else request.body
request.headers["x-amz-content-sha256"] = hashlib.sha256(body).hexdigest()

aws_request = AWSRequest(
method=request.method, url=url, params=params, data=request.body, headers=dict(request.headers)
Expand Down
43 changes: 42 additions & 1 deletion tests/catalog/test_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from __future__ import annotations

import base64
import hashlib
import os
import pickle
import platform
Expand Down Expand Up @@ -729,7 +730,47 @@ def test_sigv4_sign_request_with_body(rest_mock: Mocker) -> None:

assert prepared.headers["Authorization"].startswith("AWS4-HMAC-SHA256")
assert prepared.headers["Original-Authorization"] == f"Bearer {existing_token}"
assert prepared.headers.get("x-amz-content-sha256") != EMPTY_BODY_SHA256
assert isinstance(prepared.body, str)
assert prepared.headers["x-amz-content-sha256"] == hashlib.sha256(prepared.body.encode("utf-8")).hexdigest()


@pytest.mark.parametrize(
"request_kwargs",
[
pytest.param({"json": {"namespace": ["ns"]}}, id="bytes-body"),
pytest.param({"data": {"namespace": "ns"}}, id="str-body"),
pytest.param({}, id="empty-body"),
],
)
def test_sigv4_content_sha256_header_is_the_signed_payload_hash(rest_mock: Mocker, request_kwargs: dict[str, Any]) -> None:
from botocore.auth import SigV4Auth
from botocore.credentials import Credentials

catalog = RestCatalog(
"rest",
**{
"uri": TEST_URI,
"token": TEST_TOKEN,
"rest.sigv4-enabled": "true",
"rest.signing-region": "us-west-2",
"client.access-key-id": "id",
"client.secret-access-key": "secret",
},
)

prepared = catalog._session.prepare_request(Request("POST", f"{TEST_URI}v1/namespaces", **request_kwargs))
adapter = catalog._session.adapters[catalog.uri]
assert isinstance(adapter, HTTPAdapter)
with mock.patch("botocore.auth.SigV4Auth.add_auth", autospec=True) as add_auth:
adapter.add_headers(prepared)

# The header must equal the SHA256 botocore computes from the body, which is the
# payload hash in the canonical request that gets signed.
signed_request = add_auth.call_args.args[1]
signer = SigV4Auth(Credentials("id", "secret"), "execute-api", "us-west-2")
content_sha256 = prepared.headers["x-amz-content-sha256"]
assert content_sha256 == signer.payload(signed_request)
assert signer.canonical_request(signed_request).splitlines()[-1] == content_sha256


def test_sigv4_sign_request_keeps_blank_query_params(rest_mock: Mocker) -> None:
Expand Down