Skip to content
Open
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
6 changes: 6 additions & 0 deletions pyiceberg/catalog/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@
AWS_REGION,
AWS_SECRET_ACCESS_KEY,
AWS_SESSION_TOKEN,
S3_REQUEST_SIGNER,
S3_SIGNER,
FileIO,
load_file_io,
)
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions pyiceberg/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
119 changes: 23 additions & 96 deletions pyiceberg/io/fsspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,20 @@
# under the License.
"""FileIO implementation for reading and writing table files that uses fsspec compatible filesystems."""

import abc
import errno
import json
import logging
import os
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,
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand All @@ -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}
Expand Down
117 changes: 117 additions & 0 deletions pyiceberg/io/signer.py
Original file line number Diff line number Diff line change
@@ -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}")
12 changes: 11 additions & 1 deletion tests/catalog/test_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
21 changes: 20 additions & 1 deletion tests/io/test_fsspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"),
Expand Down
Loading