Copilot commented on code in PR #3969:
URL: https://github.com/apache/iceberg-python/pull/3969#discussion_r4341860799


##########
pyiceberg/encryption/stream.py:
##########
@@ -0,0 +1,149 @@
+# 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.
+"""Format primitives for the AGS1 stream, used to encrypt manifests and 
manifest lists.
+
+An AGS1 stream is an 8 byte header followed by a sequence of AES-GCM blocks::
+
+    "AGS1" || plain_block_size (4 bytes, little endian)
+    nonce || ciphertext || tag        (block 0, up to plain_block_size of 
plaintext)
+    nonce || ciphertext || tag        (block 1..n, the last of which may be 
shorter)
+
+Each block authenticates `aad_prefix || block_index` as additional data, so 
blocks cannot
+be reordered or moved between files.
+
+The spec gives the last block a non-zero length, which makes a bare header its 
encoding of an
+empty file. Java, iceberg-rust and PyIceberg all require at least one block 
instead, so an
+empty file is a header followed by a single empty block. apache/iceberg#18219 
tracks which of
+the two forms writers should produce.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from pyiceberg.encryption.ciphers import AesGcmCipher
+
+_GCM_STREAM_MAGIC = b"AGS1"
+_PLAIN_BLOCK_SIZE = 1024 * 1024
+_GCM_STREAM_HEADER_LENGTH = len(_GCM_STREAM_MAGIC) + 4
+_BLOCK_OVERHEAD = AesGcmCipher.NONCE_LENGTH + AesGcmCipher.TAG_LENGTH
+_CIPHER_BLOCK_SIZE = _PLAIN_BLOCK_SIZE + _BLOCK_OVERHEAD
+_BLOCK_INDEX_LENGTH = 4
+_MAX_BLOCKS = 2 ** (8 * _BLOCK_INDEX_LENGTH) - 1

Review Comment:
   `_MAX_BLOCKS` is currently set to the maximum *block index* representable by 
4 bytes (2^32 - 1), but it’s used as the maximum *number of blocks*. This 
creates an off-by-one limit where the maximum encodable index can never occur 
as the last block index (since last index is `num_blocks - 1`). Consider 
splitting this into `_MAX_BLOCK_INDEX = 2**32 - 1` and `_MAX_BLOCKS = 
_MAX_BLOCK_INDEX + 1`, then validate with `if num_blocks > _MAX_BLOCKS` (or 
equivalently `if num_blocks - 1 > _MAX_BLOCK_INDEX`). Update tests accordingly 
so the terminology matches the actual constraint.



##########
pyiceberg/encryption/stream.py:
##########
@@ -0,0 +1,149 @@
+# 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.
+"""Format primitives for the AGS1 stream, used to encrypt manifests and 
manifest lists.
+
+An AGS1 stream is an 8 byte header followed by a sequence of AES-GCM blocks::
+
+    "AGS1" || plain_block_size (4 bytes, little endian)
+    nonce || ciphertext || tag        (block 0, up to plain_block_size of 
plaintext)
+    nonce || ciphertext || tag        (block 1..n, the last of which may be 
shorter)
+
+Each block authenticates `aad_prefix || block_index` as additional data, so 
blocks cannot
+be reordered or moved between files.
+
+The spec gives the last block a non-zero length, which makes a bare header its 
encoding of an
+empty file. Java, iceberg-rust and PyIceberg all require at least one block 
instead, so an
+empty file is a header followed by a single empty block. apache/iceberg#18219 
tracks which of
+the two forms writers should produce.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from pyiceberg.encryption.ciphers import AesGcmCipher
+
+_GCM_STREAM_MAGIC = b"AGS1"
+_PLAIN_BLOCK_SIZE = 1024 * 1024
+_GCM_STREAM_HEADER_LENGTH = len(_GCM_STREAM_MAGIC) + 4
+_BLOCK_OVERHEAD = AesGcmCipher.NONCE_LENGTH + AesGcmCipher.TAG_LENGTH
+_CIPHER_BLOCK_SIZE = _PLAIN_BLOCK_SIZE + _BLOCK_OVERHEAD
+_BLOCK_INDEX_LENGTH = 4
+_MAX_BLOCKS = 2 ** (8 * _BLOCK_INDEX_LENGTH) - 1
+_MIN_STREAM_LENGTH = _GCM_STREAM_HEADER_LENGTH + _BLOCK_OVERHEAD
+
+
+def _stream_block_aad(aad_prefix: bytes | None, block_index: int) -> bytes:
+    """Return the additional authenticated data for the block at `block_index`.
+
+    Args:
+        aad_prefix (bytes | None): The file's AAD prefix, from its key 
metadata.
+        block_index (int): The zero-based index of the block within the stream.
+    """
+    return (aad_prefix or b"") + block_index.to_bytes(_BLOCK_INDEX_LENGTH, 
"little")
+
+
+def _encode_stream_header() -> bytes:
+    """Encode the AGS1 header that precedes the first block."""
+    return _GCM_STREAM_MAGIC + _PLAIN_BLOCK_SIZE.to_bytes(4, "little")
+
+
+def _decode_stream_header(header: bytes) -> int:
+    """Decode an AGS1 header, returning the plaintext block size it declares.
+
+    Args:
+        header (bytes): At least `_GCM_STREAM_HEADER_LENGTH` bytes from the 
start of the stream.
+    """
+    if len(header) < _GCM_STREAM_HEADER_LENGTH:
+        raise ValueError(f"Invalid AGS1 header: expected 
{_GCM_STREAM_HEADER_LENGTH} bytes, got {len(header)}")
+
+    if (magic := header[: len(_GCM_STREAM_MAGIC)]) != _GCM_STREAM_MAGIC:
+        raise ValueError(f"Invalid AGS1 header: magic {magic!r} does not match 
{_GCM_STREAM_MAGIC!r}")
+
+    plain_block_size = int.from_bytes(header[len(_GCM_STREAM_MAGIC) : 
_GCM_STREAM_HEADER_LENGTH], "little")
+    if plain_block_size != _PLAIN_BLOCK_SIZE:
+        raise ValueError(f"Unsupported AGS1 block size: {plain_block_size} 
(expected {_PLAIN_BLOCK_SIZE})")
+
+    return plain_block_size
+
+
+@dataclass(frozen=True)
+class _Ags1Layout:
+    """Where each block of an AGS1 stream sits, derived from the trusted 
encrypted file length.
+
+    Only the final block may hold less than `_PLAIN_BLOCK_SIZE` of plaintext, 
so the layout
+    follows from the encrypted length alone, without reading the stream.
+    """
+
+    plaintext_length: int
+    num_blocks: int
+    last_cipher_block_size: int
+
+    @classmethod
+    def from_encrypted_length(cls, encrypted_length: int) -> _Ags1Layout:
+        """Derive the layout of an AGS1 stream that occupies 
`encrypted_length` bytes.
+
+        Args:
+            encrypted_length (int): The stream's length, which must be the 
trusted `file_length` from the file's
+                `StandardKeyMetadata`, never a file system stat. The spec 
requires the trusted length because a
+                stat lets an attacker drop trailing blocks while every 
remaining block still authenticates.
+        """
+        if encrypted_length < _MIN_STREAM_LENGTH:
+            raise ValueError(f"Invalid AGS1 stream: expected at least 
{_MIN_STREAM_LENGTH} bytes, got {encrypted_length}")
+
+        full_blocks, cipher_bytes_in_last_block = divmod(encrypted_length - 
_GCM_STREAM_HEADER_LENGTH, _CIPHER_BLOCK_SIZE)
+        if cipher_bytes_in_last_block == 0:
+            num_blocks, last_cipher_block_size = full_blocks, 
_CIPHER_BLOCK_SIZE
+        elif cipher_bytes_in_last_block < _BLOCK_OVERHEAD:
+            raise ValueError(
+                f"Truncated AGS1 stream: last block is 
{cipher_bytes_in_last_block} bytes, expected at least {_BLOCK_OVERHEAD}"
+            )
+        else:
+            num_blocks, last_cipher_block_size = full_blocks + 1, 
cipher_bytes_in_last_block
+
+        if num_blocks > _MAX_BLOCKS:
+            raise ValueError(f"AGS1 streams hold at most {_MAX_BLOCKS} blocks, 
but {encrypted_length} bytes needs {num_blocks}")

Review Comment:
   `_MAX_BLOCKS` is currently set to the maximum *block index* representable by 
4 bytes (2^32 - 1), but it’s used as the maximum *number of blocks*. This 
creates an off-by-one limit where the maximum encodable index can never occur 
as the last block index (since last index is `num_blocks - 1`). Consider 
splitting this into `_MAX_BLOCK_INDEX = 2**32 - 1` and `_MAX_BLOCKS = 
_MAX_BLOCK_INDEX + 1`, then validate with `if num_blocks > _MAX_BLOCKS` (or 
equivalently `if num_blocks - 1 > _MAX_BLOCK_INDEX`). Update tests accordingly 
so the terminology matches the actual constraint.



##########
tests/encryption/ags1/README.md:
##########
@@ -0,0 +1,77 @@
+<!--
+  ~ 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.
+-->
+
+# AGS1 cross-client test fixtures
+
+These files were written by Java's `AesGcmOutputStream` (Apache Iceberg 
1.11.0), not
+by PyIceberg. They exist so PyIceberg's AGS1 support is checked against another
+implementation's bytes rather than only against its own round trip. All four 
also
+decrypt with iceberg-rust 0.10.1, through its `EncryptedInputFile`.
+
+## Fixtures
+
+| File | Encrypted size | Plaintext | Pins |
+| --- | --- | --- | --- |
+| `empty.ags1` | 36 B | 0 B | Java writes an 8 byte header **plus one empty 
block** for an empty file, not a bare header |
+| `partial-block.ags1` | 136 B | 100 B | Header, nonce/tag layout, and a 
single short block |
+| `partial-block-no-aad.ags1` | 136 B | 100 B | The same stream with a null 
AAD prefix, so the block index alone is the AAD |
+| `aligned-multi-block.ags1` | 2097216 B | 2 MiB | Two full blocks: the 
little-endian block index in each block's AAD, and that a block-aligned write 
appends **no** trailing empty block |

Review Comment:
   This table uses double leading pipes (`||`), which doesn’t render as a 
standard Markdown table (it creates an extra empty first column / can render 
incorrectly depending on parser). Replace with single-pipe Markdown table 
syntax (`| File | ... |`) for consistent rendering in GitHub and other Markdown 
viewers.



##########
pyiceberg/encryption/stream.py:
##########
@@ -0,0 +1,149 @@
+# 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.
+"""Format primitives for the AGS1 stream, used to encrypt manifests and 
manifest lists.
+
+An AGS1 stream is an 8 byte header followed by a sequence of AES-GCM blocks::
+
+    "AGS1" || plain_block_size (4 bytes, little endian)
+    nonce || ciphertext || tag        (block 0, up to plain_block_size of 
plaintext)
+    nonce || ciphertext || tag        (block 1..n, the last of which may be 
shorter)
+
+Each block authenticates `aad_prefix || block_index` as additional data, so 
blocks cannot
+be reordered or moved between files.
+
+The spec gives the last block a non-zero length, which makes a bare header its 
encoding of an
+empty file. Java, iceberg-rust and PyIceberg all require at least one block 
instead, so an
+empty file is a header followed by a single empty block. apache/iceberg#18219 
tracks which of
+the two forms writers should produce.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from pyiceberg.encryption.ciphers import AesGcmCipher
+
+_GCM_STREAM_MAGIC = b"AGS1"
+_PLAIN_BLOCK_SIZE = 1024 * 1024
+_GCM_STREAM_HEADER_LENGTH = len(_GCM_STREAM_MAGIC) + 4
+_BLOCK_OVERHEAD = AesGcmCipher.NONCE_LENGTH + AesGcmCipher.TAG_LENGTH
+_CIPHER_BLOCK_SIZE = _PLAIN_BLOCK_SIZE + _BLOCK_OVERHEAD
+_BLOCK_INDEX_LENGTH = 4
+_MAX_BLOCKS = 2 ** (8 * _BLOCK_INDEX_LENGTH) - 1
+_MIN_STREAM_LENGTH = _GCM_STREAM_HEADER_LENGTH + _BLOCK_OVERHEAD
+
+
+def _stream_block_aad(aad_prefix: bytes | None, block_index: int) -> bytes:
+    """Return the additional authenticated data for the block at `block_index`.
+
+    Args:
+        aad_prefix (bytes | None): The file's AAD prefix, from its key 
metadata.
+        block_index (int): The zero-based index of the block within the stream.
+    """

Review Comment:
   `block_index.to_bytes(4, ...)` will raise `OverflowError` for negative 
values or values > 2^32-1, which is inconsistent with the rest of the module 
using `ValueError` with clear messages. Adding an explicit range check here 
(e.g., `0 <= block_index <= _MAX_BLOCK_INDEX`) and raising `ValueError` would 
make failures more actionable and keep error behavior consistent.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to