diff --git a/pyiceberg/catalog/rest/__init__.py b/pyiceberg/catalog/rest/__init__.py index 4f9a6230ae..6fc1feb900 100644 --- a/pyiceberg/catalog/rest/__init__.py +++ b/pyiceberg/catalog/rest/__init__.py @@ -78,6 +78,8 @@ AWS_REGION, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, + S3_REQUEST_SIGNER, + S3_SIGNER, FileIO, load_file_io, ) @@ -678,6 +680,10 @@ def _load_file_io( merged_properties = {**table_properties, **self.properties, **properties} if self._auth_manager: merged_properties[AUTH_MANAGER] = self._auth_manager + if merged_properties.get(S3_SIGNER): + from pyiceberg.io.signer import create_s3_request_signer + + merged_properties[S3_REQUEST_SIGNER] = create_s3_request_signer(merged_properties) return load_file_io(merged_properties, location) def _effective_scan_planning_mode(self, table_config: Properties) -> ScanPlanningMode: diff --git a/pyiceberg/io/__init__.py b/pyiceberg/io/__init__.py index e433ed88a5..e1fa1bc3f3 100644 --- a/pyiceberg/io/__init__.py +++ b/pyiceberg/io/__init__.py @@ -76,6 +76,7 @@ def _is_local_path(path: str) -> bool: S3_CONNECT_TIMEOUT = "s3.connect-timeout" S3_REQUEST_TIMEOUT = "s3.request-timeout" S3_SIGNER = "s3.signer" +S3_REQUEST_SIGNER = "s3.request-signer" S3_SIGNER_URI = "s3.signer.uri" S3_SIGNER_ENDPOINT = "s3.signer.endpoint" S3_SIGNER_ENDPOINT_DEFAULT = "v1/aws/s3/sign" diff --git a/pyiceberg/io/fsspec.py b/pyiceberg/io/fsspec.py index 505b5eebbf..7022fc0e20 100644 --- a/pyiceberg/io/fsspec.py +++ b/pyiceberg/io/fsspec.py @@ -16,7 +16,6 @@ # under the License. """FileIO implementation for reading and writing table files that uses fsspec compatible filesystems.""" -import abc import errno import json import logging @@ -24,22 +23,13 @@ import threading from collections.abc import Callable from functools import lru_cache -from typing import ( - TYPE_CHECKING, - Any, -) +from typing import Any from urllib.parse import ParseResult, urlparse -import requests from fsspec import AbstractFileSystem from fsspec.implementations.local import LocalFileSystem -from requests import HTTPError from typing_extensions import override -from pyiceberg.catalog import TOKEN, URI -from pyiceberg.catalog.rest import _user_agent -from pyiceberg.catalog.rest.auth import AUTH_MANAGER -from pyiceberg.exceptions import SignError from pyiceberg.io import ( ADLS_ACCOUNT_HOST, ADLS_ACCOUNT_KEY, @@ -78,14 +68,12 @@ S3_PROFILE_NAME, S3_PROXY_URI, S3_REGION, + S3_REQUEST_SIGNER, S3_REQUEST_TIMEOUT, S3_SECRET_ACCESS_KEY, S3_SERVER_SIDE_ENCRYPTION, S3_SESSION_TOKEN, S3_SIGNER, - S3_SIGNER_ENDPOINT, - S3_SIGNER_ENDPOINT_DEFAULT, - S3_SIGNER_URI, S3_SSE_KMS_KEY_ID, FileIO, InputFile, @@ -94,85 +82,26 @@ OutputStream, _is_local_path, ) +from pyiceberg.io.signer import ( + SIGNERS as SIGNERS, +) +from pyiceberg.io.signer import ( + S3RequestSigner as S3RequestSigner, +) +from pyiceberg.io.signer import ( + S3V4RestSigner as S3V4RestSigner, +) +from pyiceberg.io.signer import ( + create_s3_request_signer, +) from pyiceberg.typedef import Properties from pyiceberg.types import strtobool from pyiceberg.utils.datetime import millis_to_datetime -from pyiceberg.utils.properties import get_first_property_value, get_header_properties, property_as_bool +from pyiceberg.utils.properties import get_first_property_value, property_as_bool from pyiceberg.utils.transient import _TransientStateMixin logger = logging.getLogger(__name__) -if TYPE_CHECKING: - from botocore.awsrequest import AWSRequest - - -class S3RequestSigner(abc.ABC): - """Abstract base class for S3 request signers.""" - - properties: Properties - - def __init__(self, properties: Properties) -> None: - self.properties = properties - - @abc.abstractmethod - def __call__(self, request: "AWSRequest", **_: Any) -> None: - pass - - -class S3V4RestSigner(S3RequestSigner): - """An S3 request signer that uses an external REST signing service to sign requests.""" - - _session: requests.Session - - def __init__(self, properties: Properties) -> None: - super().__init__(properties) - self._session = requests.Session() - - def __call__(self, request: "AWSRequest", operation_name: str | None = None, **_: Any) -> None: - signer_url = self.properties.get(S3_SIGNER_URI, self.properties[URI]).rstrip("/") # type: ignore - signer_endpoint = self.properties.get(S3_SIGNER_ENDPOINT, S3_SIGNER_ENDPOINT_DEFAULT) - - signer_headers: dict[str, str] = {} - - auth_header: str | None = None - if auth_manager := self.properties.get(AUTH_MANAGER): - auth_header = auth_manager.auth_header() - elif token := self.properties.get(TOKEN): - auth_header = f"Bearer {token}" - - if auth_header: - signer_headers["Authorization"] = auth_header - - signer_headers.update(get_header_properties(self.properties)) - signer_headers["User-Agent"] = _user_agent() - - signer_body = { - "method": request.method, - "region": request.context["client_region"], - "uri": request.url, - "headers": {key: [val] for key, val in request.headers.items()}, - } - # The signing service needs the DeleteObjects body to authorize the keys being deleted - if operation_name == "DeleteObjects": - signer_body["body"] = request.body.decode("utf-8") - - response = self._session.post(f"{signer_url}/{signer_endpoint.strip()}", headers=signer_headers, json=signer_body) - try: - response.raise_for_status() - response_json = response.json() - except HTTPError as e: - raise SignError(f"Failed to sign request {response.status_code}: {signer_body}") from e - - for key, value in response_json["headers"].items(): - # Replace instead of append, so a header the request already has is not sent twice - del request.headers[key] - request.headers.add_header(key, ", ".join(value)) - - request.url = response_json["uri"] - - -SIGNERS: dict[str, type[S3RequestSigner]] = {"S3V4RestSigner": S3V4RestSigner} - def _file(_: Properties) -> LocalFileSystem: return LocalFileSystem(auto_mkdir=True) @@ -190,20 +119,18 @@ def _s3(properties: Properties) -> AbstractFileSystem: } config_kwargs = {} s3_additional_kwargs = {} - register_events: dict[str, Callable[[AWSRequest], None]] = {} + register_events: dict[str, S3RequestSigner] = {} - if signer := properties.get(S3_SIGNER): + if request_signer := properties.get(S3_REQUEST_SIGNER): + register_events["before-sign.s3"] = request_signer + elif signer := properties.get(S3_SIGNER): logger.info("Loading signer %s", signer) - if signer_cls := SIGNERS.get(signer): - signer = signer_cls(properties) - register_events["before-sign.s3"] = signer + register_events["before-sign.s3"] = create_s3_request_signer(properties) - # Disable the AWS Signer - from botocore import UNSIGNED + if register_events: + from botocore import UNSIGNED - config_kwargs["signature_version"] = UNSIGNED - else: - raise ValueError(f"Signer not available: {signer}") + config_kwargs["signature_version"] = UNSIGNED if proxy_uri := properties.get(S3_PROXY_URI): config_kwargs["proxies"] = {"http": proxy_uri, "https": proxy_uri} diff --git a/pyiceberg/io/signer.py b/pyiceberg/io/signer.py new file mode 100644 index 0000000000..0abeab08c2 --- /dev/null +++ b/pyiceberg/io/signer.py @@ -0,0 +1,117 @@ +# 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. + +import abc +from typing import TYPE_CHECKING, Any + +import requests +from requests import HTTPError + +from pyiceberg.catalog import TOKEN, URI +from pyiceberg.catalog.rest import _user_agent +from pyiceberg.catalog.rest.auth import AUTH_MANAGER +from pyiceberg.exceptions import SignError +from pyiceberg.io import S3_SIGNER, S3_SIGNER_ENDPOINT, S3_SIGNER_ENDPOINT_DEFAULT, S3_SIGNER_URI +from pyiceberg.typedef import Properties +from pyiceberg.utils.properties import get_header_properties + +if TYPE_CHECKING: + from botocore.awsrequest import AWSRequest + + +class S3RequestSigner(abc.ABC): + """Abstract base class for S3 request signers.""" + + properties: Properties + + def __init__(self, properties: Properties) -> None: + self.properties = properties + + @abc.abstractmethod + def __call__(self, request: "AWSRequest", **_: Any) -> None: + pass + + +class S3V4RestSigner(S3RequestSigner): + """An S3 request signer that uses an external REST signing service to sign requests.""" + + _session: requests.Session + + def __init__(self, properties: Properties) -> None: + super().__init__(properties) + self._session = requests.Session() + + def __call__(self, request: "AWSRequest", operation_name: str | None = None, **_: Any) -> None: + signer_url = self.properties.get(S3_SIGNER_URI, self.properties[URI]).rstrip("/") + signer_endpoint = self.properties.get(S3_SIGNER_ENDPOINT, S3_SIGNER_ENDPOINT_DEFAULT) + + signer_headers: dict[str, str] = {} + + auth_header: str | None = None + if auth_manager := self.properties.get(AUTH_MANAGER): + auth_header = auth_manager.auth_header() + elif token := self.properties.get(TOKEN): + auth_header = f"Bearer {token}" + + if auth_header: + signer_headers["Authorization"] = auth_header + + signer_headers.update(get_header_properties(self.properties)) + signer_headers["User-Agent"] = _user_agent() + + signer_body = { + "method": request.method, + "region": request.context["client_region"], + "uri": request.url, + "headers": {key: [val] for key, val in request.headers.items()}, + } + if operation_name == "DeleteObjects": + signer_body["body"] = request.body.decode("utf-8") + + response = self._session.post(f"{signer_url}/{signer_endpoint.strip()}", headers=signer_headers, json=signer_body) + try: + response.raise_for_status() + response_json = response.json() + except HTTPError as e: + raise SignError(f"Failed to sign request {response.status_code}: {signer_body}") from e + + for key, value in response_json["headers"].items(): + del request.headers[key] + request.headers.add_header(key, ", ".join(value)) + + request.url = response_json["uri"] + + +SIGNERS: dict[str, type[S3RequestSigner]] = {"S3V4RestSigner": S3V4RestSigner} + + +def create_s3_request_signer(properties: Properties) -> S3RequestSigner: + """Create the configured S3 request signer. + + Args: + properties: Catalog and FileIO properties. + + Returns: + The configured signer instance. + + Raises: + ValueError: If the configured signer is not available. + """ + signer = properties.get(S3_SIGNER) + if signer_cls := SIGNERS.get(signer): + return signer_cls(properties) + raise ValueError(f"Signer not available: {signer}") diff --git a/tests/catalog/test_rest.py b/tests/catalog/test_rest.py index 0d8ca00257..25bc42a97e 100644 --- a/tests/catalog/test_rest.py +++ b/tests/catalog/test_rest.py @@ -75,7 +75,8 @@ TableAlreadyExistsError, ViewAlreadyExistsError, ) -from pyiceberg.io import ARROW_FILE_IO, FSSPEC_FILE_IO, PY_IO_IMPL, load_file_io +from pyiceberg.io import ARROW_FILE_IO, FSSPEC_FILE_IO, PY_IO_IMPL, S3_REQUEST_SIGNER, load_file_io +from pyiceberg.io.signer import S3V4RestSigner from pyiceberg.partitioning import PartitionField, PartitionSpec from pyiceberg.schema import Schema from pyiceberg.table import Table @@ -3793,6 +3794,15 @@ def test_resolve_storage_credentials_empty() -> None: assert RestCatalog._resolve_storage_credentials([], None) == {} +def test_load_file_io_passes_signer_instance(rest_mock: Mocker) -> None: + catalog = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN, **{"s3.signer": "S3V4RestSigner"}) + + io = catalog._load_file_io(location="s3://warehouse/table") + + assert isinstance(io.properties[S3_REQUEST_SIGNER], S3V4RestSigner) + assert io.properties[S3_REQUEST_SIGNER].properties["uri"] == TEST_URI + + def test_load_table_with_storage_credentials(rest_mock: Mocker, example_table_metadata_with_snapshot_v1: dict[str, Any]) -> None: metadata_location = "s3://warehouse/database/table/metadata/00001.metadata.json" rest_mock.get( diff --git a/tests/io/test_fsspec.py b/tests/io/test_fsspec.py index 9c76e535fe..ace4780c5e 100644 --- a/tests/io/test_fsspec.py +++ b/tests/io/test_fsspec.py @@ -39,7 +39,7 @@ from pyiceberg.catalog.rest import _user_agent from pyiceberg.catalog.rest.auth import AUTH_MANAGER from pyiceberg.exceptions import SignError -from pyiceberg.io import fsspec +from pyiceberg.io import S3_REQUEST_SIGNER, fsspec from pyiceberg.io.fsspec import FsspecFileIO, S3V4RestSigner from pyiceberg.io.pyarrow import PyArrowFileIO from pyiceberg.typedef import Properties @@ -1022,6 +1022,25 @@ def test_s3_registers_the_signer_on_the_session(requests_mock: Mocker) -> None: assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 Credential=abc" +def test_s3_uses_supplied_signer_instance(requests_mock: Mocker) -> None: + new_uri = "https://other-bucket/object" + requests_mock.post( + f"{TEST_URI}/v1/aws/s3/sign", + json={"uri": new_uri, "headers": {"Authorization": ["AWS4-HMAC-SHA256 Credential=abc"]}, "extensions": {}}, + status_code=200, + ) + signer = S3V4RestSigner({"token": "abc", "uri": TEST_URI}) + + with mock.patch("s3fs.S3FileSystem") as mock_s3fs: + fsspec._s3({S3_REQUEST_SIGNER: signer, "s3.endpoint": "http://localhost:9000"}) + + session = mock_s3fs.call_args.kwargs["session"] + request = _sign_with_session(session, "https://bucket/object") + + assert request.url == new_uri + assert request.headers["Authorization"] == "AWS4-HMAC-SHA256 Credential=abc" + + def test_s3_registers_the_signer_per_session(requests_mock: Mocker) -> None: signers = [ ("https://first-signer", "https://bucket/first"),