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
8 changes: 8 additions & 0 deletions pyiceberg/encryption/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ def _data_key_size(metadata: TableMetadata) -> AesKeySize:
return AesKeySize.from_key_length(TableProperties.ENCRYPTION_DATA_KEY_LENGTH_DEFAULT if key_length is None else key_length)


def _reject_encrypted_writes(*metadata: TableMetadata) -> None:
"""Raise if any of the metadata is encrypted, until encrypted manifests and manifest lists can be written."""
from pyiceberg.table import TableProperties

if any(TableProperties.ENCRYPTION_KEY_ID in m.properties for m in metadata):
raise NotImplementedError("Writing to encrypted tables is not yet supported")


def _now_ms() -> int:
return time.time_ns() // 1_000_000

Expand Down
4 changes: 4 additions & 0 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,10 @@ def dynamic_partition_overwrite(
snapshot_properties: Custom properties to be added to the snapshot summary
branch: Branch Reference to run the dynamic partition overwrite operation
"""
from pyiceberg.encryption.manager import _reject_encrypted_writes

# Data files are written before the delete creates a snapshot producer
_reject_encrypted_writes(self._table.metadata, self.table_metadata)
try:
import pyarrow as pa
except ModuleNotFoundError as e:
Expand Down
9 changes: 9 additions & 0 deletions pyiceberg/table/update/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ def __init__(
branch: str | None = MAIN_BRANCH,
) -> None:
super().__init__(transaction)
self._reject_encrypted_writes()
self.commit_uuid = commit_uuid or uuid.uuid4()
self._io = io
self._operation = operation
Expand Down Expand Up @@ -334,7 +335,15 @@ def _summary(self, snapshot_properties: dict[str, str] = EMPTY_DICT) -> Summary:
previous_summary=previous_snapshot.summary if previous_snapshot is not None else None,
)

def _reject_encrypted_writes(self) -> None:
from pyiceberg.encryption.manager import _reject_encrypted_writes

# Committed metadata too, so removing the key in the same transaction can't bypass this
_reject_encrypted_writes(self._transaction._table.metadata, self._transaction.table_metadata)

def _commit(self) -> UpdatesAndRequirements:
# Again here, since a retry reruns this against refreshed metadata
self._reject_encrypted_writes()
new_manifests = self._manifests()
next_sequence_number = self._transaction.table_metadata.next_sequence_number()

Expand Down
52 changes: 52 additions & 0 deletions tests/table/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
StaticTable,
Table,
TableIdentifier,
TableProperties,
)
from pyiceberg.table.labels import Labels
from pyiceberg.table.metadata import EncryptedKey, TableMetadataUtil, TableMetadataV1, TableMetadataV2, _generate_snapshot_id
Expand Down Expand Up @@ -2401,6 +2402,57 @@ def test_scan_encrypted_table(table_v3_encrypted: Table) -> None:
assert table_v3_encrypted.scan().to_arrow().num_rows == 0


def test_writes_to_encrypted_table_are_rejected(table_v3_encrypted: Table, tmp_path: Path) -> None:
import pyarrow as pa

table_v3_encrypted.metadata = table_v3_encrypted.metadata.model_copy(update={"location": f"file://{tmp_path}"})
df = pa.table({"x": [1, 2, 3]}, schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]))

for write in [
lambda: table_v3_encrypted.append(df),
lambda: table_v3_encrypted.overwrite(df),
lambda: table_v3_encrypted.delete(AlwaysTrue()),
lambda: table_v3_encrypted.transaction().remove_properties(TableProperties.ENCRYPTION_KEY_ID).append(df),
]:
with pytest.raises(NotImplementedError, match="Writing to encrypted tables is not yet supported"):
write()

assert list(tmp_path.iterdir()) == []


def test_dynamic_partition_overwrite_to_encrypted_table_writes_nothing(table_v3_encrypted: Table, tmp_path: Path) -> None:
import pyarrow as pa

spec = PartitionSpec(PartitionField(source_id=1, field_id=1000, transform=IdentityTransform(), name="x"), spec_id=0)
table_v3_encrypted.metadata = table_v3_encrypted.metadata.model_copy(
update={"location": f"file://{tmp_path}", "partition_specs": [spec]}
)
df = pa.table({"x": [1, 2, 3]}, schema=pa.schema([pa.field("x", pa.int64(), nullable=False)]))

with pytest.raises(NotImplementedError, match="Writing to encrypted tables is not yet supported"):
table_v3_encrypted.dynamic_partition_overwrite(df)

assert list(tmp_path.iterdir()) == []


def test_write_is_rejected_when_table_is_encrypted_before_a_retry(table_v3: Table) -> None:
producer = table_v3.transaction().update_snapshot().fast_append()

# A retry refreshes the table metadata, then reruns _commit
table_v3.metadata = table_v3.metadata.model_copy(
update={"properties": {**table_v3.metadata.properties, TableProperties.ENCRYPTION_KEY_ID: "master-1"}}
)

with pytest.raises(NotImplementedError, match="Writing to encrypted tables is not yet supported"):
producer._commit()


def test_metadata_only_updates_to_encrypted_table_are_allowed(table_v3_encrypted: Table) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this one also passes on main, since set_properties never goes through a snapshot producer. I'm fine keeping it as a guard against over-blocking though.

transaction = table_v3_encrypted.transaction().set_properties(owner="me")

assert transaction.table_metadata.properties["owner"] == "me"


def test_inspect_encrypted_table(table_v3_encrypted: Table) -> None:
assert table_v3_encrypted.inspect.manifests().num_rows == 0
assert table_v3_encrypted.inspect.all_manifests().num_rows == 0
Expand Down
Loading