From a9248baee0704973a77a88e00b961c2441c897e1 Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Thu, 26 Nov 2026 01:42:24 +0530 Subject: [PATCH 1/2] Core: Extract REST SigV4 signing into a dedicated module Move SigV4Adapter, its constants, and the initialization helper out of RestCatalog._init_sigv4. Re-export the existing public names from catalog.rest for compatibility. Part of #3410; signing and retry fixes remain separate. --- pyiceberg/catalog/rest/__init__.py | 99 ++++++++---------------------- pyiceberg/catalog/rest/sigv4.py | 96 +++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 75 deletions(-) create mode 100644 pyiceberg/catalog/rest/sigv4.py diff --git a/pyiceberg/catalog/rest/__init__.py b/pyiceberg/catalog/rest/__init__.py index 2ba7a00ebf..f10839df81 100644 --- a/pyiceberg/catalog/rest/__init__.py +++ b/pyiceberg/catalog/rest/__init__.py @@ -16,7 +16,6 @@ # under the License. from __future__ import annotations -import hashlib import logging import os import platform @@ -40,7 +39,7 @@ from urllib3.util.retry import Retry from pyiceberg import __version__ -from pyiceberg.catalog import BOTOCORE_SESSION, TOKEN, URI, WAREHOUSE_LOCATION, Catalog, PropertiesUpdateSummary +from pyiceberg.catalog import TOKEN, URI, WAREHOUSE_LOCATION, Catalog, PropertiesUpdateSummary from pyiceberg.catalog.rest.auth import AUTH_MANAGER, AuthManager, AuthManagerAdapter, AuthManagerFactory, LegacyOAuth2AuthManager from pyiceberg.catalog.rest.response import _handle_non_200_response from pyiceberg.catalog.rest.scan_planning import ( @@ -55,6 +54,27 @@ ScanTasks, StorageCredential, ) +from pyiceberg.catalog.rest.sigv4 import ( + EMPTY_BODY_SHA256 as EMPTY_BODY_SHA256, +) +from pyiceberg.catalog.rest.sigv4 import ( + SIGV4_MAX_RETRIES as SIGV4_MAX_RETRIES, +) +from pyiceberg.catalog.rest.sigv4 import ( + SIGV4_MAX_RETRIES_DEFAULT as SIGV4_MAX_RETRIES_DEFAULT, +) +from pyiceberg.catalog.rest.sigv4 import ( + SIGV4_REGION as SIGV4_REGION, +) +from pyiceberg.catalog.rest.sigv4 import ( + SIGV4_SERVICE as SIGV4_SERVICE, +) +from pyiceberg.catalog.rest.sigv4 import ( + SigV4Adapter as SigV4Adapter, +) +from pyiceberg.catalog.rest.sigv4 import ( + init_sigv4, +) from pyiceberg.exceptions import ( AuthorizationExpiredError, CommitFailedException, @@ -74,11 +94,6 @@ ) from pyiceberg.expressions import AlwaysTrue, BooleanExpression from pyiceberg.io import ( - AWS_ACCESS_KEY_ID, - AWS_PROFILE_NAME, - AWS_REGION, - AWS_SECRET_ACCESS_KEY, - AWS_SESSION_TOKEN, S3_REMOTE_SIGNING_ENABLED, S3_SIGNER, FileIO, @@ -107,7 +122,6 @@ from pyiceberg.types import transform_dict_value_to_str from pyiceberg.utils.deprecated import deprecation_message from pyiceberg.utils.properties import ( - get_first_property_value, get_header_properties, property_as_bool, property_as_float, @@ -295,10 +309,6 @@ class ScanPlanningMode(Enum): CA_BUNDLE = "cabundle" SSL = "ssl" SIGV4 = "rest.sigv4-enabled" -SIGV4_REGION = "rest.signing-region" -SIGV4_SERVICE = "rest.signing-name" -SIGV4_MAX_RETRIES = "rest.sigv4.max-retries" -SIGV4_MAX_RETRIES_DEFAULT = 10 REST_CLIENT_CONNECTION_TIMEOUT_MS = "rest.client.connection-timeout-ms" REST_CLIENT_SOCKET_TIMEOUT_MS = "rest.client.socket-timeout-ms" REST_CLIENT_MAX_RETRIES = "rest.client.max-retries" @@ -308,7 +318,7 @@ class ScanPlanningMode(Enum): _CONNECTION_RETRY_STATUS_FORCELIST = (429, 500, 502, 503, 504) _CONNECTION_RETRY_ALLOWED_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}) IDEMPOTENCY_KEY_HEADER = "Idempotency-Key" -EMPTY_BODY_SHA256: str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + OAUTH2_SERVER_URI = "oauth2-server-uri" SNAPSHOT_LOADING_MODE = "snapshot-loading-mode" AUTH = "auth" @@ -641,7 +651,7 @@ def _create_session(self) -> Session: # Configure SigV4 Request Signing if property_as_bool(self.properties, SIGV4, False): - self._init_sigv4(session) + init_sigv4(session, self.uri, self.properties) return session @@ -1129,67 +1139,6 @@ def _split_identifier_for_json(self, identifier: str | Identifier) -> dict[str, identifier_tuple = self._identifier_to_validated_tuple(identifier) return {"namespace": identifier_tuple[:-1], "name": identifier_tuple[-1]} - def _init_sigv4(self, session: Session) -> None: - from urllib import parse - - import boto3 - from botocore.auth import SigV4Auth - from botocore.awsrequest import AWSRequest - - class SigV4Adapter(HTTPAdapter): - def __init__(self, **properties: str): - self._properties = properties - max_retries = property_as_int(self._properties, SIGV4_MAX_RETRIES, SIGV4_MAX_RETRIES_DEFAULT) - super().__init__(max_retries=max_retries) - self._boto_session = boto3.Session( - profile_name=get_first_property_value(self._properties, AWS_PROFILE_NAME), - region_name=get_first_property_value(self._properties, AWS_REGION), - botocore_session=self._properties.get(BOTOCORE_SESSION), - aws_access_key_id=get_first_property_value(self._properties, AWS_ACCESS_KEY_ID), - aws_secret_access_key=get_first_property_value(self._properties, AWS_SECRET_ACCESS_KEY), - aws_session_token=get_first_property_value(self._properties, AWS_SESSION_TOKEN), - ) - - def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: # pylint: disable=W0613 - credentials = self._boto_session.get_credentials().get_frozen_credentials() - region = self._properties.get(SIGV4_REGION, self._boto_session.region_name) - service = self._properties.get(SIGV4_SERVICE, "execute-api") - - url = str(request.url).split("?")[0] - query = str(parse.urlsplit(request.url).query) - params = dict(parse.parse_qsl(query, keep_blank_values=True)) - - # remove the connection header as it will be updated after signing - if "connection" in request.headers: - del request.headers["connection"] - # 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) - ) - - SigV4Auth(credentials, service, region).add_auth(aws_request) - original_header = request.headers - signed_headers = aws_request.headers - relocated_headers = {} - - # relocate headers if there is a conflict with signed headers - for header, value in original_header.items(): - if header in signed_headers and signed_headers[header] != value: - relocated_headers[f"Original-{header}"] = value - - request.headers.update(relocated_headers) - request.headers.update(signed_headers) - - session.mount(self.uri, SigV4Adapter(**self.properties)) - def _response_to_table(self, identifier_tuple: tuple[str, ...], table_response: TableResponse) -> Table: # Per Iceberg spec: storage-credentials take precedence over config credential_config = self._resolve_storage_credentials( diff --git a/pyiceberg/catalog/rest/sigv4.py b/pyiceberg/catalog/rest/sigv4.py new file mode 100644 index 0000000000..df8d1b02fe --- /dev/null +++ b/pyiceberg/catalog/rest/sigv4.py @@ -0,0 +1,96 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +from typing import Any +from urllib import parse + +from requests import PreparedRequest, Session +from requests.adapters import HTTPAdapter + +from pyiceberg.catalog import BOTOCORE_SESSION +from pyiceberg.io import ( + AWS_ACCESS_KEY_ID, + AWS_PROFILE_NAME, + AWS_REGION, + AWS_SECRET_ACCESS_KEY, + AWS_SESSION_TOKEN, +) +from pyiceberg.typedef import Properties +from pyiceberg.utils.properties import get_first_property_value, property_as_int + +SIGV4_REGION = "rest.signing-region" +SIGV4_SERVICE = "rest.signing-name" +SIGV4_MAX_RETRIES = "rest.sigv4.max-retries" +SIGV4_MAX_RETRIES_DEFAULT = 10 +EMPTY_BODY_SHA256: str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + + +class SigV4Adapter(HTTPAdapter): + """HTTP adapter that signs REST requests with AWS Signature Version 4.""" + + def __init__(self, **properties: str) -> None: + import boto3 + + self._properties = properties + max_retries = property_as_int(self._properties, SIGV4_MAX_RETRIES, SIGV4_MAX_RETRIES_DEFAULT) + super().__init__(max_retries=max_retries) + self._boto_session = boto3.Session( + profile_name=get_first_property_value(self._properties, AWS_PROFILE_NAME), + region_name=get_first_property_value(self._properties, AWS_REGION), + botocore_session=self._properties.get(BOTOCORE_SESSION), + aws_access_key_id=get_first_property_value(self._properties, AWS_ACCESS_KEY_ID), + aws_secret_access_key=get_first_property_value(self._properties, AWS_SECRET_ACCESS_KEY), + aws_session_token=get_first_property_value(self._properties, AWS_SESSION_TOKEN), + ) + + def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + + credentials = self._boto_session.get_credentials().get_frozen_credentials() + region = self._properties.get(SIGV4_REGION, self._boto_session.region_name) + service = self._properties.get(SIGV4_SERVICE, "execute-api") + + url = str(request.url).split("?")[0] + query = str(parse.urlsplit(request.url).query) + params = dict(parse.parse_qsl(query)) + + if "connection" in request.headers: + del request.headers["connection"] + if not request.body: + request.headers["x-amz-content-sha256"] = EMPTY_BODY_SHA256 + + aws_request = AWSRequest(method=request.method, url=url, params=params, data=request.body, headers=dict(request.headers)) + + SigV4Auth(credentials, service, region).add_auth(aws_request) + original_header = request.headers + signed_headers = aws_request.headers + relocated_headers = {} + + for header, value in original_header.items(): + if header in signed_headers and signed_headers[header] != value: + relocated_headers[f"Original-{header}"] = value + + request.headers.update(relocated_headers) + request.headers.update(signed_headers) + + +def init_sigv4(session: Session, uri: str, properties: Properties) -> None: + """Mount the SigV4 adapter on a requests session for the catalog URI.""" + session.mount(uri, SigV4Adapter(**properties)) From c29ef34b294952c0ef1fbc02d4cb6f316f988ddd Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Sat, 5 Dec 2026 17:17:35 +0530 Subject: [PATCH 2/2] Keep SigV4 helpers private and retain the constants re-exports SigV4Adapter and init_sigv4 were private before the move, so expose them as _SigV4Adapter and _init_sigv4. Keep SIGV4_REGION, SIGV4_SERVICE, SIGV4_MAX_RETRIES, SIGV4_MAX_RETRIES_DEFAULT and EMPTY_BODY_SHA256 importable from pyiceberg.catalog.rest, as they were before the extraction. Carry over the request-body content hash and the blank query parameter handling from main so the module keeps the behavior it had before the move. --- pyiceberg/catalog/rest/__init__.py | 7 ++----- pyiceberg/catalog/rest/sigv4.py | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/pyiceberg/catalog/rest/__init__.py b/pyiceberg/catalog/rest/__init__.py index f10839df81..60f8b27776 100644 --- a/pyiceberg/catalog/rest/__init__.py +++ b/pyiceberg/catalog/rest/__init__.py @@ -70,10 +70,7 @@ SIGV4_SERVICE as SIGV4_SERVICE, ) from pyiceberg.catalog.rest.sigv4 import ( - SigV4Adapter as SigV4Adapter, -) -from pyiceberg.catalog.rest.sigv4 import ( - init_sigv4, + _init_sigv4, ) from pyiceberg.exceptions import ( AuthorizationExpiredError, @@ -651,7 +648,7 @@ def _create_session(self) -> Session: # Configure SigV4 Request Signing if property_as_bool(self.properties, SIGV4, False): - init_sigv4(session, self.uri, self.properties) + _init_sigv4(session, self.uri, self.properties) return session diff --git a/pyiceberg/catalog/rest/sigv4.py b/pyiceberg/catalog/rest/sigv4.py index df8d1b02fe..baefef0ad0 100644 --- a/pyiceberg/catalog/rest/sigv4.py +++ b/pyiceberg/catalog/rest/sigv4.py @@ -17,6 +17,7 @@ from __future__ import annotations +import hashlib from typing import Any from urllib import parse @@ -41,7 +42,7 @@ EMPTY_BODY_SHA256: str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" -class SigV4Adapter(HTTPAdapter): +class _SigV4Adapter(HTTPAdapter): """HTTP adapter that signs REST requests with AWS Signature Version 4.""" def __init__(self, **properties: str) -> None: @@ -69,12 +70,19 @@ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: url = str(request.url).split("?")[0] query = str(parse.urlsplit(request.url).query) - params = dict(parse.parse_qsl(query)) + params = dict(parse.parse_qsl(query, keep_blank_values=True)) + # remove the connection header as it will be updated after signing if "connection" in request.headers: del request.headers["connection"] + # 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)) @@ -83,6 +91,7 @@ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: signed_headers = aws_request.headers relocated_headers = {} + # relocate headers if there is a conflict with signed headers for header, value in original_header.items(): if header in signed_headers and signed_headers[header] != value: relocated_headers[f"Original-{header}"] = value @@ -91,6 +100,6 @@ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: request.headers.update(signed_headers) -def init_sigv4(session: Session, uri: str, properties: Properties) -> None: +def _init_sigv4(session: Session, uri: str, properties: Properties) -> None: """Mount the SigV4 adapter on a requests session for the catalog URI.""" - session.mount(uri, SigV4Adapter(**properties)) + session.mount(uri, _SigV4Adapter(**properties))