diff --git a/dev/docker-compose-integration.yml b/dev/docker-compose-integration.yml index 43dbd3dffd..1c3ce6abeb 100644 --- a/dev/docker-compose-integration.yml +++ b/dev/docker-compose-integration.yml @@ -70,6 +70,8 @@ services: - warehouse.object-store ports: - 9000:9000 + # Lakekeeper shares this network namespace, see the lakekeeper service. + - 8182:8181 environment: - RUSTFS_ACCESS_KEY=admin - RUSTFS_SECRET_KEY=password @@ -125,6 +127,60 @@ services: environment: SERVICE_NAME: "metastore" SERVICE_OPTS: "-Dmetastore.warehouse.dir=s3a://warehouse/hive/" + lakekeeper-db: + image: postgres:17 + container_name: pyiceberg-lakekeeper-db + networks: + iceberg_net: + environment: + - POSTGRES_PASSWORD=postgres + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -p 5432 -d postgres"] + interval: 2s + timeout: 10s + retries: 10 + start_period: 5s + lakekeeper-migrate: + image: quay.io/lakekeeper/catalog:v0.15.1 + container_name: pyiceberg-lakekeeper-migrate + networks: + iceberg_net: + environment: + - LAKEKEEPER__PG_ENCRYPTION_KEY=This-is-NOT-Secure! + - LAKEKEEPER__PG_DATABASE_URL_READ=postgresql://postgres:postgres@lakekeeper-db:5432/postgres + - LAKEKEEPER__PG_DATABASE_URL_WRITE=postgresql://postgres:postgres@lakekeeper-db:5432/postgres + command: ["migrate"] + restart: "no" + depends_on: + lakekeeper-db: + condition: service_healthy + lakekeeper: + image: quay.io/lakekeeper/catalog:v0.15.1 + container_name: pyiceberg-lakekeeper + # Lakekeeper returns the S3 endpoint of the warehouse to the client. Sharing the network + # namespace of the object store makes http://localhost:9000 reachable from both Lakekeeper + # and the tests on the host. The catalog is published on port 8182 by the object-store service. + network_mode: "service:object-store" + environment: + - LAKEKEEPER__PG_ENCRYPTION_KEY=This-is-NOT-Secure! + - LAKEKEEPER__PG_DATABASE_URL_READ=postgresql://postgres:postgres@lakekeeper-db:5432/postgres + - LAKEKEEPER__PG_DATABASE_URL_WRITE=postgresql://postgres:postgres@lakekeeper-db:5432/postgres + # The default metrics port 9000 is taken by the object store in the shared network namespace. + - LAKEKEEPER__METRICS__PORT=9091 + command: ["serve"] + depends_on: + lakekeeper-migrate: + condition: service_completed_successfully + object-store: + condition: service_healthy + aws-cli: + condition: service_completed_successfully + healthcheck: + test: ["CMD", "/home/nonroot/lakekeeper", "healthcheck"] + interval: 2s + timeout: 10s + retries: 10 + start_period: 5s networks: iceberg_net: diff --git a/dev/provision.py b/dev/provision.py index 846576fb75..d65f9b7b83 100644 --- a/dev/provision.py +++ b/dev/provision.py @@ -15,6 +15,9 @@ # specific language governing permissions and limitations # under the License. +from typing import Any + +import requests from pyspark.sql import SparkSession from pyspark.sql.functions import current_date, date_add, expr @@ -22,6 +25,57 @@ from pyiceberg.schema import Schema from pyiceberg.types import FixedType, NestedField, UUIDType +LAKEKEEPER_MANAGEMENT_URI = "http://localhost:8182/management/v1" +LAKEKEEPER_WAREHOUSE = "lakekeeper" + + +def _lakekeeper(method: str, path: str, json: dict[str, Any] | None = None) -> requests.Response: + response = requests.request(method, f"{LAKEKEEPER_MANAGEMENT_URI}/{path}", json=json) + if not response.ok: + raise RuntimeError(f"Lakekeeper {method} {path} failed with {response.status_code}: {response.text}") + return response + + +def provision_lakekeeper() -> None: + """Bootstrap Lakekeeper and create a warehouse that only allows access through remote signing.""" + if not _lakekeeper("GET", "info").json()["bootstrapped"]: + _lakekeeper("POST", "bootstrap", json={"accept-terms-of-use": True}) + + warehouses = _lakekeeper("GET", "warehouse").json()["warehouses"] + if any(warehouse["name"] == LAKEKEEPER_WAREHOUSE for warehouse in warehouses): + return + + _lakekeeper( + "POST", + "warehouse", + json={ + "warehouse-name": LAKEKEEPER_WAREHOUSE, + "storage-profile": { + "type": "s3", + "bucket": "warehouse", + "key-prefix": "lakekeeper", + "region": "us-east-1", + # Lakekeeper shares the network namespace of the object store, see docker-compose-integration.yml + "endpoint": "http://localhost:9000", + "path-style-access": True, + "flavor": "s3-compat", + "sts-enabled": False, + "remote-signing-enabled": True, + "remote-signing-url-style": "path", + }, + "storage-credential": { + "type": "s3", + "credential-type": "access-key", + "aws-access-key-id": "admin", + "aws-secret-access-key": "password", + }, + "delete-profile": {"type": "hard"}, + }, + ) + + +provision_lakekeeper() + # Create SparkSession against the remote Spark Connect server spark = SparkSession.builder.remote("sc://localhost:15002").getOrCreate() diff --git a/mkdocs/docs/contributing.md b/mkdocs/docs/contributing.md index 2e9cf126d1..0bdce9d0d2 100644 --- a/mkdocs/docs/contributing.md +++ b/mkdocs/docs/contributing.md @@ -257,6 +257,7 @@ This command spins up the full integration test infrastructure via Docker Compos - **Spark** (with Spark Connect) - **Iceberg REST Catalog** (using the [`apache/iceberg-rest-fixture`](https://hub.docker.com/r/apache/iceberg-rest-fixture) image) - **Hive Metastore** +- **Lakekeeper REST Catalog** (on port 8182, with S3 remote signing) - **S3-compatible object storage** (RustFS) **Spark Example Notebook** (`notebooks/spark_integration_example.ipynb`) is based on the [Spark Getting Started](https://iceberg.apache.org/docs/nightly/spark-getting-started/) guide. This notebook demonstrates how to work with PyIceberg alongside Spark, leveraging the Docker-based testing setup for a complete local development environment. diff --git a/tests/conftest.py b/tests/conftest.py index 05d50925c6..34a6ca3570 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2820,6 +2820,20 @@ def session_catalog() -> Catalog: ) +@pytest.fixture(scope="session") +def session_catalog_lakekeeper() -> Catalog: + # No S3 credentials: Lakekeeper signs every request to the object store + return load_catalog( + "lakekeeper", + **{ + "type": "rest", + "uri": "http://localhost:8182/catalog", + "warehouse": "lakekeeper", + "header.X-Iceberg-Access-Delegation": "remote-signing", + }, + ) + + @pytest.fixture(scope="session") def session_catalog_hive() -> Catalog: return load_catalog( diff --git a/tests/integration/test_rest_remote_signing.py b/tests/integration/test_rest_remote_signing.py new file mode 100644 index 0000000000..bce48ae396 --- /dev/null +++ b/tests/integration/test_rest_remote_signing.py @@ -0,0 +1,91 @@ +# 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. +# pylint:disable=redefined-outer-name +"""Integration tests for S3 remote signing against Lakekeeper, which signs every request to the object store.""" + +from collections.abc import Generator + +import pyarrow as pa +import pytest + +from pyiceberg.catalog import Catalog +from pyiceberg.exceptions import SignError +from pyiceberg.io import S3_ACCESS_KEY_ID, S3_REMOTE_SIGNING_ENABLED, S3_SECRET_ACCESS_KEY, S3_SIGNER +from pyiceberg.io.fsspec import FsspecFileIO +from pyiceberg.partitioning import PartitionField, PartitionSpec +from pyiceberg.schema import Schema +from pyiceberg.table import Table +from pyiceberg.transforms import IdentityTransform +from pyiceberg.types import LongType, NestedField, StringType +from tests.conftest import clean_up + +SCHEMA = Schema( + NestedField(field_id=1, name="id", field_type=LongType(), required=False), + NestedField(field_id=2, name="category", field_type=StringType(), required=False), +) + +ARROW_TABLE = pa.Table.from_pydict( + {"id": [1, 2, 3, 4], "category": ["a", "b", "c", "a"]}, + schema=SCHEMA.as_arrow(), +) + + +@pytest.fixture +def table(session_catalog_lakekeeper: Catalog, database_name: str, table_name: str) -> Generator[Table, None, None]: + session_catalog_lakekeeper.create_namespace(database_name) + yield session_catalog_lakekeeper.create_table( + (database_name, table_name), + schema=SCHEMA, + partition_spec=PartitionSpec(PartitionField(source_id=2, field_id=1000, transform=IdentityTransform(), name="category")), + ) + clean_up(session_catalog_lakekeeper) + + +@pytest.mark.integration +def test_remote_signing_file_io(table: Table) -> None: + assert isinstance(table.io, FsspecFileIO) + assert table.io.properties[S3_SIGNER] == "S3V4RestSigner" + assert table.io.properties[S3_REMOTE_SIGNING_ENABLED] == "true" + assert S3_ACCESS_KEY_ID not in table.io.properties + assert S3_SECRET_ACCESS_KEY not in table.io.properties + + +@pytest.mark.integration +def test_remote_signing_append_and_scan(table: Table) -> None: + # One data file per partition, written concurrently + table.append(ARROW_TABLE) + + assert len(list(table.scan().plan_files())) == 3 + assert table.scan().to_arrow().sort_by("id") == ARROW_TABLE + + +@pytest.mark.integration +def test_remote_signing_delete(table: Table) -> None: + table.append(ARROW_TABLE) + data_file = next(iter(table.scan().plan_files())).file.file_path + assert table.io.new_input(data_file).exists() + + # Goes through DeleteObjects, which needs the request body to be signed + table.io.delete(data_file) + + assert not table.io.new_input(data_file).exists() + + +@pytest.mark.integration +def test_remote_signing_rejects_location_outside_table(table: Table) -> None: + with pytest.raises(SignError, match="Failed to sign request"): + table.io.new_input(f"{table.location()}-other/data.parquet").open()