wgtmac commented on code in PR #1030:
URL: https://github.com/apache/iceberg-cpp/pull/1030#discussion_r4314054424


##########
src/iceberg/encryption/aes_gcm_stream.cc:
##########
@@ -0,0 +1,351 @@
+/*
+ * 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.
+ */
+
+#include "iceberg/encryption/aes_gcm_stream.h"
+
+#include <algorithm>
+#include <array>
+#include <cstring>
+#include <limits>
+#include <utility>
+
+#include "iceberg/encryption/aes_gcm_internal.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace {
+
+using encryption::AesGcmCipher;
+
+constexpr int64_t kPlainBlock = AesGcmStream::kPlainBlockSize;
+constexpr int64_t kCipherBlock = AesGcmStream::kCipherBlockSize;
+constexpr int64_t kBlockOverhead =
+    AesGcmStream::kNonceLength + AesGcmStream::kGcmTagLength;
+
+/// \brief Block AAD: file AAD prefix followed by the block index as a 4-byte 
LE int.
+std::vector<uint8_t> BlockAad(const std::vector<uint8_t>& aad_prefix,
+                              int32_t block_index) {
+  std::vector<uint8_t> aad(aad_prefix);
+  for (int i = 0; i < 4; ++i) {
+    aad.push_back(
+        static_cast<uint8_t>((static_cast<uint32_t>(block_index) >> (8 * i)) & 
0xFF));
+  }
+  return aad;
+}
+
+std::array<std::byte, AesGcmStream::kHeaderLength> HeaderBytes() {
+  std::array<std::byte, AesGcmStream::kHeaderLength> header{};
+  std::memcpy(header.data(), AesGcmStream::kMagic.data(), 
AesGcmStream::kMagic.size());
+  for (int i = 0; i < 4; ++i) {
+    header[4 + i] = static_cast<std::byte>(
+        (static_cast<uint32_t>(AesGcmStream::kPlainBlockSize) >> (8 * i)) & 
0xFF);
+  }
+  return header;
+}
+
+class AesGcmInputStream : public SeekableInputStream {
+ public:
+  /// \brief Construct over an encrypted length already accepted by
+  /// AesGcmStream::PlaintextLength, which bounds the block count.
+  AesGcmInputStream(std::unique_ptr<SeekableInputStream> source,
+                    std::unique_ptr<AesGcmCipher> cipher, std::vector<uint8_t> 
aad_prefix,
+                    int64_t encrypted_length, int64_t plain_size)
+      : source_(std::move(source)),
+        cipher_(std::move(cipher)),
+        aad_prefix_(std::move(aad_prefix)),
+        cipher_block_(kCipherBlock),
+        plain_block_(kPlainBlock),
+        plain_size_(plain_size) {
+    int64_t stream_length = encrypted_length - AesGcmStream::kHeaderLength;
+    int64_t num_full_blocks = stream_length / kCipherBlock;
+    int64_t last_bytes = stream_length - num_full_blocks * kCipherBlock;
+    bool full_blocks_only = last_bytes == 0;
+    num_blocks_ = full_blocks_only ? num_full_blocks : num_full_blocks + 1;
+    last_cipher_block_size_ = full_blocks_only ? kCipherBlock : last_bytes;
+  }
+
+  Status ValidateHeader() {
+    std::array<std::byte, AesGcmStream::kHeaderLength> header{};
+    ICEBERG_RETURN_UNEXPECTED(source_->ReadFully(0, header));
+    if (std::memcmp(header.data(), AesGcmStream::kMagic.data(),
+                    AesGcmStream::kMagic.size()) != 0) {
+      return Invalid("Invalid GCM stream: magic does not match AGS1");
+    }
+    uint32_t plain_block_size = 0;
+    for (int i = 0; i < 4; ++i) {
+      plain_block_size |= static_cast<uint32_t>(header[4 + i]) << (8 * i);
+    }
+    if (plain_block_size != 
static_cast<uint32_t>(AesGcmStream::kPlainBlockSize)) {
+      return Invalid("Invalid GCM stream: block size {} != {}", 
plain_block_size,
+                     AesGcmStream::kPlainBlockSize);
+    }
+    return {};
+  }
+
+  Result<int64_t> Position() const override { return position_; }
+
+  Status Seek(int64_t position) override {
+    if (position < 0 || position > plain_size_) {
+      return IOError("Invalid position {} for stream of length {}", position,
+                     plain_size_);
+    }
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    int64_t total = 0;
+    while (std::cmp_less(total, out.size()) && position_ < plain_size_) {
+      int64_t block_index = position_ / kPlainBlock;
+      ICEBERG_RETURN_UNEXPECTED(DecryptBlock(block_index));
+      int64_t offset = position_ % kPlainBlock;
+      int64_t n = std::min<int64_t>(current_block_size_ - offset,
+                                    static_cast<int64_t>(out.size()) - total);
+      std::memcpy(out.data() + total, plain_block_.data() + offset, n);
+      total += n;
+      position_ += n;
+    }
+    return total;
+  }
+
+  Status ReadFully(int64_t position, std::span<std::byte> out) override {
+    if (position < 0 || position + static_cast<int64_t>(out.size()) > 
plain_size_) {

Review Comment:
   This range check can still signed-overflow: ReadFully(INT64_MAX, 
a_one_byte_buffer) evaluates INT64_MAX + 1 before Seek rejects the position. 
Check position against plain_size_ first, then compare out.size() with 
plain_size_ - position, or use checked addition. Please add this small-buffer 
boundary case.



##########
src/iceberg/encryption/aes_gcm_stream.h:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+/// \file iceberg/encryption/aes_gcm_stream.h
+/// AES GCM Stream (AGS1) files, see format/gcm-stream-spec.md.
+
+#include <array>
+#include <cstdint>
+#include <memory>
+#include <span>
+#include <vector>
+
+#include "iceberg/file_io.h"
+#include "iceberg/iceberg_bundle_export.h"
+#include "iceberg/result.h"
+
+namespace iceberg {
+
+/// \brief AES GCM Stream format constants.
+struct AesGcmStream {
+  static constexpr int32_t kPlainBlockSize = 1024 * 1024;
+  static constexpr int32_t kNonceLength = 12;
+  static constexpr int32_t kGcmTagLength = 16;
+  static constexpr int32_t kCipherBlockSize =
+      kPlainBlockSize + kNonceLength + kGcmTagLength;
+  static constexpr std::array<char, 4> kMagic = {'A', 'G', 'S', '1'};
+  static constexpr int32_t kHeaderLength = 8;  // magic + plain block size (LE 
int32)
+  static constexpr int64_t kMinStreamLength =
+      kHeaderLength + kNonceLength + kGcmTagLength;
+
+  /// \brief Plaintext length of a stream with the given encrypted length.
+  ///
+  /// Returns an error if the length is shorter than an empty stream, implies 
more
+  /// than int32 max blocks, or ends in a block too short to hold a nonce and 
tag.
+  static Result<int64_t> PlaintextLength(int64_t encrypted_length);

Review Comment:
   Please export this out-of-line public method with ICEBERG_BUNDLE_EXPORT. 
Shared bundle targets use hidden visibility and explicit DLL exports on 
Windows, so a downstream call to AesGcmStream::PlaintextLength otherwise fails 
to link. The current static-first tests do not cover this.



##########
src/iceberg/encryption/aes_gcm_stream.cc:
##########
@@ -0,0 +1,351 @@
+/*
+ * 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.
+ */
+
+#include "iceberg/encryption/aes_gcm_stream.h"
+
+#include <algorithm>
+#include <array>
+#include <cstring>
+#include <limits>
+#include <utility>
+
+#include "iceberg/encryption/aes_gcm_internal.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg {
+
+namespace {
+
+using encryption::AesGcmCipher;
+
+constexpr int64_t kPlainBlock = AesGcmStream::kPlainBlockSize;
+constexpr int64_t kCipherBlock = AesGcmStream::kCipherBlockSize;
+constexpr int64_t kBlockOverhead =
+    AesGcmStream::kNonceLength + AesGcmStream::kGcmTagLength;
+
+/// \brief Block AAD: file AAD prefix followed by the block index as a 4-byte 
LE int.
+std::vector<uint8_t> BlockAad(const std::vector<uint8_t>& aad_prefix,
+                              int32_t block_index) {
+  std::vector<uint8_t> aad(aad_prefix);
+  for (int i = 0; i < 4; ++i) {
+    aad.push_back(
+        static_cast<uint8_t>((static_cast<uint32_t>(block_index) >> (8 * i)) & 
0xFF));
+  }
+  return aad;
+}
+
+std::array<std::byte, AesGcmStream::kHeaderLength> HeaderBytes() {
+  std::array<std::byte, AesGcmStream::kHeaderLength> header{};
+  std::memcpy(header.data(), AesGcmStream::kMagic.data(), 
AesGcmStream::kMagic.size());
+  for (int i = 0; i < 4; ++i) {
+    header[4 + i] = static_cast<std::byte>(
+        (static_cast<uint32_t>(AesGcmStream::kPlainBlockSize) >> (8 * i)) & 
0xFF);
+  }
+  return header;
+}
+
+class AesGcmInputStream : public SeekableInputStream {
+ public:
+  /// \brief Construct over an encrypted length already accepted by
+  /// AesGcmStream::PlaintextLength, which bounds the block count.
+  AesGcmInputStream(std::unique_ptr<SeekableInputStream> source,
+                    std::unique_ptr<AesGcmCipher> cipher, std::vector<uint8_t> 
aad_prefix,
+                    int64_t encrypted_length, int64_t plain_size)
+      : source_(std::move(source)),
+        cipher_(std::move(cipher)),
+        aad_prefix_(std::move(aad_prefix)),
+        cipher_block_(kCipherBlock),
+        plain_block_(kPlainBlock),
+        plain_size_(plain_size) {
+    int64_t stream_length = encrypted_length - AesGcmStream::kHeaderLength;
+    int64_t num_full_blocks = stream_length / kCipherBlock;
+    int64_t last_bytes = stream_length - num_full_blocks * kCipherBlock;
+    bool full_blocks_only = last_bytes == 0;
+    num_blocks_ = full_blocks_only ? num_full_blocks : num_full_blocks + 1;
+    last_cipher_block_size_ = full_blocks_only ? kCipherBlock : last_bytes;
+  }
+
+  Status ValidateHeader() {
+    std::array<std::byte, AesGcmStream::kHeaderLength> header{};
+    ICEBERG_RETURN_UNEXPECTED(source_->ReadFully(0, header));
+    if (std::memcmp(header.data(), AesGcmStream::kMagic.data(),
+                    AesGcmStream::kMagic.size()) != 0) {
+      return Invalid("Invalid GCM stream: magic does not match AGS1");
+    }
+    uint32_t plain_block_size = 0;
+    for (int i = 0; i < 4; ++i) {
+      plain_block_size |= static_cast<uint32_t>(header[4 + i]) << (8 * i);
+    }
+    if (plain_block_size != 
static_cast<uint32_t>(AesGcmStream::kPlainBlockSize)) {
+      return Invalid("Invalid GCM stream: block size {} != {}", 
plain_block_size,
+                     AesGcmStream::kPlainBlockSize);
+    }
+    return {};
+  }
+
+  Result<int64_t> Position() const override { return position_; }
+
+  Status Seek(int64_t position) override {
+    if (position < 0 || position > plain_size_) {
+      return IOError("Invalid position {} for stream of length {}", position,
+                     plain_size_);
+    }
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    int64_t total = 0;
+    while (std::cmp_less(total, out.size()) && position_ < plain_size_) {

Review Comment:
   Please authenticate the sole block of an empty AGS1 stream before reporting 
EOF. With plain_size_ == 0, this loop never calls DecryptBlock, so a wrong 
key/AAD, a corrupted tag, or a file truncated to just its header is accepted as 
an empty file. Java's testEmptyFile explicitly checks this; please add the same 
negative cases here.



-- 
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