diff --git a/dev/release/rat_exclude_files.txt b/dev/release/rat_exclude_files.txt index 7b5b3b10c8..07afcd6df2 100644 --- a/dev/release/rat_exclude_files.txt +++ b/dev/release/rat_exclude_files.txt @@ -27,3 +27,4 @@ requirements.txt test/resources/** *.json src/iceberg/util/murmurhash3_internal.* +src/iceberg/test/resources/encryption/** diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 71c7a40186..f9604e2575 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -33,6 +33,8 @@ set(ICEBERG_SOURCES deletes/position_delete_index.cc deletes/position_delete_range_consumer.cc deletes/roaring_position_bitmap.cc + encryption/encrypted_files.cc + encryption/encryption_manager.cc encryption/key_management_client.cc encryption/standard_key_metadata.cc expression/aggregate.cc @@ -337,6 +339,7 @@ if(ICEBERG_BUILD_BUNDLE) avro/avro_register.cc avro/avro_schema_util.cc avro/avro_stream_internal.cc + encryption/encryption_register.cc parquet/parquet_bloom_row_group_filter.cc parquet/parquet_data_util.cc parquet/parquet_dictionary_row_group_filter.cc @@ -354,7 +357,9 @@ if(ICEBERG_BUILD_BUNDLE) ICEBERG_BUNDLE_SOURCES encryption/aes_gcm.cc encryption/aes_gcm_stream.cc - encryption/in_memory_kms.cc) + encryption/encryption_util.cc + encryption/in_memory_kms.cc + encryption/standard_encryption_manager.cc) endif() # Libraries to link with exported libiceberg_bundle.{so,a}. @@ -429,6 +434,11 @@ if(ICEBERG_BUILD_BUNDLE) foreach(target iceberg_bundle_static iceberg_bundle_shared) if(TARGET ${target}) + if(ICEBERG_ENCRYPTION) + target_compile_definitions(${target} PRIVATE ICEBERG_ENCRYPTION_ENABLED=1) + else() + target_compile_definitions(${target} PRIVATE ICEBERG_ENCRYPTION_ENABLED=0) + endif() if(ICEBERG_S3) target_compile_definitions(${target} PUBLIC "$") diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 5c2115c21c..93d716e950 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -49,9 +49,14 @@ #include "iceberg/deletes/position_delete_index.h" #include "iceberg/deletes/position_delete_range_consumer.h" #include "iceberg/deletes/roaring_position_bitmap.h" +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encrypted_files.h" #include "iceberg/encryption/encrypted_key.h" +#include "iceberg/encryption/encryption_key_metadata.h" +#include "iceberg/encryption/encryption_manager.h" #include "iceberg/encryption/key_management_client.h" #include "iceberg/encryption/standard_key_metadata.h" +#include "iceberg/encryption/type_fwd.h" #include "iceberg/exception.h" #include "iceberg/expression/aggregate.h" #include "iceberg/expression/binder.h" @@ -222,6 +227,7 @@ # include "iceberg/avro/avro_reader.h" # include "iceberg/avro/avro_register.h" # include "iceberg/avro/avro_writer.h" +# include "iceberg/encryption/encryption_register.h" # include "iceberg/parquet/parquet_reader.h" # include "iceberg/parquet/parquet_register.h" # include "iceberg/parquet/parquet_writer.h" @@ -229,7 +235,9 @@ #ifdef ICEBERG_PUBLIC_HEADERS_ENCRYPTION # include "iceberg/encryption/aes_gcm_stream.h" +# include "iceberg/encryption/encryption_util.h" # include "iceberg/encryption/in_memory_kms.h" +# include "iceberg/encryption/standard_encryption_manager.h" #endif // ICEBERG_PUBLIC_HEADERS_ENCRYPTION #ifdef ICEBERG_PUBLIC_HEADERS_HIVE diff --git a/src/iceberg/encryption/CMakeLists.txt b/src/iceberg/encryption/CMakeLists.txt index c490aa79ca..6b48efbc2d 100644 --- a/src/iceberg/encryption/CMakeLists.txt +++ b/src/iceberg/encryption/CMakeLists.txt @@ -17,14 +17,28 @@ iceberg_install_all_headers(iceberg/encryption PATTERN + encrypted_file.h + encrypted_files.h encrypted_key.h + encryption_key_metadata.h + encryption_manager.h key_management_client.h - standard_key_metadata.h) -if(ICEBERG_BUILD_BUNDLE AND ICEBERG_ENCRYPTION) + standard_key_metadata.h + type_fwd.h) +if(ICEBERG_BUILD_BUNDLE) iceberg_install_all_headers(iceberg/encryption PATTERN - aes_gcm_stream.h - in_memory_kms.h + encryption_register.h HEADER_GROUP - ICEBERG_PUBLIC_HEADERS_ENCRYPTION) + ICEBERG_PUBLIC_HEADERS_BUNDLE) + if(ICEBERG_ENCRYPTION) + iceberg_install_all_headers(iceberg/encryption + PATTERN + aes_gcm_stream.h + encryption_util.h + in_memory_kms.h + standard_encryption_manager.h + HEADER_GROUP + ICEBERG_PUBLIC_HEADERS_ENCRYPTION) + endif() endif() diff --git a/src/iceberg/encryption/aes_gcm_internal.h b/src/iceberg/encryption/aes_gcm_internal.h index e09a7802e7..1e35ffc6f8 100644 --- a/src/iceberg/encryption/aes_gcm_internal.h +++ b/src/iceberg/encryption/aes_gcm_internal.h @@ -22,18 +22,32 @@ /// \file iceberg/encryption/aes_gcm_internal.h /// AES GCM cipher compatible with Java's org.apache.iceberg.encryption.Ciphers. +#include #include #include #include #include #include "iceberg/result.h" +#include "iceberg/type_fwd.h" namespace iceberg::encryption { inline constexpr int32_t kNonceLength = 12; inline constexpr int32_t kGcmTagLength = 16; +inline constexpr bool IsValidAesKeyLength(std::size_t length) { + return length == 16 || length == 24 || length == 32; +} + +Result AesGcmPlaintextLength(std::span key, + int64_t encrypted_length); + +/// \brief Open an AGS1 stream that owns its underlying stream. +Result> OpenAesGcmInputStream( + InputFile& source, std::span key, std::span aad_prefix, + int64_t encrypted_length); + /// \brief Fill `out` with cryptographically secure random bytes. Status SecureRandomBytes(std::span out); diff --git a/src/iceberg/encryption/aes_gcm_stream.cc b/src/iceberg/encryption/aes_gcm_stream.cc index 7fb545dbf9..fb4b9be447 100644 --- a/src/iceberg/encryption/aes_gcm_stream.cc +++ b/src/iceberg/encryption/aes_gcm_stream.cc @@ -320,29 +320,72 @@ Result AesGcmStream::PlaintextLength(int64_t encrypted_length) { return num_full_blocks * kPlainBlockSize + last_plain; } +namespace encryption { + +Result AesGcmPlaintextLength(std::span key, + int64_t encrypted_length) { + ICEBERG_PRECHECK(IsValidAesKeyLength(key.size()), + "Invalid encryption key length: {} (must be 16, 24 or 32 bytes)", + key.size()); + return AesGcmStream::PlaintextLength(encrypted_length); +} + +Result> OpenAesGcmInputStream( + InputFile& source, std::span key, std::span aad_prefix, + int64_t encrypted_length) { + ICEBERG_ASSIGN_OR_RAISE(auto plaintext_length, + AesGcmPlaintextLength(key, encrypted_length)); + ICEBERG_ASSIGN_OR_RAISE(auto cipher, AesGcmCipher::Make(key)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, source.Open()); + auto decrypted = std::make_unique( + std::move(stream), std::move(cipher), + std::vector(aad_prefix.begin(), aad_prefix.end()), encrypted_length, + plaintext_length); + ICEBERG_RETURN_UNEXPECTED(decrypted->ValidateHeader()); + ICEBERG_RETURN_UNEXPECTED(decrypted->ValidateEmptyStream()); + return decrypted; +} + +} // namespace encryption + +Result> AesGcmInputFile::Make( + std::unique_ptr source, std::span key, + std::span aad_prefix, int64_t encrypted_length) { + ICEBERG_PRECHECK(source != nullptr, "Encrypted input file cannot be null"); + ICEBERG_ASSIGN_OR_RAISE(auto plaintext_length, + encryption::AesGcmPlaintextLength(key, encrypted_length)); + return std::unique_ptr(new AesGcmInputFile( + std::move(source), {key.begin(), key.end()}, {aad_prefix.begin(), aad_prefix.end()}, + encrypted_length, plaintext_length)); +} + AesGcmInputFile::AesGcmInputFile(std::unique_ptr source, std::vector key, std::vector aad_prefix, - int64_t encrypted_length) + int64_t encrypted_length, int64_t plaintext_length) : source_(std::move(source)), key_(std::move(key)), aad_prefix_(std::move(aad_prefix)), - encrypted_length_(encrypted_length) {} + encrypted_length_(encrypted_length), + plaintext_length_(plaintext_length) {} -Result AesGcmInputFile::Size() const { - return AesGcmStream::PlaintextLength(encrypted_length_); -} +Result AesGcmInputFile::Size() const { return plaintext_length_; } Result> AesGcmInputFile::Open() { - ICEBERG_ASSIGN_OR_RAISE(auto plain_size, - AesGcmStream::PlaintextLength(encrypted_length_)); - ICEBERG_ASSIGN_OR_RAISE(auto cipher, AesGcmCipher::Make(key_)); - ICEBERG_ASSIGN_OR_RAISE(auto source, source_->Open()); - auto stream = std::make_unique( - std::move(source), std::move(cipher), aad_prefix_, encrypted_length_, plain_size); - ICEBERG_RETURN_UNEXPECTED(stream->ValidateHeader()); - ICEBERG_RETURN_UNEXPECTED(stream->ValidateEmptyStream()); - return stream; + return encryption::OpenAesGcmInputStream(*source_, key_, aad_prefix_, + encrypted_length_); +} + +Result> AesGcmOutputFile::Make( + std::unique_ptr target, std::span key, + std::span aad_prefix) { + ICEBERG_PRECHECK(target != nullptr, "Output file cannot be null"); + ICEBERG_PRECHECK(encryption::IsValidAesKeyLength(key.size()), + "Invalid encryption key length: {} (must be 16, 24 or 32 bytes)", + key.size()); + return std::unique_ptr( + new AesGcmOutputFile(std::move(target), {key.begin(), key.end()}, + {aad_prefix.begin(), aad_prefix.end()})); } AesGcmOutputFile::AesGcmOutputFile(std::unique_ptr target, diff --git a/src/iceberg/encryption/aes_gcm_stream.h b/src/iceberg/encryption/aes_gcm_stream.h index 766eb85eb4..8675425024 100644 --- a/src/iceberg/encryption/aes_gcm_stream.h +++ b/src/iceberg/encryption/aes_gcm_stream.h @@ -66,31 +66,41 @@ struct AesGcmStream { /// truncation of the file is detected. class ICEBERG_BUNDLE_EXPORT AesGcmInputFile : public InputFile { public: - AesGcmInputFile(std::unique_ptr source, std::vector key, - std::vector aad_prefix, int64_t encrypted_length); + static Result> Make( + std::unique_ptr source, std::span key, + std::span aad_prefix, int64_t encrypted_length); std::string_view location() const override { return source_->location(); } Result Size() const override; Result> Open() override; private: + AesGcmInputFile(std::unique_ptr source, std::vector key, + std::vector aad_prefix, int64_t encrypted_length, + int64_t plaintext_length); + std::unique_ptr source_; std::vector key_; std::vector aad_prefix_; int64_t encrypted_length_; + int64_t plaintext_length_; }; /// \brief An OutputFile that writes an AGS1 file. class ICEBERG_BUNDLE_EXPORT AesGcmOutputFile : public OutputFile { public: - AesGcmOutputFile(std::unique_ptr target, std::vector key, - std::vector aad_prefix); + static Result> Make( + std::unique_ptr target, std::span key, + std::span aad_prefix); std::string_view location() const override { return target_->location(); } Result> Create() override; Result> CreateOrOverwrite() override; private: + AesGcmOutputFile(std::unique_ptr target, std::vector key, + std::vector aad_prefix); + std::unique_ptr target_; std::vector key_; std::vector aad_prefix_; diff --git a/src/iceberg/encryption/encrypted_file.h b/src/iceberg/encryption/encrypted_file.h new file mode 100644 index 0000000000..e5e514d539 --- /dev/null +++ b/src/iceberg/encryption/encrypted_file.h @@ -0,0 +1,121 @@ +/* + * 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/encrypted_file.h +/// Pairs a file handle with its key metadata, mirroring Java's +/// EncryptedInputFile / EncryptedOutputFile. + +#include + +#include "iceberg/encryption/encryption_key_metadata.h" +#include "iceberg/encryption/type_fwd.h" +#include "iceberg/file_io.h" +#include "iceberg/iceberg_export.h" + +namespace iceberg { + +/// \brief An encrypted input file together with the key metadata needed to decrypt it. +class ICEBERG_EXPORT EncryptedInputFile { + public: + virtual ~EncryptedInputFile() = default; + + /// \brief Take ownership of a native wrapper, or leave encrypted intact and return + /// null. + static std::unique_ptr AsNative( + std::unique_ptr& encrypted); + + /// \brief Transfer ownership of the still-encrypted raw input file. + /// + /// Returns nullptr if the wrapper has no file. Use the returned handle for file access + /// after detaching. + virtual std::unique_ptr DetachInputFile() && = 0; + + /// \brief The key metadata needed to decrypt this file. + virtual const EncryptionKeyMetadata& key_metadata() const = 0; + + private: + virtual NativeEncryptionInputFile* native_input_file() noexcept { return nullptr; } +}; + +/// \brief An encrypted input file that supports both read paths of Java's +/// NativeEncryptionInputFile. +/// +/// - Native path, for formats such as Parquet that perform their own modular decryption: +/// key_metadata() gives the key parameters (and AAD prefix) the native reader needs. +/// DetachInputFile() then transfers the still-encrypted raw file. +/// - Stream path: the InputFile methods read the file as an AES GCM stream (AGS1), +/// decrypting it, and require the encrypted file length in the key metadata. +/// +/// Implementations may defer building the stream reader until the InputFile methods are +/// first used, so native-only callers are not subject to the stream path's requirements. +class ICEBERG_EXPORT NativeEncryptionInputFile : public EncryptedInputFile, + public InputFile { + public: + const NativeEncryptionKeyMetadata& key_metadata() const override = 0; + + private: + NativeEncryptionInputFile* native_input_file() noexcept final { return this; } +}; + +/// \brief An encrypting output file together with the key metadata that was used (or +/// will be used) to encrypt it. +class ICEBERG_EXPORT EncryptedOutputFile { + public: + virtual ~EncryptedOutputFile() = default; + + /// \brief Borrow the encrypting output file from this wrapper. + virtual OutputFile& encrypting_output_file() const = 0; + + /// \brief The key metadata that was used to encrypt this file. + virtual const EncryptionKeyMetadata& key_metadata() const = 0; +}; + +/// \brief An encrypting output file that supports both write paths of Java's +/// NativeEncryptionOutputFile. +/// +/// - Native path, for formats such as Parquet that perform their own modular encryption: +/// plain_output_file() gives the file to write the (already encrypted) bytes to and +/// key_metadata() gives the key parameters (and AAD prefix) the native writer needs. +/// - Stream path: encrypting_output_file(), and the OutputFile methods that delegate to +/// it, write the file as an AES GCM stream (AGS1). +class ICEBERG_EXPORT NativeEncryptionOutputFile : public EncryptedOutputFile, + public OutputFile { + public: + /// \brief The underlying plain output file, for native writers. + virtual OutputFile& plain_output_file() const = 0; + + const NativeEncryptionKeyMetadata& key_metadata() const override = 0; + + // OutputFile, delegating to the stream path. + std::string_view location() const override { + return encrypting_output_file().location(); + } + + Result> Create() override { + return encrypting_output_file().Create(); + } + + Result> CreateOrOverwrite() override { + return encrypting_output_file().CreateOrOverwrite(); + } +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/encrypted_files.cc b/src/iceberg/encryption/encrypted_files.cc new file mode 100644 index 0000000000..7188ae90e7 --- /dev/null +++ b/src/iceberg/encryption/encrypted_files.cc @@ -0,0 +1,108 @@ +/* + * 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/encrypted_files.h" + +#include + +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/util/macros.h" + +namespace iceberg { + +namespace { + +class BaseEncryptedInputFile final : public EncryptedInputFile { + public: + static Result> Make( + std::unique_ptr encrypted_input_file, + std::shared_ptr key_metadata) { + ICEBERG_PRECHECK(encrypted_input_file != nullptr, + "Encrypted input file cannot be null"); + ICEBERG_PRECHECK(key_metadata != nullptr, "Key metadata cannot be null"); + return std::unique_ptr(new BaseEncryptedInputFile( + std::move(encrypted_input_file), std::move(key_metadata))); + } + + std::unique_ptr DetachInputFile() && override { + return std::move(encrypted_input_file_); + } + + const EncryptionKeyMetadata& key_metadata() const override { return *key_metadata_; } + + private: + BaseEncryptedInputFile(std::unique_ptr encrypted_input_file, + std::shared_ptr key_metadata) + : encrypted_input_file_(std::move(encrypted_input_file)), + key_metadata_(std::move(key_metadata)) {} + + std::unique_ptr encrypted_input_file_; + std::shared_ptr key_metadata_; +}; + +class BaseEncryptedOutputFile final : public EncryptedOutputFile { + public: + static Result> Make( + std::unique_ptr encrypting_output_file, + std::shared_ptr key_metadata) { + ICEBERG_PRECHECK(encrypting_output_file != nullptr, "Output file cannot be null"); + ICEBERG_PRECHECK(key_metadata != nullptr, "Key metadata cannot be null"); + return std::unique_ptr(new BaseEncryptedOutputFile( + std::move(encrypting_output_file), std::move(key_metadata))); + } + + OutputFile& encrypting_output_file() const override { return *encrypting_output_file_; } + const EncryptionKeyMetadata& key_metadata() const override { return *key_metadata_; } + + private: + BaseEncryptedOutputFile(std::unique_ptr encrypting_output_file, + std::shared_ptr key_metadata) + : encrypting_output_file_(std::move(encrypting_output_file)), + key_metadata_(std::move(key_metadata)) {} + + std::unique_ptr encrypting_output_file_; + std::shared_ptr key_metadata_; +}; + +} // namespace + +std::unique_ptr EncryptedInputFile::AsNative( + std::unique_ptr& encrypted) { + auto* native = encrypted ? encrypted->native_input_file() : nullptr; + if (native != nullptr) { + encrypted.release(); + } + return std::unique_ptr(native); +} + +Result> EncryptedFiles::EncryptedInput( + std::unique_ptr encrypted_input_file, + std::shared_ptr key_metadata) { + return BaseEncryptedInputFile::Make(std::move(encrypted_input_file), + std::move(key_metadata)); +} + +Result> EncryptedFiles::EncryptedOutput( + std::unique_ptr encrypting_output_file, + std::shared_ptr key_metadata) { + return BaseEncryptedOutputFile::Make(std::move(encrypting_output_file), + std::move(key_metadata)); +} + +} // namespace iceberg diff --git a/src/iceberg/encryption/encrypted_files.h b/src/iceberg/encryption/encrypted_files.h new file mode 100644 index 0000000000..b81ddab6a5 --- /dev/null +++ b/src/iceberg/encryption/encrypted_files.h @@ -0,0 +1,51 @@ +/* + * 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/encrypted_files.h +/// Builds the generic EncryptedInputFile / EncryptedOutputFile wrappers that +/// EncryptionManager consumes and produces, mirroring Java's EncryptedFiles. + +#include + +#include "iceberg/encryption/type_fwd.h" +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +/// \brief Pairs existing input and output files with their key metadata. +class ICEBERG_EXPORT EncryptedFiles { + public: + /// \brief Wrap a still-encrypted input file together with its key metadata. + static Result> EncryptedInput( + std::unique_ptr encrypted_input_file, + std::shared_ptr key_metadata); + + /// \brief Pair an existing encrypting output file with its key metadata. + /// + /// To encrypt a plain output file, use EncryptionManager::Encrypt. + static Result> EncryptedOutput( + std::unique_ptr encrypting_output_file, + std::shared_ptr key_metadata); +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_key_metadata.h b/src/iceberg/encryption/encryption_key_metadata.h new file mode 100644 index 0000000000..82658a6cc1 --- /dev/null +++ b/src/iceberg/encryption/encryption_key_metadata.h @@ -0,0 +1,121 @@ +/* + * 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/encryption_key_metadata.h +/// Opaque, serialized key metadata, mirroring Java's EncryptionKeyMetadata. + +#include +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" + +namespace iceberg { + +/// \brief Opaque serialized key metadata for one file. +/// +/// Implementations are free to choose any serialization; EncryptionManager and its +/// callers treat the result as an opaque byte buffer. +class ICEBERG_EXPORT EncryptionKeyMetadata { + public: + virtual ~EncryptionKeyMetadata() = default; + + /// \brief Return an owning copy of the current serialized key metadata. + virtual std::vector buffer() const = 0; + + /// \brief Whether key metadata is present. + /// + /// Absent key metadata (as for unencrypted files) has an empty buffer(), but so can + /// present key metadata that is zero bytes long; this tells the two apart. + virtual bool has_value() const { return true; } + + /// \brief A copy of this key metadata. + virtual std::shared_ptr Copy() const = 0; +}; + +/// \brief EncryptionKeyMetadata backed by a fixed, already-serialized buffer. +/// +/// The buffer is optional so that absent key metadata (Empty(), as used for unencrypted +/// files) can be told apart from present key metadata that happens to be zero bytes long. +class ICEBERG_EXPORT BaseEncryptionKeyMetadata : public EncryptionKeyMetadata { + public: + /// \brief Key metadata with the given bytes; a zero-length buffer is still present. + explicit BaseEncryptionKeyMetadata(std::optional> buffer) + : buffer_(std::move(buffer)) {} + + /// \brief Absent key metadata. + static std::shared_ptr Empty() { + return std::make_shared(std::nullopt); + } + + /// \brief Whether key metadata is present, even if it is zero bytes long. + bool has_value() const override { return buffer_.has_value(); } + + /// \brief The key metadata bytes, or an empty buffer if absent. + std::vector buffer() const override { + return buffer_.value_or(std::vector{}); + } + + std::shared_ptr Copy() const override { + return std::make_shared(*this); + } + + private: + std::optional> buffer_; +}; + +/// \brief Key metadata for the native (AES-GCM) encryption key parameters. +/// +/// Exposes the data encryption key and AAD prefix directly, for formats (such as +/// Parquet) that perform their own native encryption rather than using the AGS1 stream +/// format. +/// Key and AAD views borrow storage from this object. +class ICEBERG_EXPORT NativeEncryptionKeyMetadata : public EncryptionKeyMetadata { + public: + /// \brief The data encryption key. + virtual std::span encryption_key() const = 0; + + /// \brief The AAD prefix (file ID) used to bind ciphertext to this file, if any. + virtual std::optional> aad_prefix() const = 0; + + /// \brief The encrypted (stored) file length, or nullopt if not yet known. + /// + /// Returns NotSupported unless the implementation tracks a file length. + virtual Result> file_length() const { + return NotSupported("file_length is not implemented by this key metadata"); + } + + /// \brief A copy of this key metadata, with the same key and AAD prefix, that records + /// the given encrypted file length. + /// + /// Writers call this after closing the file, once the stored length is known. Returns + /// NotSupported unless the implementation tracks a file length. + virtual Result> CopyWithLength( + int64_t length) const { + return NotSupported("CopyWithLength is not implemented by this key metadata"); + } +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_manager.cc b/src/iceberg/encryption/encryption_manager.cc new file mode 100644 index 0000000000..da1f701462 --- /dev/null +++ b/src/iceberg/encryption/encryption_manager.cc @@ -0,0 +1,124 @@ +/* + * 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/encryption_manager.h" + +#include +#include + +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encrypted_files.h" +#include "iceberg/encryption/encryption_manager_internal.h" +#include "iceberg/logging/log_macros.h" +#include "iceberg/util/macros.h" + +namespace iceberg { + +Result>> EncryptionManager::Decrypt( + std::vector> encrypted) { + std::vector> decrypted; + decrypted.reserve(encrypted.size()); + for (auto& file : encrypted) { + ICEBERG_ASSIGN_OR_RAISE(auto input_file, Decrypt(std::move(file))); + decrypted.push_back(std::move(input_file)); + } + return decrypted; +} + +Result>> EncryptionManager::Encrypt( + std::vector> plain) { + std::vector> encrypted; + encrypted.reserve(plain.size()); + for (auto& file : plain) { + ICEBERG_ASSIGN_OR_RAISE(auto encrypted_file, Encrypt(std::move(file))); + encrypted.push_back(std::move(encrypted_file)); + } + return encrypted; +} + +Result> PlaintextEncryptionManager::Decrypt( + std::unique_ptr encrypted) { + ICEBERG_PRECHECK(encrypted != nullptr, "Encrypted input file cannot be null"); + if (encrypted->key_metadata().has_value()) { + ICEBERG_LOG_WARN( + "File encryption key metadata is present, but no encryption has been " + "configured."); + } + auto input = std::move(*encrypted).DetachInputFile(); + ICEBERG_PRECHECK(input != nullptr, "Encrypted input file has no underlying file"); + return input; +} + +Result> PlaintextEncryptionManager::Encrypt( + std::unique_ptr plain) { + return EncryptedFiles::EncryptedOutput(std::move(plain), + BaseEncryptionKeyMetadata::Empty()); +} + +namespace { + +struct RegistryState { + std::mutex mutex; + EncryptionManagerRegistry::Factory factory; +}; + +RegistryState& State() { + static RegistryState state; + return state; +} + +} // namespace + +void EncryptionManagerRegistry::Register(Factory factory) { + auto& state = State(); + std::lock_guard lock(state.mutex); + state.factory.swap(factory); +} + +void internal::RegisterDefaultEncryptionManagerFactory( + EncryptionManagerRegistry::Factory factory) { + auto& state = State(); + std::lock_guard lock(state.mutex); + if (!state.factory) { + state.factory.swap(factory); + } +} + +Result> EncryptionManagerRegistry::Make( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client) { + Factory factory; + { + auto& state = State(); + std::lock_guard lock(state.mutex); + factory = state.factory; + } + if (!factory) { + return NotSupported( + "No encryption manager factory registered. For standard encryption, link " + "iceberg_bundle built with ICEBERG_ENCRYPTION=ON and call " + "iceberg::encryption::RegisterAll()"); + } + ICEBERG_ASSIGN_OR_RAISE(auto manager, + factory(keys, table_properties, std::move(kms_client))); + ICEBERG_PRECHECK(manager != nullptr, "Encryption manager factory returned null"); + return manager; +} + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_manager.h b/src/iceberg/encryption/encryption_manager.h new file mode 100644 index 0000000000..41422e1f5d --- /dev/null +++ b/src/iceberg/encryption/encryption_manager.h @@ -0,0 +1,106 @@ +/* + * 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/encryption_manager.h +/// Table encryption manager interface and the registry that creates one. + +#include +#include +#include + +#include "iceberg/encryption/type_fwd.h" +#include "iceberg/iceberg_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +/// \brief Encrypts and decrypts the files of one table. +/// +/// This interface does not require a particular key metadata encoding or encryption +/// algorithm; those are the business of the specific implementation (such as +/// StandardEncryptionManager, which needs a crypto provider and lives in the bundle +/// library). EncryptedFiles builds the EncryptedInputFile / EncryptedOutputFile +/// wrappers. The core library reaches the standard implementation through +/// EncryptionManagerRegistry. +class ICEBERG_EXPORT EncryptionManager { + public: + virtual ~EncryptionManager() = default; + + /// \brief Decrypt a file, given its raw bytes and key metadata. + virtual Result> Decrypt( + std::unique_ptr encrypted) = 0; + + /// \brief Wrap a plaintext output file so that it, and its key metadata, can be + /// produced once writing is complete. + virtual Result> Encrypt( + std::unique_ptr plain) = 0; + + /// \brief Batch variant of Decrypt(std::unique_ptr). + /// + /// The default implementation decrypts each file in order; implementations may + /// override it to decrypt more efficiently, for example by batching KMS calls. + /// TODO(encryption): Support lazy batches with Stream so callers can consume files on + /// demand. + virtual Result>> Decrypt( + std::vector> encrypted); + + /// \brief Batch variant of Encrypt(std::unique_ptr). + virtual Result>> Encrypt( + std::vector> plain); +}; + +/// \brief An EncryptionManager for unencrypted tables; wraps files without encrypting +/// them. +class ICEBERG_EXPORT PlaintextEncryptionManager : public EncryptionManager { + public: + // Keep the batch overloads visible: overriding the single-file ones would hide them. + using EncryptionManager::Decrypt; + using EncryptionManager::Encrypt; + + Result> Decrypt( + std::unique_ptr encrypted) override; + + Result> Encrypt( + std::unique_ptr plain) override; +}; + +/// \brief Creates the encryption manager of encrypted tables. +/// +/// The bundle library supplies the standard implementation as a default (see +/// iceberg::encryption::RegisterAll()). An explicitly registered factory takes +/// precedence. Each factory validates its own properties. +class ICEBERG_EXPORT EncryptionManagerRegistry { + public: + using Factory = std::function>( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client)>; + + /// \brief Replace the current factory, or clear it by passing an empty factory. + static void Register(Factory factory); + + /// \brief Create an encryption manager. + static Result> Make( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client); +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_manager_internal.h b/src/iceberg/encryption/encryption_manager_internal.h new file mode 100644 index 0000000000..2f9d16616d --- /dev/null +++ b/src/iceberg/encryption/encryption_manager_internal.h @@ -0,0 +1,31 @@ +/* + * 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 + +#include "iceberg/encryption/encryption_manager.h" +#include "iceberg/iceberg_export.h" + +namespace iceberg::internal { + +/// \brief Install the bundle's default factory if the registry is empty. +ICEBERG_EXPORT void RegisterDefaultEncryptionManagerFactory( + EncryptionManagerRegistry::Factory factory); + +} // namespace iceberg::internal diff --git a/src/iceberg/encryption/encryption_register.cc b/src/iceberg/encryption/encryption_register.cc new file mode 100644 index 0000000000..2bb2560510 --- /dev/null +++ b/src/iceberg/encryption/encryption_register.cc @@ -0,0 +1,36 @@ +/* + * 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/encryption_register.h" + +namespace iceberg::encryption { + +#if ICEBERG_ENCRYPTION_ENABLED +void RegisterStandardEncryptionManager(); +#endif + +void RegisterAll() { +#if ICEBERG_ENCRYPTION_ENABLED + RegisterStandardEncryptionManager(); +#endif +} + +bool IsEncryptionAvailable() { return ICEBERG_ENCRYPTION_ENABLED; } + +} // namespace iceberg::encryption diff --git a/src/iceberg/encryption/encryption_register.h b/src/iceberg/encryption/encryption_register.h new file mode 100644 index 0000000000..c8f0cc26fa --- /dev/null +++ b/src/iceberg/encryption/encryption_register.h @@ -0,0 +1,36 @@ +/* + * 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/encryption_register.h +/// Registration of the table encryption implementation of the bundle library. + +#include "iceberg/iceberg_bundle_export.h" + +namespace iceberg::encryption { + +/// \brief Register the standard factory if encryption is enabled in the bundle and +/// the registry is empty. +ICEBERG_BUNDLE_EXPORT void RegisterAll(); + +/// \brief Whether the bundle was built with table encryption support. +ICEBERG_BUNDLE_EXPORT bool IsEncryptionAvailable(); + +} // namespace iceberg::encryption diff --git a/src/iceberg/encryption/encryption_util.cc b/src/iceberg/encryption/encryption_util.cc new file mode 100644 index 0000000000..93f09f30ca --- /dev/null +++ b/src/iceberg/encryption/encryption_util.cc @@ -0,0 +1,56 @@ +/* + * 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/encryption_util.h" + +#include + +#include "iceberg/encryption/encryption_manager.h" +#include "iceberg/encryption/standard_encryption_manager.h" +#include "iceberg/table_properties.h" +#include "iceberg/util/macros.h" + +namespace iceberg { + +Result> EncryptionUtil::MakeEncryptionManager( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client) { + ICEBERG_PRECHECK(kms_client != nullptr, "Invalid KMS client: null"); + const auto& properties = table_properties.configs(); + auto key_id = properties.find(TableProperties::kEncryptionTableKey.key()); + if (key_id == properties.end()) { + static const auto plaintext = std::make_shared(); + return plaintext; + } + ICEBERG_PRECHECK(!key_id->second.empty(), "Invalid encryption key ID: empty"); + return EncryptionManagerRegistry::Make(keys, table_properties, std::move(kms_client)); +} + +Result> EncryptionUtil::DecryptManifestListKeyMetadata( + const std::shared_ptr& manager, + std::string_view manifest_list_key_id) { + auto* standard = dynamic_cast(manager.get()); + if (standard == nullptr) { + return NotSupported( + "Manifest list key metadata decryption requires StandardEncryptionManager"); + } + return standard->DecryptManifestListKeyMetadata(manifest_list_key_id); +} + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_util.h b/src/iceberg/encryption/encryption_util.h new file mode 100644 index 0000000000..8e846fc0f4 --- /dev/null +++ b/src/iceberg/encryption/encryption_util.h @@ -0,0 +1,58 @@ +/* + * 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/encryption_util.h +/// Helpers that reach standard-specific encryption operations through the generic +/// EncryptionManager interface, mirroring Java's EncryptionUtil. + +#include +#include +#include +#include + +#include "iceberg/encryption/type_fwd.h" +#include "iceberg/iceberg_bundle_export.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" + +namespace iceberg { + +/// \brief Manager construction and standard-specific operations. +class ICEBERG_BUNDLE_EXPORT EncryptionUtil { + public: + /// \brief Select plaintext for an unencrypted table, or the registered factory when + /// the table has an encryption key ID. + /// + /// Requires a KMS client even for unencrypted tables. The table key ID must come + /// from a trusted source, such as the catalog. + static Result> MakeEncryptionManager( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client); + + /// \brief Decrypt the manifest list key metadata referenced by a snapshot's `key-id`. + /// + /// Fails with NotSupported if manager is not backed by StandardEncryptionManager. + static Result> DecryptManifestListKeyMetadata( + const std::shared_ptr& manager, + std::string_view manifest_list_key_id); +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/in_memory_kms.cc b/src/iceberg/encryption/in_memory_kms.cc index 31e1eedb7b..30a3f54045 100644 --- a/src/iceberg/encryption/in_memory_kms.cc +++ b/src/iceberg/encryption/in_memory_kms.cc @@ -19,16 +19,33 @@ #include "iceberg/encryption/in_memory_kms.h" +#include + #include "iceberg/encryption/aes_gcm_internal.h" #include "iceberg/util/base64.h" #include "iceberg/util/macros.h" namespace iceberg { +Result> InMemoryKms::Make( + std::unordered_map> master_keys) { + for (const auto& [id, key] : master_keys) { + ICEBERG_PRECHECK(!id.empty(), "Master key ID cannot be empty"); + ICEBERG_PRECHECK(encryption::IsValidAesKeyLength(key.size()), + "Master key {} must be 16, 24 or 32 bytes, got {}", id, key.size()); + } + return std::unique_ptr(new InMemoryKms(std::move(master_keys))); +} + +InMemoryKms::InMemoryKms( + std::unordered_map> master_keys) + : master_keys_(std::move(master_keys)) {} + void InMemoryKms::Register() { KmsRegistry::Register(std::string(kName), []() -> Result> { - return std::make_unique(); + ICEBERG_ASSIGN_OR_RAISE(auto kms, Make()); + return kms; }); } @@ -44,7 +61,7 @@ Status InMemoryKms::Initialize( auto id = name.substr(kKeyPropertyPrefix.size()); ICEBERG_PRECHECK(!id.empty(), "Master key property {} has an empty key id", name); ICEBERG_ASSIGN_OR_RAISE(auto key, Base64::Decode(value)); - ICEBERG_PRECHECK(key.size() == 16 || key.size() == 24 || key.size() == 32, + ICEBERG_PRECHECK(encryption::IsValidAesKeyLength(key.size()), "Master key {} must be 16, 24 or 32 bytes, got {}", name, key.size()); decoded.insert_or_assign(std::move(id), std::vector(key.begin(), key.end())); diff --git a/src/iceberg/encryption/in_memory_kms.h b/src/iceberg/encryption/in_memory_kms.h index b97025cac4..2c5fd81632 100644 --- a/src/iceberg/encryption/in_memory_kms.h +++ b/src/iceberg/encryption/in_memory_kms.h @@ -23,6 +23,7 @@ /// KMS client with master keys held in memory, for tests and local development. #include +#include #include #include #include @@ -41,15 +42,14 @@ namespace iceberg { /// without AAD. class ICEBERG_BUNDLE_EXPORT InMemoryKms : public KeyManagementClient { public: - /// \brief The name used with `encryption.kms-impl` after RegisterInMemoryKms(). + /// \brief The name used with `encryption.kms-impl` after Register(). static constexpr std::string_view kName = "in-memory"; /// \brief Catalog property prefix for master keys: `encryption.in-memory-kms.key.` /// = Base64 of the key bytes. static constexpr std::string_view kKeyPropertyPrefix = "encryption.in-memory-kms.key."; - InMemoryKms() = default; - explicit InMemoryKms(std::unordered_map> master_keys) - : master_keys_(std::move(master_keys)) {} + static Result> Make( + std::unordered_map> master_keys = {}); /// \brief Register this client in KmsRegistry under kName. static void Register(); @@ -64,6 +64,8 @@ class ICEBERG_BUNDLE_EXPORT InMemoryKms : public KeyManagementClient { std::string_view wrapping_key_id) override; private: + explicit InMemoryKms(std::unordered_map> master_keys); + Result*> MasterKey(std::string_view id) const; std::unordered_map> master_keys_; diff --git a/src/iceberg/encryption/standard_encryption_manager.cc b/src/iceberg/encryption/standard_encryption_manager.cc new file mode 100644 index 0000000000..9f62189aab --- /dev/null +++ b/src/iceberg/encryption/standard_encryption_manager.cc @@ -0,0 +1,368 @@ +/* + * 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/standard_encryption_manager.h" + +#include +#include +#include + +#include "iceberg/encryption/aes_gcm_internal.h" +#include "iceberg/encryption/aes_gcm_stream.h" +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encryption_manager_internal.h" +#include "iceberg/encryption/key_management_client.h" +#include "iceberg/encryption/standard_key_metadata.h" +#include "iceberg/table_properties.h" +#include "iceberg/util/base64.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/string_util.h" + +namespace iceberg { + +namespace { + +using encryption::AesGcmCipher; +using encryption::SecureRandomBytes; + +std::span AsBytes(std::string_view s) { + return {reinterpret_cast(s.data()), s.size()}; +} + +std::string ToString(std::span bytes) { + return {reinterpret_cast(bytes.data()), bytes.size()}; +} + +Result GenerateKeyId() { + std::array id{}; + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(id)); + return Base64::Encode(ToString(id)); +} + +Result ParseTimestamp(const EncryptedKey& key) { + auto it = key.properties.find(std::string(StandardEncryptionManager::kKeyTimestamp)); + if (it == key.properties.end()) { + return Invalid("Key encryption key {} must be timestamped", key.key_id); + } + int64_t value = 0; + const auto& str = it->second; + auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value); + if (ec != std::errc{} || ptr != str.data() + str.size() || value < 0) { + return Invalid("Invalid KEY_TIMESTAMP for key encryption key {}", key.key_id); + } + return value; +} + +class StandardDecryptedInputFile : public NativeEncryptionInputFile { + public: + StandardDecryptedInputFile(std::unique_ptr encrypted_input_file, + StandardKeyMetadata key_metadata) + : encrypted_input_file_(std::move(encrypted_input_file)), + key_metadata_(std::move(key_metadata)) {} + + std::unique_ptr DetachInputFile() && override { + return std::move(encrypted_input_file_); + } + + const NativeEncryptionKeyMetadata& key_metadata() const override { + return key_metadata_; + } + + std::string_view location() const override { + return encrypted_input_file_ ? encrypted_input_file_->location() : std::string_view{}; + } + + Result Size() const override { + ICEBERG_ASSIGN_OR_RAISE(auto encrypted_length, EncryptedLength()); + return encryption::AesGcmPlaintextLength(key_metadata_.encryption_key(), + encrypted_length); + } + + Result> Open() override { + ICEBERG_ASSIGN_OR_RAISE(auto encrypted_length, EncryptedLength()); + return encryption::OpenAesGcmInputStream( + *encrypted_input_file_, key_metadata_.encryption_key(), + key_metadata_.aad_prefix().value_or(std::span{}), + encrypted_length); + } + + private: + Result EncryptedLength() const { + ICEBERG_PRECHECK(encrypted_input_file_ != nullptr, + "Encrypted input file was detached"); + ICEBERG_ASSIGN_OR_RAISE(auto file_length, key_metadata_.file_length()); + // The length must come from trusted key metadata to detect truncation. + if (!file_length.has_value()) { + return Invalid("Cannot read AES GCM stream {}: key metadata has no file length", + encrypted_input_file_->location()); + } + return *file_length; + } + + std::unique_ptr encrypted_input_file_; + StandardKeyMetadata key_metadata_; +}; + +class StandardEncryptedOutputFile : public NativeEncryptionOutputFile { + public: + StandardEncryptedOutputFile(std::unique_ptr encrypting_output_file, + OutputFile& plain_output_file, + StandardKeyMetadata key_metadata) + : encrypting_output_file_(std::move(encrypting_output_file)), + plain_output_file_(plain_output_file), + key_metadata_(std::move(key_metadata)) {} + + OutputFile& plain_output_file() const override { return plain_output_file_; } + + OutputFile& encrypting_output_file() const override { return *encrypting_output_file_; } + + const NativeEncryptionKeyMetadata& key_metadata() const override { + return key_metadata_; + } + + private: + std::unique_ptr encrypting_output_file_; + OutputFile& plain_output_file_; // Owned by encrypting_output_file_. + StandardKeyMetadata key_metadata_; +}; + +Result CastOrParse(const EncryptionKeyMetadata& key_metadata) { + if (const auto* standard = dynamic_cast(&key_metadata)) { + return *standard; + } + auto buffer = key_metadata.buffer(); + return StandardKeyMetadata::Parse(buffer); +} + +Result> MakeStandardEncryptionManager( + const std::vector& keys, const TableProperties& table_properties, + std::shared_ptr kms_client) { + const auto& dek = TableProperties::kEncryptionDekLength; + auto data_key_length = dek.value(); + const auto& properties = table_properties.configs(); + if (auto it = properties.find(dek.key()); it != properties.end()) { + ICEBERG_ASSIGN_OR_RAISE(data_key_length, + StringUtils::ParseNumber(it->second)); + } + return StandardEncryptionManager::Make( + keys, table_properties.Get(TableProperties::kEncryptionTableKey), data_key_length, + std::move(kms_client)); +} + +} // namespace + +Result> StandardEncryptionManager::Make( + std::vector keys, std::string table_key_id, int32_t data_key_length, + std::shared_ptr kms_client) { + ICEBERG_PRECHECK(!table_key_id.empty(), "Invalid encryption key ID: empty"); + ICEBERG_PRECHECK(encryption::IsValidAesKeyLength(data_key_length), + "Invalid data key length: {} (must be 16, 24, or 32)", + data_key_length); + ICEBERG_PRECHECK(kms_client != nullptr, "Invalid KMS client: null"); + return std::shared_ptr(new StandardEncryptionManager( + std::move(keys), std::move(table_key_id), data_key_length, std::move(kms_client))); +} + +StandardEncryptionManager::StandardEncryptionManager( + std::vector keys, std::string table_key_id, int32_t data_key_length, + std::shared_ptr kms_client) + : table_key_id_(std::move(table_key_id)), + data_key_length_(data_key_length), + kms_client_(std::move(kms_client)) { + for (auto& key : keys) { + AddKey(std::move(key)); + } +} + +void StandardEncryptionManager::AddKey(EncryptedKey key) { + auto key_id = key.key_id; + if (encryption_keys_.insert_or_assign(key_id, std::move(key)).second) { + encryption_key_order_.push_back(std::move(key_id)); + } +} + +int64_t StandardEncryptionManager::CurrentTimeMillis() const { + auto now = std::chrono::system_clock::now().time_since_epoch(); + return (std::chrono::duration_cast(now) + test_time_shift_) + .count(); +} + +Result StandardEncryptionManager::NewKeyMetadata() { + std::vector encryption_key(data_key_length_); + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(encryption_key)); + std::vector aad_prefix(kAadPrefixLength); + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(aad_prefix)); + return StandardKeyMetadata::Make(std::move(encryption_key), std::move(aad_prefix)); +} + +Result> StandardEncryptionManager::UnwrapKek( + const std::string& kek_id) { + if (auto it = unwrapped_key_cache_.find(kek_id); it != unwrapped_key_cache_.end()) { + const auto age = std::chrono::steady_clock::now() - it->second.cached_at; + if (age < kUnwrappedKekCacheExpiry) { + return it->second.key; + } + unwrapped_key_cache_.erase(it); + } + auto it = encryption_keys_.find(kek_id); + if (it == encryption_keys_.end()) { + return Invalid("Cannot find key encryption key with id {}", kek_id); + } + ICEBERG_ASSIGN_OR_RAISE( + auto kek, + kms_client_->UnwrapKey(AsBytes(it->second.encrypted_key_metadata), table_key_id_)); + unwrapped_key_cache_.insert_or_assign(kek_id, CachedKek{.key = kek}); + return kek; +} + +Result> StandardEncryptionManager::DecryptManifestListKeyMetadata( + std::string_view manifest_list_key_id) { + std::lock_guard lock(mutex_); + auto it = encryption_keys_.find(std::string(manifest_list_key_id)); + if (it == encryption_keys_.end()) { + return Invalid("Cannot find manifest list key metadata with id {}", + manifest_list_key_id); + } + const EncryptedKey& manifest_list_key = it->second; + if (!manifest_list_key.encrypted_by_id.has_value() || + *manifest_list_key.encrypted_by_id == table_key_id_) { + return Invalid("{} is not manifest list key metadata", manifest_list_key_id); + } + + const std::string& kek_id = *manifest_list_key.encrypted_by_id; + ICEBERG_ASSIGN_OR_RAISE(auto kek, UnwrapKek(kek_id)); + auto timestamp = + encryption_keys_.at(kek_id).properties.find(std::string(kKeyTimestamp)); + if (timestamp == encryption_keys_.at(kek_id).properties.end()) { + return Invalid("Key encryption key {} must be timestamped", kek_id); + } + + // The KEK timestamp is the AAD, to prevent timestamp tampering attacks. + ICEBERG_ASSIGN_OR_RAISE(auto cipher, AesGcmCipher::Make(kek)); + return cipher->Decrypt(AsBytes(manifest_list_key.encrypted_key_metadata), + AsBytes(timestamp->second)); +} + +Result StandardEncryptionManager::KeyEncryptionKeyId() { + const int64_t now = CurrentTimeMillis(); + for (const auto& key_id : encryption_key_order_) { + const EncryptedKey& key = encryption_keys_.at(key_id); + if (key.encrypted_by_id != table_key_id_) { + continue; + } + ICEBERG_ASSIGN_OR_RAISE(auto timestamp, ParseTimestamp(key)); + if (timestamp > now || now - timestamp < kKekLifespan.count()) { + return key_id; + } + } + + // No unexpired key encryption key: create one, wrapped by the table master key. + std::vector kek(data_key_length_); + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(kek)); + ICEBERG_ASSIGN_OR_RAISE(auto wrapped, kms_client_->WrapKey(kek, table_key_id_)); + const int64_t timestamp = CurrentTimeMillis(); + ICEBERG_ASSIGN_OR_RAISE(auto kek_id, GenerateKeyId()); + AddKey(EncryptedKey{ + .key_id = kek_id, + .encrypted_key_metadata = ToString(wrapped), + .encrypted_by_id = table_key_id_, + .properties = {{std::string(kKeyTimestamp), std::to_string(timestamp)}}}); + unwrapped_key_cache_.insert_or_assign(kek_id, CachedKek{.key = std::move(kek)}); + return kek_id; +} + +Result StandardEncryptionManager::RegisterKeyMetadata( + const NativeEncryptionKeyMetadata& key_metadata) { + auto serialized = key_metadata.buffer(); + std::lock_guard lock(mutex_); + ICEBERG_ASSIGN_OR_RAISE(auto kek_id, KeyEncryptionKeyId()); + ICEBERG_ASSIGN_OR_RAISE(auto kek, UnwrapKek(kek_id)); + const EncryptedKey& kek_entry = encryption_keys_.at(kek_id); + const std::string& timestamp = kek_entry.properties.at(std::string(kKeyTimestamp)); + + ICEBERG_ASSIGN_OR_RAISE(auto cipher, AesGcmCipher::Make(kek)); + ICEBERG_ASSIGN_OR_RAISE(auto encrypted, + cipher->Encrypt(serialized, AsBytes(timestamp))); + ICEBERG_ASSIGN_OR_RAISE(auto file_key_id, GenerateKeyId()); + EncryptedKey file_key{.key_id = file_key_id, + .encrypted_key_metadata = ToString(encrypted), + .encrypted_by_id = kek_id}; + AddKey(file_key); + return FileEncryptionKeys{.key_encryption_key = encryption_keys_.at(kek_id), + .file_key = std::move(file_key)}; +} + +Result> StandardEncryptionManager::Decrypt( + std::unique_ptr encrypted) { + ICEBERG_PRECHECK(encrypted != nullptr, "Encrypted input file cannot be null"); + if (auto native = EncryptedInputFile::AsNative(encrypted)) { + return native; + } + ICEBERG_ASSIGN_OR_RAISE(auto metadata, CastOrParse(encrypted->key_metadata())); + auto raw = std::move(*encrypted).DetachInputFile(); + ICEBERG_PRECHECK(raw != nullptr, "Encrypted input file has no underlying file"); + return std::make_unique(std::move(raw), + std::move(metadata)); +} + +Result> StandardEncryptionManager::Encrypt( + std::unique_ptr plain) { + ICEBERG_PRECHECK(plain != nullptr, "Output file cannot be null"); + ICEBERG_ASSIGN_OR_RAISE(auto key_metadata, NewKeyMetadata()); + const auto aad_prefix = key_metadata.aad_prefix(); + ICEBERG_CHECK(aad_prefix.has_value() && aad_prefix->size() == kAadPrefixLength, + "Standard encryption requires a {}-byte AAD prefix", kAadPrefixLength); + auto* plain_output_file = plain.get(); + ICEBERG_ASSIGN_OR_RAISE( + auto encrypting_output_file, + AesGcmOutputFile::Make(std::move(plain), key_metadata.encryption_key(), + *aad_prefix)); + return std::make_unique( + std::move(encrypting_output_file), *plain_output_file, std::move(key_metadata)); +} + +std::vector StandardEncryptionManager::encryption_keys() const { + std::lock_guard lock(mutex_); + std::vector result; + result.reserve(encryption_key_order_.size()); + for (const auto& key_id : encryption_key_order_) { + result.push_back(encryption_keys_.at(key_id)); + } + return result; +} + +namespace encryption { + +void RegisterStandardEncryptionManager() { + ::iceberg::internal::RegisterDefaultEncryptionManagerFactory( + MakeStandardEncryptionManager); +} + +namespace { + +[[maybe_unused]] const bool kStandardEncryptionManagerRegistered = []() { + RegisterStandardEncryptionManager(); + return true; +}(); + +} // namespace + +} // namespace encryption + +} // namespace iceberg diff --git a/src/iceberg/encryption/standard_encryption_manager.h b/src/iceberg/encryption/standard_encryption_manager.h new file mode 100644 index 0000000000..aaa6ae0c0b --- /dev/null +++ b/src/iceberg/encryption/standard_encryption_manager.h @@ -0,0 +1,127 @@ +/* + * 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/standard_encryption_manager.h +/// Envelope encryption manager, compatible with Java's StandardEncryptionManager. + +#include +#include +#include +#include +#include +#include + +#include "iceberg/encryption/encrypted_key.h" +#include "iceberg/encryption/encryption_manager.h" +#include "iceberg/encryption/type_fwd.h" +#include "iceberg/iceberg_bundle_export.h" + +namespace iceberg { + +/// \brief The two keys produced by registering a manifest list's key metadata. +struct ICEBERG_BUNDLE_EXPORT FileEncryptionKeys { + /// The key encryption key, wrapped by the table master key in the KMS. + EncryptedKey key_encryption_key; + /// The manifest list key metadata, encrypted by the key encryption key. + EncryptedKey file_key; +}; + +/// \brief Standard Iceberg envelope encryption. +/// +/// Key hierarchy: +/// - table master key: in the KMS, ID in table property `encryption.key-id`; +/// - key encryption keys (KEK): wrapped by the KMS and kept in `encryption-keys` +/// with `encrypted-by-id` = the table key ID and a KEY_TIMESTAMP property. A KEK is +/// used for 730 days (NIST SP 800-57), then a new one is created; +/// - manifest list key metadata: AES-GCM encrypted by a KEK with the KEK timestamp as +/// AAD, kept in `encryption-keys` and referenced by the snapshot `key-id`; +/// - manifest key metadata: in the manifest list `key_metadata` field; +/// - data and delete file key metadata: in the manifest `key_metadata` field. +/// +/// The thread-safe manager reuses an unwrapped KEK for up to one hour. +class ICEBERG_BUNDLE_EXPORT StandardEncryptionManager : public EncryptionManager { + public: + static constexpr std::string_view kKeyTimestamp = "KEY_TIMESTAMP"; + static constexpr int32_t kAadPrefixLength = 16; + static constexpr std::chrono::milliseconds kKekLifespan{730LL * 24 * 3600 * 1000}; + static constexpr std::chrono::milliseconds kUnwrappedKekCacheExpiry{3600LL * 1000}; + + static Result> Make( + std::vector keys, std::string table_key_id, int32_t data_key_length, + std::shared_ptr kms_client); + + using EncryptionManager::Decrypt; + using EncryptionManager::Encrypt; + + /// \brief Return a NativeEncryptionInputFile, preserving an existing native wrapper. + /// + /// AGS1 Size() and Open() require the encrypted file length in the key metadata. + Result> Decrypt( + std::unique_ptr encrypted) override; + + /// \brief Return a NativeEncryptionOutputFile for native encryption or AGS1 streaming. + /// + /// Both paths use the same key and AAD prefix. The wrapper is not thread-safe. + Result> Encrypt( + std::unique_ptr plain) override; + + Result> DecryptManifestListKeyMetadata( + std::string_view manifest_list_key_id); + + Result RegisterKeyMetadata( + const NativeEncryptionKeyMetadata& key_metadata); + + /// \brief All keys: those from table metadata and those created by this manager. + std::vector encryption_keys() const; + + private: + friend struct StandardEncryptionManagerTestAccess; + + struct CachedKek { + std::vector key; + std::chrono::steady_clock::time_point cached_at = std::chrono::steady_clock::now(); + }; + + StandardEncryptionManager(std::vector keys, std::string table_key_id, + int32_t data_key_length, + std::shared_ptr kms_client); + + Result NewKeyMetadata(); + + // The following require mutex_ to be held. + Result> UnwrapKek(const std::string& kek_id); + Result KeyEncryptionKeyId(); + void AddKey(EncryptedKey key); + + int64_t CurrentTimeMillis() const; + + const std::string table_key_id_; + const int32_t data_key_length_; + const std::shared_ptr kms_client_; + + mutable std::mutex mutex_; + std::chrono::milliseconds test_time_shift_{0}; + std::vector encryption_key_order_; + std::unordered_map encryption_keys_; + std::unordered_map unwrapped_key_cache_; +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/standard_key_metadata.cc b/src/iceberg/encryption/standard_key_metadata.cc index 18f2d92ea2..1f2cb33ece 100644 --- a/src/iceberg/encryption/standard_key_metadata.cc +++ b/src/iceberg/encryption/standard_key_metadata.cc @@ -21,6 +21,7 @@ #include +#include "iceberg/encryption/aes_gcm_internal.h" #include "iceberg/util/macros.h" namespace iceberg { @@ -116,6 +117,25 @@ class Decoder { } // namespace +StandardKeyMetadata::StandardKeyMetadata(std::vector encryption_key, + std::optional> aad_prefix, + std::optional file_length) + : encryption_key_(std::move(encryption_key)), + aad_prefix_(std::move(aad_prefix)), + file_length_(file_length) {} + +Result StandardKeyMetadata::Make( + std::vector encryption_key, std::optional> aad_prefix, + std::optional file_length) { + ICEBERG_PRECHECK(encryption::IsValidAesKeyLength(encryption_key.size()), + "Invalid encryption key length: {} (must be 16, 24 or 32 bytes)", + encryption_key.size()); + ICEBERG_PRECHECK(!file_length.has_value() || *file_length >= 0, + "Encrypted file length must be nonnegative"); + return StandardKeyMetadata(std::move(encryption_key), std::move(aad_prefix), + file_length); +} + Result StandardKeyMetadata::Parse(std::span buffer) { if (buffer.empty()) { return Invalid("Empty key metadata"); @@ -126,43 +146,49 @@ Result StandardKeyMetadata::Parse(std::span } Decoder decoder(buffer.subspan(1)); - StandardKeyMetadata metadata; - ICEBERG_ASSIGN_OR_RAISE(metadata.encryption_key, decoder.ReadBytes()); + ICEBERG_ASSIGN_OR_RAISE(auto encryption_key, decoder.ReadBytes()); + std::optional> aad_prefix; ICEBERG_ASSIGN_OR_RAISE(auto has_aad_prefix, decoder.ReadOptionalBranch()); if (has_aad_prefix) { - ICEBERG_ASSIGN_OR_RAISE(metadata.aad_prefix, decoder.ReadBytes()); + ICEBERG_ASSIGN_OR_RAISE(aad_prefix, decoder.ReadBytes()); } + std::optional file_length; ICEBERG_ASSIGN_OR_RAISE(auto has_file_length, decoder.ReadOptionalBranch()); if (has_file_length) { - ICEBERG_ASSIGN_OR_RAISE(metadata.file_length, decoder.ReadLong()); + ICEBERG_ASSIGN_OR_RAISE(file_length, decoder.ReadLong()); } // Trailing bytes are ignored, matching Java, which decodes a single record. - return metadata; + return StandardKeyMetadata(std::move(encryption_key), std::move(aad_prefix), + file_length); } std::vector StandardKeyMetadata::Serialize() const { std::vector out; out.push_back(kV1); - WriteBytes(encryption_key, out); - if (aad_prefix.has_value()) { + WriteBytes(encryption_key_, out); + if (aad_prefix_.has_value()) { WriteLong(1, out); - WriteBytes(*aad_prefix, out); + WriteBytes(*aad_prefix_, out); } else { WriteLong(0, out); } - if (file_length.has_value()) { + if (file_length_.has_value()) { WriteLong(1, out); - WriteLong(*file_length, out); + WriteLong(*file_length_, out); } else { WriteLong(0, out); } return out; } -StandardKeyMetadata StandardKeyMetadata::WithFileLength(int64_t length) const { - StandardKeyMetadata copy = *this; - copy.file_length = length; - return copy; +Result StandardKeyMetadata::WithFileLength(int64_t length) const { + return Make(encryption_key_, aad_prefix_, length); +} + +Result> StandardKeyMetadata::CopyWithLength( + int64_t length) const { + ICEBERG_ASSIGN_OR_RAISE(auto copy, WithFileLength(length)); + return std::make_shared(std::move(copy)); } } // namespace iceberg diff --git a/src/iceberg/encryption/standard_key_metadata.h b/src/iceberg/encryption/standard_key_metadata.h index 7e788eae56..38abb33b49 100644 --- a/src/iceberg/encryption/standard_key_metadata.h +++ b/src/iceberg/encryption/standard_key_metadata.h @@ -23,10 +23,12 @@ /// Key metadata of the standard Iceberg encryption scheme. #include +#include #include #include #include +#include "iceberg/encryption/encryption_key_metadata.h" #include "iceberg/iceberg_export.h" #include "iceberg/result.h" @@ -46,15 +48,14 @@ namespace iceberg { /// version (1) followed by an Avro binary encoded record with the fields /// `encryption_key: bytes`, `aad_prefix: union{null, bytes}` and /// `file_length: union{null, long}`. -struct ICEBERG_EXPORT StandardKeyMetadata { +class ICEBERG_EXPORT StandardKeyMetadata : public NativeEncryptionKeyMetadata { + public: static constexpr uint8_t kV1 = 1; - /// \brief The data encryption key (16, 24 or 32 bytes). - std::vector encryption_key; - /// \brief The AAD prefix (file ID) used to bind ciphertext to this file. - std::optional> aad_prefix; - /// \brief The encrypted (stored) file length, required to read AES GCM streams. - std::optional file_length; + static Result Make( + std::vector encryption_key, + std::optional> aad_prefix = std::nullopt, + std::optional file_length = std::nullopt); /// \brief Parse serialized key metadata. static Result Parse(std::span buffer); @@ -63,10 +64,41 @@ struct ICEBERG_EXPORT StandardKeyMetadata { std::vector Serialize() const; /// \brief Return a copy with the given encrypted file length. - StandardKeyMetadata WithFileLength(int64_t length) const; + Result WithFileLength(int64_t length) const; - friend bool operator==(const StandardKeyMetadata&, - const StandardKeyMetadata&) = default; + std::vector buffer() const override { return Serialize(); } + + std::shared_ptr Copy() const override { + return std::make_shared(*this); + } + + std::span encryption_key() const override { return encryption_key_; } + + std::optional> aad_prefix() const override { + if (!aad_prefix_.has_value()) { + return std::nullopt; + } + return std::span(*aad_prefix_); + } + + Result> file_length() const override { return file_length_; } + + Result> CopyWithLength( + int64_t length) const override; + + friend bool operator==(const StandardKeyMetadata& lhs, const StandardKeyMetadata& rhs) { + return lhs.encryption_key_ == rhs.encryption_key_ && + lhs.aad_prefix_ == rhs.aad_prefix_ && lhs.file_length_ == rhs.file_length_; + } + + private: + StandardKeyMetadata(std::vector encryption_key, + std::optional> aad_prefix, + std::optional file_length); + + std::vector encryption_key_; + std::optional> aad_prefix_; + std::optional file_length_; }; } // namespace iceberg diff --git a/src/iceberg/encryption/type_fwd.h b/src/iceberg/encryption/type_fwd.h new file mode 100644 index 0000000000..d8602590b8 --- /dev/null +++ b/src/iceberg/encryption/type_fwd.h @@ -0,0 +1,41 @@ +/* + * 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/type_fwd.h +/// Forward declarations for table encryption types. + +namespace iceberg { + +struct EncryptedKey; +struct FileEncryptionKeys; + +class EncryptedInputFile; +class EncryptedOutputFile; +class EncryptionKeyMetadata; +class EncryptionManager; +class KeyManagementClient; +class NativeEncryptionInputFile; +class NativeEncryptionKeyMetadata; +class NativeEncryptionOutputFile; +class StandardEncryptionManager; +class StandardKeyMetadata; + +} // namespace iceberg diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index c69ad54c7d..4d9e84a10f 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -142,7 +142,11 @@ add_iceberg_test(expression_test residual_evaluator_test.cc strict_metrics_evaluator_test.cc) -add_iceberg_test(encryption_test SOURCES kms_test.cc standard_key_metadata_test.cc) +add_iceberg_test(encryption_test + SOURCES + encryption_manager_test.cc + kms_test.cc + standard_key_metadata_test.cc) add_iceberg_test(json_serde_test SOURCES @@ -276,7 +280,11 @@ if(ICEBERG_BUILD_BUNDLE) endif() if(ICEBERG_ENCRYPTION) - add_iceberg_test(crypto_test USE_BUNDLE SOURCES aes_gcm_test.cc) + add_iceberg_test(crypto_test + USE_BUNDLE + SOURCES + aes_gcm_test.cc + standard_encryption_manager_test.cc) endif() add_iceberg_test(scan_test diff --git a/src/iceberg/test/aes_gcm_test.cc b/src/iceberg/test/aes_gcm_test.cc index e3d1248e75..5a90cb78be 100644 --- a/src/iceberg/test/aes_gcm_test.cc +++ b/src/iceberg/test/aes_gcm_test.cc @@ -145,46 +145,54 @@ TEST(AesGcmCipherTest, DecryptsJavaManifestListKeyMetadata) { ICEBERG_UNWRAP_OR_FAIL(auto decrypted, cipher->Decrypt(kJavaManifestListKeyMetadata, AsBytes(kKekTimestamp))); ICEBERG_UNWRAP_OR_FAIL(auto metadata, StandardKeyMetadata::Parse(decrypted)); - EXPECT_EQ(metadata.encryption_key, TestBytes(16, 1)); - EXPECT_EQ(metadata.aad_prefix, TestBytes(16, 2)); - EXPECT_EQ(metadata.file_length, 4242); + EXPECT_TRUE(std::ranges::equal(metadata.encryption_key(), TestBytes(16, 1))); + ASSERT_TRUE(metadata.aad_prefix().has_value()); + EXPECT_TRUE(std::ranges::equal(*metadata.aad_prefix(), TestBytes(16, 2))); + ICEBERG_UNWRAP_OR_FAIL(auto length, metadata.file_length()); + EXPECT_EQ(length, 4242); } class AesGcmStreamTest : public TempFileTestBase { protected: + static constexpr int64_t kMaxBlocks = std::numeric_limits::max(); + static constexpr int64_t kTooManyBlocksLength = + AesGcmStream::kHeaderLength + (kMaxBlocks + 1) * AesGcmStream::kCipherBlockSize; + void SetUp() override { TempFileTestBase::SetUp(); io_ = std::shared_ptr(arrow::MakeLocalFileIO()); } // Write `plain` as an AGS1 stream and return the stored length. - int64_t Write(const std::string& path, std::span plain, - const std::vector& key, const std::vector& aad, - size_t chunk = 1 << 20) { - auto out = io_->NewOutputFile(path); - EXPECT_THAT(out, IsOk()); - AesGcmOutputFile file(std::move(out.value()), key, aad); - auto stream = file.CreateOrOverwrite(); - EXPECT_THAT(stream, IsOk()); + Result Write(const std::string& path, std::span plain, + const std::vector& key, const std::vector& aad, + size_t chunk = 1 << 20) { + ICEBERG_ASSIGN_OR_RAISE(auto out, io_->NewOutputFile(path)); + ICEBERG_ASSIGN_OR_RAISE(auto file, AesGcmOutputFile::Make(std::move(out), key, aad)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, file->CreateOrOverwrite()); for (size_t pos = 0; pos < plain.size(); pos += chunk) { auto part = plain.subspan(pos, std::min(chunk, plain.size() - pos)); - EXPECT_THAT((*stream)->Write(std::as_bytes(part)), IsOk()); + ICEBERG_RETURN_UNEXPECTED(stream->Write(std::as_bytes(part))); } - EXPECT_EQ((*stream)->Position().value(), static_cast(plain.size())); - EXPECT_THAT((*stream)->Close(), IsOk()); + ICEBERG_ASSIGN_OR_RAISE(auto position, stream->Position()); + EXPECT_EQ(position, static_cast(plain.size())); + ICEBERG_RETURN_UNEXPECTED(stream->Close()); // Java's AesGcmOutputStream keeps reporting the plaintext length once closed - EXPECT_EQ((*stream)->Position().value(), static_cast(plain.size())); - auto stored = (*stream)->StoredLength().value(); - EXPECT_EQ(stored, static_cast(std::filesystem::file_size(path))); + ICEBERG_ASSIGN_OR_RAISE(position, stream->Position()); + EXPECT_EQ(position, static_cast(plain.size())); + ICEBERG_ASSIGN_OR_RAISE(auto stored, stream->StoredLength()); + ICEBERG_ASSIGN_OR_RAISE(auto input, io_->NewInputFile(path)); + ICEBERG_ASSIGN_OR_RAISE(auto file_size, input->Size()); + EXPECT_EQ(stored, file_size); return stored; } - std::unique_ptr Open(const std::string& path, - const std::vector& key, - const std::vector& aad, int64_t length) { - auto in = io_->NewInputFile(path); - EXPECT_THAT(in, IsOk()); - return std::make_unique(std::move(in.value()), key, aad, length); + Result> Open(const std::string& path, + const std::vector& key, + const std::vector& aad, + int64_t length) { + ICEBERG_ASSIGN_OR_RAISE(auto in, io_->NewInputFile(path)); + return AesGcmInputFile::Make(std::move(in), key, aad, length); } // Materialize an inlined Java fixture as a file the reader can open. @@ -206,7 +214,8 @@ TEST_F(AesGcmStreamTest, ReadsJavaVectors) { {0, &kJavaAgs1Empty}, {1, &kJavaAgs1OneByte}, {100, &kJavaAgs1Hundred}}; for (const auto& [length, encrypted] : vectors) { auto path = WriteRaw(*encrypted); - auto file = Open(path, kDataKey, kAadPrefix, static_cast(encrypted->size())); + ICEBERG_UNWRAP_OR_FAIL(auto file, Open(path, kDataKey, kAadPrefix, + static_cast(encrypted->size()))); ICEBERG_UNWRAP_OR_FAIL(auto plain, ReadAll(*file)); EXPECT_EQ(plain, TestBytes(length, 5)) << "plaintext length " << length; } @@ -216,7 +225,8 @@ TEST_F(AesGcmStreamTest, WritesJavaCompatibleLayout) { // Same plaintext, key and AAD prefix as Java's 100-byte vector: same header and // length (the ciphertext differs only by the random nonce). auto path = CreateNewTempFilePath(); - auto stored = Write(path, TestBytes(100, 5), kDataKey, kAadPrefix); + ICEBERG_UNWRAP_OR_FAIL(auto stored, + Write(path, TestBytes(100, 5), kDataKey, kAadPrefix)); ASSERT_EQ(stored, static_cast(kJavaAgs1Hundred.size())); std::ifstream in(path, std::ios::binary); std::vector header(8); @@ -234,13 +244,13 @@ TEST_F(AesGcmStreamTest, RoundTripAcrossBlocks) { auto path = CreateNewTempFilePath(); auto plain = TestBytes(size, 5); // Odd write sizes exercise writes that straddle blocks - int64_t stored = Write(path, plain, key, aad, /*chunk=*/333331); + ICEBERG_UNWRAP_OR_FAIL(auto stored, Write(path, plain, key, aad, /*chunk=*/333331)); size_t blocks = size == 0 ? 1 : (size + kBlock - 1) / kBlock; EXPECT_EQ(stored, static_cast(8 + size + blocks * 28)); ICEBERG_UNWRAP_OR_FAIL(auto plain_size, AesGcmStream::PlaintextLength(stored)); EXPECT_EQ(plain_size, static_cast(size)); - auto file = Open(path, key, aad, stored); + ICEBERG_UNWRAP_OR_FAIL(auto file, Open(path, key, aad, stored)); ICEBERG_UNWRAP_OR_FAIL(auto read, ReadAll(*file)); EXPECT_EQ(read, plain); @@ -259,53 +269,55 @@ TEST_F(AesGcmStreamTest, DetectsTampering) { auto aad = TestBytes(16, 9); auto path = CreateNewTempFilePath(); auto plain = TestBytes(AesGcmStream::kPlainBlockSize + 100, 5); - int64_t stored = Write(path, plain, key, aad); + ICEBERG_UNWRAP_OR_FAIL(auto stored, Write(path, plain, key, aad)); // Wrong key or AAD prefix (a file swapped in from another manifest entry) - EXPECT_THAT(ReadAll(*Open(path, TestBytes(16, 8), aad, stored)), - IsError(ErrorKind::kInvalid)); - EXPECT_THAT(ReadAll(*Open(path, key, TestBytes(16, 10), stored)), - IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto wrong_key, Open(path, TestBytes(16, 8), aad, stored)); + EXPECT_THAT(ReadAll(*wrong_key), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto wrong_aad, Open(path, key, TestBytes(16, 10), stored)); + EXPECT_THAT(ReadAll(*wrong_aad), IsError(ErrorKind::kInvalid)); // Truncation: the trusted length from the key metadata no longer matches the file std::filesystem::resize_file(path, 8 + AesGcmStream::kCipherBlockSize); - EXPECT_THAT(ReadAll(*Open(path, key, aad, stored)), IsError(ErrorKind::kIOError)); + ICEBERG_UNWRAP_OR_FAIL(auto file, Open(path, key, aad, stored)); + EXPECT_THAT(ReadAll(*file), IsError(ErrorKind::kIOError)); // AGS1 blocks do not mark the end of the stream: a truncated file read with its own // (untrusted) length still decrypts. This is why readers must take the length from // the key metadata. - auto truncated = Open(path, key, aad, 8 + AesGcmStream::kCipherBlockSize); + ICEBERG_UNWRAP_OR_FAIL(auto truncated, + Open(path, key, aad, 8 + AesGcmStream::kCipherBlockSize)); ICEBERG_UNWRAP_OR_FAIL(auto first_block, ReadAll(*truncated)); EXPECT_EQ(first_block.size(), AesGcmStream::kPlainBlockSize); // Bad magic std::filesystem::resize_file(path, 0); std::ofstream(path, std::ios::binary) << "XXXX0000" << std::string(28, '\0'); - EXPECT_THAT(Open(path, key, aad, 36)->Open(), IsError(ErrorKind::kInvalid)); - // Shorter than an empty stream - EXPECT_THAT(Open(path, key, aad, 35)->Open(), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto bad_magic, Open(path, key, aad, 36)); + EXPECT_THAT(bad_magic->Open(), IsError(ErrorKind::kInvalid)); } TEST_F(AesGcmStreamTest, AuthenticatesEmptyStream) { auto key = TestBytes(16, 7); auto aad = TestBytes(16, 9); auto path = CreateNewTempFilePath(); - int64_t stored = Write(path, {}, key, aad); + ICEBERG_UNWRAP_OR_FAIL(auto stored, Write(path, {}, key, aad)); ASSERT_EQ(stored, AesGcmStream::kMinStreamLength); // An empty stream still carries one block with a nonce and a tag, so opening it // authenticates that block even though there is no plaintext to read. - ICEBERG_UNWRAP_OR_FAIL(auto plain, ReadAll(*Open(path, key, aad, stored))); + ICEBERG_UNWRAP_OR_FAIL(auto file, Open(path, key, aad, stored)); + ICEBERG_UNWRAP_OR_FAIL(auto plain, ReadAll(*file)); EXPECT_TRUE(plain.empty()); // Wrong key or AAD prefix (a file swapped in from another manifest entry) - EXPECT_THAT(Open(path, TestBytes(16, 8), aad, stored)->Open(), - IsError(ErrorKind::kInvalid)); - EXPECT_THAT(Open(path, key, TestBytes(16, 10), stored)->Open(), - IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto wrong_key, Open(path, TestBytes(16, 8), aad, stored)); + EXPECT_THAT(wrong_key->Open(), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto wrong_aad, Open(path, key, TestBytes(16, 10), stored)); + EXPECT_THAT(wrong_aad->Open(), IsError(ErrorKind::kInvalid)); // Truncated to its header behind a trusted length that says otherwise std::filesystem::resize_file(path, AesGcmStream::kHeaderLength); - EXPECT_THAT(Open(path, key, aad, stored)->Open(), IsError(ErrorKind::kIOError)); + EXPECT_THAT(file->Open(), IsError(ErrorKind::kIOError)); // A corrupt tag auto corrupt = WriteRaw(kJavaAgs1Empty); @@ -314,18 +326,18 @@ TEST_F(AesGcmStreamTest, AuthenticatesEmptyStream) { out.seekp(static_cast(kJavaAgs1Empty.size() - 1)); out.put(static_cast(kJavaAgs1Empty.back() ^ 0xFF)); } - EXPECT_THAT( - Open(corrupt, kDataKey, kAadPrefix, static_cast(kJavaAgs1Empty.size())) - ->Open(), - IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto bad_tag, Open(corrupt, kDataKey, kAadPrefix, + static_cast(kJavaAgs1Empty.size()))); + EXPECT_THAT(bad_tag->Open(), IsError(ErrorKind::kInvalid)); } TEST_F(AesGcmStreamTest, RejectsOutOfRangeReadFully) { auto key = TestBytes(16, 7); auto aad = TestBytes(16, 9); auto path = CreateNewTempFilePath(); - int64_t stored = Write(path, TestBytes(100, 5), key, aad); - ICEBERG_UNWRAP_OR_FAIL(auto stream, Open(path, key, aad, stored)->Open()); + ICEBERG_UNWRAP_OR_FAIL(auto stored, Write(path, TestBytes(100, 5), key, aad)); + ICEBERG_UNWRAP_OR_FAIL(auto file, Open(path, key, aad, stored)); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); // A position near int64 max must be rejected without overflowing the range check std::vector one(1); @@ -361,18 +373,30 @@ TEST_F(AesGcmStreamTest, RejectsInvalidEncryptedLength) { // More blocks than the int32 block index in the block AAD can address. The check // must happen here rather than when a block is decrypted, so that a caller asking // only for the size never sees a length it could not read back. - constexpr int64_t kMaxBlocks = std::numeric_limits::max(); EXPECT_THAT(AesGcmStream::PlaintextLength(kHeader + kMaxBlocks * kCipherBlock), HasValue(::testing::Eq(kMaxBlocks * AesGcmStream::kPlainBlockSize))); - EXPECT_THAT(AesGcmStream::PlaintextLength(kHeader + kMaxBlocks * kCipherBlock + 1), + EXPECT_THAT(AesGcmStream::PlaintextLength(kTooManyBlocksLength), IsError(ErrorKind::kInvalid)); +} + +TEST_F(AesGcmStreamTest, RejectsInvalidFileArguments) { + constexpr int64_t kLength = AesGcmStream::kMinStreamLength; + EXPECT_THAT(AesGcmInputFile::Make(nullptr, kDataKey, {}, kLength), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(AesGcmOutputFile::Make(nullptr, kDataKey, {}), + IsError(ErrorKind::kInvalidArgument)); - // Both Size() and Open() reject it, rather than Open() alone auto path = CreateNewTempFilePath(); - Write(path, TestBytes(10, 5), kDataKey, kAadPrefix); - auto file = Open(path, kDataKey, kAadPrefix, kHeader + kMaxBlocks * kCipherBlock + 1); - EXPECT_THAT(file->Size(), IsError(ErrorKind::kInvalid)); - EXPECT_THAT(file->Open(), IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto in, io_->NewInputFile(path)); + EXPECT_THAT(AesGcmInputFile::Make(std::move(in), {}, {}, kLength), + IsError(ErrorKind::kInvalidArgument)); + ICEBERG_UNWRAP_OR_FAIL(in, io_->NewInputFile(path)); + EXPECT_THAT( + AesGcmInputFile::Make(std::move(in), kDataKey, kAadPrefix, kTooManyBlocksLength), + IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto out, io_->NewOutputFile(path)); + EXPECT_THAT(AesGcmOutputFile::Make(std::move(out), {}, {}), + IsError(ErrorKind::kInvalidArgument)); } // The key encryption key of the Java fixture table, wrapped by Java's UnitestKMS under @@ -394,14 +418,15 @@ constexpr std::string_view kJavaMasterKeyA = "0123456789012345"; TEST(InMemoryKmsTest, UnwrapsJavaWrappedKey) { auto master_key = AsBytes(kJavaMasterKeyA); - InMemoryKms kms({{"keyA", std::vector(master_key.begin(), master_key.end())}}); - ICEBERG_UNWRAP_OR_FAIL(auto kek, kms.UnwrapKey(kJavaKekWrappedByKeyA, "keyA")); + ICEBERG_UNWRAP_OR_FAIL( + auto kms, InMemoryKms::Make({{"keyA", {master_key.begin(), master_key.end()}}})); + ICEBERG_UNWRAP_OR_FAIL(auto kek, kms->UnwrapKey(kJavaKekWrappedByKeyA, "keyA")); EXPECT_EQ(kek, kJavaKek); - ICEBERG_UNWRAP_OR_FAIL(auto wrapped, kms.WrapKey(kek, "keyA")); - ICEBERG_UNWRAP_OR_FAIL(auto unwrapped, kms.UnwrapKey(wrapped, "keyA")); + ICEBERG_UNWRAP_OR_FAIL(auto wrapped, kms->WrapKey(kek, "keyA")); + ICEBERG_UNWRAP_OR_FAIL(auto unwrapped, kms->UnwrapKey(wrapped, "keyA")); EXPECT_EQ(unwrapped, kJavaKek); - EXPECT_THAT(kms.UnwrapKey(wrapped, "keyB"), IsError(ErrorKind::kNotFound)); + EXPECT_THAT(kms->UnwrapKey(wrapped, "keyB"), IsError(ErrorKind::kNotFound)); } TEST(InMemoryKmsTest, RegistryAndProperties) { @@ -417,6 +442,11 @@ TEST(InMemoryKmsTest, RegistryAndProperties) { } TEST(InMemoryKmsTest, RejectsInvalidMasterKeyProperties) { + EXPECT_THAT(InMemoryKms::Make({{"", std::vector(16)}}), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(InMemoryKms::Make({{"keyA", {1, 2, 3}}}), + IsError(ErrorKind::kInvalidArgument)); + InMemoryKms::Register(); auto load = [](std::string id, std::string value) { return KmsRegistry::FromCatalogProperties( diff --git a/src/iceberg/test/encryption_manager_test.cc b/src/iceberg/test/encryption_manager_test.cc new file mode 100644 index 0000000000..b5af47e109 --- /dev/null +++ b/src/iceberg/test/encryption_manager_test.cc @@ -0,0 +1,123 @@ +/* + * 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/encryption_manager.h" + +#include + +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encrypted_files.h" +#include "iceberg/encryption/encrypted_key.h" +#include "iceberg/table_properties.h" +#include "iceberg/test/logging_test_helpers.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/std_io.h" + +namespace iceberg { +namespace { + +class EncryptionManagerRegistryTest : public ::testing::Test { + protected: + void TearDown() override { EncryptionManagerRegistry::Register({}); } +}; + +TEST_F(EncryptionManagerRegistryTest, RegistersCustomFactoryWithoutKms) { + std::vector keys{ + {.key_id = "custom-key", .encrypted_key_metadata = "wrapped"}}; + auto properties = TableProperties::FromMap( + {{"custom.property", "value"}, {"encryption.data-key-length", "custom"}}); + EXPECT_THAT(EncryptionManagerRegistry::Make(keys, properties, nullptr), + IsError(ErrorKind::kNotSupported)); + + auto custom = std::make_shared(); + EncryptionManagerRegistry::Register([&](const std::vector& received_keys, + const TableProperties& received_properties, + std::shared_ptr kms_client) + -> Result> { + EXPECT_EQ(received_keys, keys); + EXPECT_EQ(received_properties.configs(), properties.configs()); + EXPECT_EQ(kms_client, nullptr); + return custom; + }); + ICEBERG_UNWRAP_OR_FAIL(auto direct, + EncryptionManagerRegistry::Make(keys, properties, nullptr)); + EXPECT_EQ(direct, custom); + + custom.reset(); + EXPECT_THAT(EncryptionManagerRegistry::Make(keys, properties, nullptr), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST(PlaintextEncryptionManagerTest, RejectsNullFileHandles) { + PlaintextEncryptionManager manager; + std::vector> inputs(1); + EXPECT_THAT(manager.Decrypt(std::move(inputs)), IsError(ErrorKind::kInvalidArgument)); + std::vector> outputs(1); + EXPECT_THAT(manager.Encrypt(std::move(outputs)), IsError(ErrorKind::kInvalidArgument)); +} + +TEST(EncryptedFilesTest, RejectsNullArguments) { + auto metadata = BaseEncryptionKeyMetadata::Empty(); + EXPECT_THAT(EncryptedFiles::EncryptedInput(nullptr, metadata), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(EncryptedFiles::EncryptedOutput(nullptr, metadata), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT( + EncryptedFiles::EncryptedInput(std::make_unique("in"), nullptr), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(EncryptedFiles::EncryptedOutput( + std::make_unique("out"), nullptr), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST(PlaintextEncryptionManagerTest, WarnsWhenKeyMetadataIsPresent) { + PlaintextEncryptionManager manager; + auto logger = std::make_shared(); + ScopedLogger bind(logger); + auto present_empty = + std::make_shared(std::vector{}); + for (const auto& metadata : {BaseEncryptionKeyMetadata::Empty(), present_empty}) { + auto input = std::make_unique("in"); + auto* raw = input.get(); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, + EncryptedFiles::EncryptedInput(std::move(input), metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, manager.Decrypt(std::move(encrypted))); + EXPECT_EQ(decrypted.get(), raw); + EXPECT_EQ(logger->count(), metadata->has_value() ? 1u : 0u); + } + EXPECT_THAT(logger->records(), ::testing::ElementsAre(::testing::Field( + &LogMessage::level, LogLevel::kWarn))); +} + +TEST(BaseEncryptionKeyMetadataTest, DistinguishesAbsentFromEmpty) { + auto absent = BaseEncryptionKeyMetadata::Empty(); + BaseEncryptionKeyMetadata empty(std::vector{}); + EXPECT_FALSE(absent->has_value()); + EXPECT_TRUE(empty.has_value()); + EXPECT_TRUE(absent->buffer().empty()); + EXPECT_EQ(absent->buffer(), empty.buffer()); + EXPECT_FALSE(absent->Copy()->has_value()); + EXPECT_TRUE(empty.Copy()->has_value()); + + BaseEncryptionKeyMetadata bytes(std::vector{1, 2}); + EXPECT_EQ(bytes.Copy()->buffer(), bytes.buffer()); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/resources/encryption/table/metadata/snap-1122461367364127429-1-462964d7-9cf9-4547-a01b-29e4eef4bc25.avro b/src/iceberg/test/resources/encryption/table/metadata/snap-1122461367364127429-1-462964d7-9cf9-4547-a01b-29e4eef4bc25.avro new file mode 100644 index 0000000000..c45ab3ca34 Binary files /dev/null and b/src/iceberg/test/resources/encryption/table/metadata/snap-1122461367364127429-1-462964d7-9cf9-4547-a01b-29e4eef4bc25.avro differ diff --git a/src/iceberg/test/resources/encryption/table/metadata/snap-5112456484007752895-1-95f19655-198b-4c2a-a7e5-e3cf75d5ab54.avro b/src/iceberg/test/resources/encryption/table/metadata/snap-5112456484007752895-1-95f19655-198b-4c2a-a7e5-e3cf75d5ab54.avro new file mode 100644 index 0000000000..195c5055d9 Binary files /dev/null and b/src/iceberg/test/resources/encryption/table/metadata/snap-5112456484007752895-1-95f19655-198b-4c2a-a7e5-e3cf75d5ab54.avro differ diff --git a/src/iceberg/test/resources/encryption/table/metadata/snap-5555854819025587960-1-d1977369-b04a-4cf3-a491-6090bc1572fc.avro b/src/iceberg/test/resources/encryption/table/metadata/snap-5555854819025587960-1-d1977369-b04a-4cf3-a491-6090bc1572fc.avro new file mode 100644 index 0000000000..eb6658a6f4 Binary files /dev/null and b/src/iceberg/test/resources/encryption/table/metadata/snap-5555854819025587960-1-d1977369-b04a-4cf3-a491-6090bc1572fc.avro differ diff --git a/src/iceberg/test/resources/encryption/table/metadata/snap-564307663132197943-1-511c33d0-d9b9-4c80-bce0-b6fe4679785b.avro b/src/iceberg/test/resources/encryption/table/metadata/snap-564307663132197943-1-511c33d0-d9b9-4c80-bce0-b6fe4679785b.avro new file mode 100644 index 0000000000..bfc39890f1 Binary files /dev/null and b/src/iceberg/test/resources/encryption/table/metadata/snap-564307663132197943-1-511c33d0-d9b9-4c80-bce0-b6fe4679785b.avro differ diff --git a/src/iceberg/test/resources/encryption/table/metadata/v5.metadata.json b/src/iceberg/test/resources/encryption/table/metadata/v5.metadata.json new file mode 100644 index 0000000000..241ea609c3 --- /dev/null +++ b/src/iceberg/test/resources/encryption/table/metadata/v5.metadata.json @@ -0,0 +1 @@ +{"format-version":3,"table-uuid":"2091a278-2727-4bc0-8427-ffb04a2b7e6d","location":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table","last-sequence-number":4,"last-updated-ms":1791460593995,"last-column-id":2,"current-schema-id":0,"schemas":[{"type":"struct","schema-id":0,"fields":[{"id":1,"name":"id","required":true,"type":"long"},{"id":2,"name":"data","required":false,"type":"string"}]}],"default-spec-id":0,"partition-specs":[{"spec-id":0,"fields":[]}],"last-partition-id":999,"default-sort-order-id":0,"sort-orders":[{"order-id":0,"fields":[]}],"properties":{"encryption.key-id":"keyA","write.parquet.compression-codec":"zstd"},"current-snapshot-id":5555854819025587960,"next-row-id":13,"encryption-keys":[{"key-id":"6kMyWaTMFqk5FVecTafB8w==","encrypted-key-metadata":"BA3fkOhBo//37HfxBA1lUEbSrgrv3k06ovUGyi70AINLvvCU9iCUdhwR9lM=","encrypted-by-id":"keyA","properties":{"KEY_TIMESTAMP":"1791460593549"}},{"key-id":"9Dpe+fdlQ+4lMH5jW0q1YQ==","encrypted-key-metadata":"UTlv697ZHJpwrMe7rfBpOBNsbrSKKZuHLJm2i/V0DiJmtTR3RxxBhYlxxBaDH6K9kpFRZ1YrkRCYLhgrY5pAyvj9KA==","encrypted-by-id":"6kMyWaTMFqk5FVecTafB8w=="},{"key-id":"LU90Mju0jbgvcsbifDCF0A==","encrypted-key-metadata":"2VLA6waTLBagemORlfjUdPRjmo3M3fPei7WkwX/q4S8aEM8CnAW8gllBDpEPXa/70jzMCvlVXkdg5x0CCmzoBKaSkA==","encrypted-by-id":"6kMyWaTMFqk5FVecTafB8w=="},{"key-id":"ZkXVnuHz4Qlemc4wNaI8Eg==","encrypted-key-metadata":"qz9eUQScTKPymZ8tV+csNKXRhBF2hDHU7s0d7+AbbG10T6Zgqc/BVKXfL5FjYJ2KNQdCxpp4CAm3HlXpFbxR5HA+Kw==","encrypted-by-id":"6kMyWaTMFqk5FVecTafB8w=="},{"key-id":"VTWjHxdPbZFKJheX7XsR/Q==","encrypted-key-metadata":"EgZwxa5QZHjIWGAyrWOZiTfZEzOuQ1elzfuKke1DqxTQmGSHUTSNSxE0piZMRisSN/Ijp1EF7jbohWPi9OEr0BuBjQ==","encrypted-by-id":"6kMyWaTMFqk5FVecTafB8w=="}],"refs":{"main":{"snapshot-id":5555854819025587960,"type":"branch"}},"snapshots":[{"sequence-number":1,"snapshot-id":564307663132197943,"timestamp-ms":1791460593552,"summary":{"operation":"append","manifests-created":"1","manifests-kept":"0","manifests-replaced":"0","added-data-files":"1","added-records":"5","added-files-size":"1791","changed-partition-count":"1","total-records":"5","total-files-size":"1791","total-data-files":"1","total-delete-files":"0","total-position-deletes":"0","total-equality-deletes":"0","iceberg-version":"Apache Iceberg 1.13.0-SNAPSHOT (commit 4d5811f2c701b15be4379686b17144503ed1e685)"},"manifest-list":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/snap-564307663132197943-1-511c33d0-d9b9-4c80-bce0-b6fe4679785b.avro","schema-id":0,"first-row-id":0,"added-rows":5,"key-id":"9Dpe+fdlQ+4lMH5jW0q1YQ=="},{"sequence-number":2,"snapshot-id":1122461367364127429,"parent-snapshot-id":564307663132197943,"timestamp-ms":1791460593713,"summary":{"operation":"append","manifests-created":"1","manifests-kept":"1","manifests-replaced":"0","added-data-files":"1","added-records":"5","added-files-size":"1793","changed-partition-count":"1","total-records":"10","total-files-size":"3584","total-data-files":"2","total-delete-files":"0","total-position-deletes":"0","total-equality-deletes":"0","iceberg-version":"Apache Iceberg 1.13.0-SNAPSHOT (commit 4d5811f2c701b15be4379686b17144503ed1e685)"},"manifest-list":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/snap-1122461367364127429-1-462964d7-9cf9-4547-a01b-29e4eef4bc25.avro","schema-id":0,"first-row-id":5,"added-rows":5,"key-id":"LU90Mju0jbgvcsbifDCF0A=="},{"sequence-number":3,"snapshot-id":5112456484007752895,"parent-snapshot-id":1122461367364127429,"timestamp-ms":1791460593828,"summary":{"operation":"append","manifests-created":"1","manifests-kept":"2","manifests-replaced":"0","added-data-files":"1","added-records":"3","added-files-size":"445","changed-partition-count":"1","total-records":"13","total-files-size":"4029","total-data-files":"3","total-delete-files":"0","total-position-deletes":"0","total-equality-deletes":"0","iceberg-version":"Apache Iceberg 1.13.0-SNAPSHOT (commit 4d5811f2c701b15be4379686b17144503ed1e685)"},"manifest-list":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/snap-5112456484007752895-1-95f19655-198b-4c2a-a7e5-e3cf75d5ab54.avro","schema-id":0,"first-row-id":10,"added-rows":3,"key-id":"ZkXVnuHz4Qlemc4wNaI8Eg=="},{"sequence-number":4,"snapshot-id":5555854819025587960,"parent-snapshot-id":5112456484007752895,"timestamp-ms":1791460593995,"summary":{"operation":"delete","manifests-created":"1","manifests-kept":"3","manifests-replaced":"0","added-delete-files":"1","added-dvs":"1","added-files-size":"42","added-position-deletes":"1","changed-partition-count":"1","total-records":"13","total-files-size":"4071","total-data-files":"3","total-delete-files":"1","total-position-deletes":"1","total-equality-deletes":"0","iceberg-version":"Apache Iceberg 1.13.0-SNAPSHOT (commit 4d5811f2c701b15be4379686b17144503ed1e685)"},"manifest-list":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/snap-5555854819025587960-1-d1977369-b04a-4cf3-a491-6090bc1572fc.avro","schema-id":0,"first-row-id":13,"added-rows":0,"key-id":"VTWjHxdPbZFKJheX7XsR/Q=="}],"statistics":[],"partition-statistics":[],"snapshot-log":[{"timestamp-ms":1791460593552,"snapshot-id":564307663132197943},{"timestamp-ms":1791460593713,"snapshot-id":1122461367364127429},{"timestamp-ms":1791460593828,"snapshot-id":5112456484007752895},{"timestamp-ms":1791460593995,"snapshot-id":5555854819025587960}],"metadata-log":[{"timestamp-ms":1791460592557,"metadata-file":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/v1.metadata.json"},{"timestamp-ms":1791460593555,"metadata-file":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/v2.metadata.json"},{"timestamp-ms":1791460593713,"metadata-file":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/v3.metadata.json"},{"timestamp-ms":1791460593828,"metadata-file":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table/metadata/v4.metadata.json"}]} diff --git a/src/iceberg/test/standard_encryption_manager_test.cc b/src/iceberg/test/standard_encryption_manager_test.cc new file mode 100644 index 0000000000..1453051a24 --- /dev/null +++ b/src/iceberg/test/standard_encryption_manager_test.cc @@ -0,0 +1,562 @@ +/* + * 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/standard_encryption_manager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/arrow/arrow_io_util.h" +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encrypted_files.h" +#include "iceberg/encryption/encryption_register.h" +#include "iceberg/encryption/encryption_util.h" +#include "iceberg/encryption/in_memory_kms.h" +#include "iceberg/encryption/standard_key_metadata.h" +#include "iceberg/snapshot.h" +#include "iceberg/table_metadata.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/temp_file_test_base.h" +#include "iceberg/test/test_resource.h" + +namespace iceberg { + +namespace { + +// The master key for "keyA" used by the Java fixture under +// test/resources/encryption/table. +const std::vector kMasterKeyA = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', '0', '1', '2', '3', '4', '5'}; + +/// Counts calls to the KMS. +class CountingKms : public KeyManagementClient { + public: + explicit CountingKms(std::unique_ptr kms) : kms_(std::move(kms)) {} + + Result> WrapKey(std::span key, + std::string_view id) override { + ++wraps; + ICEBERG_ASSIGN_OR_RAISE(auto wrapped, kms_->WrapKey(key, id)); + if (after_wrap) { + after_wrap(); + } + return wrapped; + } + Result> UnwrapKey(std::span wrapped, + std::string_view id) override { + ++unwraps; + return kms_->UnwrapKey(wrapped, id); + } + int wraps = 0; + int unwraps = 0; + std::function after_wrap; + + private: + std::unique_ptr kms_; +}; + +std::shared_ptr MakeKms() { + auto kms = InMemoryKms::Make({{"keyA", kMasterKeyA}}); + EXPECT_THAT(kms, IsOk()); + return std::make_shared(std::move(kms.value())); +} + +} // namespace + +TEST(StandardEncryptionManagerTest, DecryptsJavaManifestListKeys) { + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, + ReadTableMetadataFromResource("encryption/table/metadata/v5.metadata.json")); + ASSERT_EQ(metadata->snapshots.size(), 4); + ASSERT_EQ(metadata->encryption_keys.size(), 5); + + auto kms = MakeKms(); + auto table_properties = TableProperties::FromMap({{"encryption.key-id", "keyA"}}); + ICEBERG_UNWRAP_OR_FAIL(auto manager, + EncryptionUtil::MakeEncryptionManager(metadata->encryption_keys, + table_properties, kms)); + + auto io = arrow::MakeLocalFileIO(); + constexpr std::string_view kAvroMagic = "Obj\x01"; + for (const auto& snapshot : metadata->snapshots) { + SCOPED_TRACE(snapshot->manifest_list); + ASSERT_TRUE(snapshot->key_id.has_value()); + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, EncryptionUtil::DecryptManifestListKeyMetadata( + manager, *snapshot->key_id)); + ICEBERG_UNWRAP_OR_FAIL(auto key_metadata, StandardKeyMetadata::Parse(decrypted)); + EXPECT_EQ(key_metadata.encryption_key().size(), 16); + const auto aad_prefix = key_metadata.aad_prefix(); + ASSERT_TRUE(aad_prefix.has_value()); + EXPECT_EQ(aad_prefix->size(), 16); + // The trusted length is the stored (encrypted) size of the manifest list file + auto name = std::filesystem::path(snapshot->manifest_list).filename().string(); + auto path = GetResourcePath("encryption/table/metadata/" + name); + ICEBERG_UNWRAP_OR_FAIL(auto raw, io->NewInputFile(path)); + ICEBERG_UNWRAP_OR_FAIL(auto stored_length, raw->Size()); + ICEBERG_UNWRAP_OR_FAIL(auto file_length, key_metadata.file_length()); + EXPECT_EQ(file_length, stored_length); + + ICEBERG_UNWRAP_OR_FAIL( + auto encrypted, EncryptedFiles::EncryptedInput( + std::move(raw), std::make_shared( + std::move(decrypted)))); + ICEBERG_UNWRAP_OR_FAIL(auto manifest_list, manager->Decrypt(std::move(encrypted))); + ICEBERG_UNWRAP_OR_FAIL(auto stream, manifest_list->Open()); + std::string magic(kAvroMagic.size(), '\0'); + ASSERT_THAT(stream->ReadFully(0, std::as_writable_bytes(std::span(magic))), IsOk()); + EXPECT_EQ(magic, kAvroMagic); + } + // One key encryption key for all snapshots, unwrapped once + EXPECT_EQ(kms->unwraps, 1); +} + +struct StandardEncryptionManagerTestAccess { + static void SetTimeShift(StandardEncryptionManager& manager, + std::chrono::milliseconds shift) { + std::lock_guard lock(manager.mutex_); + manager.test_time_shift_ = shift; + } + + static void AdvanceCacheAge(StandardEncryptionManager& manager, + std::chrono::milliseconds elapsed) { + std::lock_guard lock(manager.mutex_); + for (auto& [id, entry] : manager.unwrapped_key_cache_) { + entry.cached_at -= elapsed; + } + } + + static int64_t AdvanceTimeDuringWrap(StandardEncryptionManager& manager, + std::chrono::milliseconds elapsed) { + // RegisterKeyMetadata holds the mutex while calling WrapKey. + manager.test_time_shift_ += elapsed; + return manager.CurrentTimeMillis(); + } +}; + +TEST(StandardEncryptionManagerTest, RotatesKeyEncryptionKeys) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, + StandardEncryptionManager::Make({}, "keyA", 16, kms)); + ICEBERG_UNWRAP_OR_FAIL( + auto key_metadata, + StandardKeyMetadata::Make(std::vector(16, 1), std::nullopt, 100)); + + ICEBERG_UNWRAP_OR_FAIL(auto first, manager->RegisterKeyMetadata(key_metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto second, manager->RegisterKeyMetadata(key_metadata)); + EXPECT_EQ(second.key_encryption_key.key_id, first.key_encryption_key.key_id); + EXPECT_NE(second.file_key.key_id, first.file_key.key_id); + + StandardEncryptionManagerTestAccess::SetTimeShift( + *manager, StandardEncryptionManager::kKekLifespan); + ICEBERG_UNWRAP_OR_FAIL(auto third, manager->RegisterKeyMetadata(key_metadata)); + EXPECT_NE(third.key_encryption_key.key_id, first.key_encryption_key.key_id); + EXPECT_EQ(kms->wraps, 2); + + // Manifest lists encrypted with the old key encryption key stay readable + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, + manager->DecryptManifestListKeyMetadata(first.file_key.key_id)); + EXPECT_EQ(decrypted, key_metadata.Serialize()); +} + +TEST(StandardEncryptionManagerTest, RejectsInvalidKeyTimestamp) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL( + auto key_metadata, + StandardKeyMetadata::Make(std::vector(16, 1), std::nullopt, 100)); + + const std::vector> invalid_timestamps = { + std::nullopt, "", "123x", "9223372036854775808", "-1", "-9223372036854775808"}; + for (const auto& timestamp : invalid_timestamps) { + SCOPED_TRACE(timestamp.value_or("")); + EncryptedKey kek{.key_id = "invalid-kek", .encrypted_by_id = "keyA"}; + if (timestamp.has_value()) { + kek.properties.emplace(StandardEncryptionManager::kKeyTimestamp, *timestamp); + } + ICEBERG_UNWRAP_OR_FAIL(auto manager, + StandardEncryptionManager::Make({kek}, "keyA", 16, kms)); + EXPECT_THAT(manager->RegisterKeyMetadata(key_metadata), IsError(ErrorKind::kInvalid)); + EXPECT_EQ(kms->wraps, 0); + EXPECT_EQ(kms->unwraps, 0); + } +} + +TEST(StandardEncryptionManagerTest, TimestampsKeyAfterWrap) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, + StandardEncryptionManager::Make({}, "keyA", 16, kms)); + ICEBERG_UNWRAP_OR_FAIL(auto key_metadata, + StandardKeyMetadata::Make(std::vector(16, 1))); + std::optional wrap_time; + kms->after_wrap = [&] { + wrap_time = StandardEncryptionManagerTestAccess::AdvanceTimeDuringWrap( + *manager, std::chrono::hours{1}); + }; + + ICEBERG_UNWRAP_OR_FAIL(auto keys, manager->RegisterKeyMetadata(key_metadata)); + ASSERT_TRUE(wrap_time.has_value()); + const auto& properties = keys.key_encryption_key.properties; + auto timestamp = properties.find(std::string(StandardEncryptionManager::kKeyTimestamp)); + ASSERT_NE(timestamp, properties.end()); + EXPECT_GE(std::stoll(timestamp->second), *wrap_time); +} + +TEST(StandardEncryptionManagerTest, UnwrappedKeyCacheExpires) { + ICEBERG_UNWRAP_OR_FAIL( + auto metadata, + ReadTableMetadataFromResource("encryption/table/metadata/v5.metadata.json")); + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, StandardEncryptionManager::Make( + metadata->encryption_keys, "keyA", 16, kms)); + const auto& key_id = *metadata->snapshots.front()->key_id; + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + EXPECT_EQ(kms->unwraps, 1); + + StandardEncryptionManagerTestAccess::AdvanceCacheAge(*manager, + std::chrono::minutes{59}); + StandardEncryptionManagerTestAccess::SetTimeShift(*manager, std::chrono::hours{2}); + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + EXPECT_EQ(kms->unwraps, 1); + + // The hit at 59 minutes does not extend the original entry's lifetime. + StandardEncryptionManagerTestAccess::AdvanceCacheAge(*manager, std::chrono::minutes{2}); + StandardEncryptionManagerTestAccess::SetTimeShift(*manager, -std::chrono::hours{2}); + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + EXPECT_EQ(kms->unwraps, 2); +} + +namespace { + +Result ReadAll(InputFile& file) { + ICEBERG_ASSIGN_OR_RAISE(auto size, file.Size()); + ICEBERG_ASSIGN_OR_RAISE(auto stream, file.Open()); + std::string out(size, '\0'); + ICEBERG_RETURN_UNEXPECTED(stream->ReadFully(0, std::as_writable_bytes(std::span(out)))); + return out; +} + +/// A NativeEncryptionKeyMetadata that implements nothing beyond the required members. +class MinimalNativeKeyMetadata : public NativeEncryptionKeyMetadata { + public: + std::vector buffer() const override { return {0xf0, 0x01, 0x23}; } + std::shared_ptr Copy() const override { + return std::make_shared(*this); + } + std::span encryption_key() const override { return key_; } + std::optional> aad_prefix() const override { + return std::nullopt; + } + + private: + std::vector key_ = std::vector(16, 1); +}; + +class StandardEncryptionManagerFileTest : public TempFileTestBase { + protected: + void SetUp() override { + TempFileTestBase::SetUp(); + ICEBERG_UNWRAP_OR_FAIL(manager_, + StandardEncryptionManager::Make({}, "keyA", 16, kms_)); + } + + template + void CheckBatch(Manager* manager, bool expect_key_metadata) { + EncryptionManager* base = manager; + ICEBERG_UNWRAP_OR_FAIL(auto empty_outputs, + base->Encrypt(std::vector>{})); + EXPECT_TRUE(empty_outputs.empty()); + ICEBERG_UNWRAP_OR_FAIL( + auto empty_inputs, + manager->Decrypt(std::vector>{})); + EXPECT_TRUE(empty_inputs.empty()); + + std::vector paths{CreateNewTempFilePath(), CreateNewTempFilePath()}; + std::vector> outputs; + for (const auto& path : paths) { + ICEBERG_UNWRAP_OR_FAIL(auto output, io_->NewOutputFile(path)); + outputs.push_back(std::move(output)); + } + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager->Encrypt(std::move(outputs))); + ASSERT_EQ(encrypted.size(), paths.size()); + + std::vector> inputs; + for (size_t i = 0; i < paths.size(); ++i) { + auto& output = encrypted[i]->encrypting_output_file(); + EXPECT_EQ(output.location(), paths[i]); + ICEBERG_UNWRAP_OR_FAIL(auto stream, output.Create()); + ASSERT_THAT(stream->Write(std::as_bytes(std::span(paths[i]))), IsOk()); + ASSERT_THAT(stream->Close(), IsOk()); + const auto& metadata = encrypted[i]->key_metadata(); + EXPECT_EQ(metadata.has_value(), expect_key_metadata); + std::shared_ptr key; + if (expect_key_metadata) { + auto* native = dynamic_cast(&metadata); + ASSERT_NE(native, nullptr); + ICEBERG_UNWRAP_OR_FAIL(auto stored, stream->StoredLength()); + ICEBERG_UNWRAP_OR_FAIL(key, native->CopyWithLength(stored)); + } else { + key = metadata.Copy(); + } + ICEBERG_UNWRAP_OR_FAIL(auto input, io_->NewInputFile(paths[i])); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted_input, EncryptedFiles::EncryptedInput( + std::move(input), std::move(key))); + inputs.push_back(std::move(encrypted_input)); + } + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, base->Decrypt(std::move(inputs))); + ASSERT_EQ(decrypted.size(), paths.size()); + for (size_t i = 0; i < paths.size(); ++i) { + EXPECT_THAT(ReadAll(*decrypted[i]), HasValue(::testing::Eq(paths[i]))); + } + } + + std::unique_ptr io_ = arrow::MakeLocalFileIO(); + std::shared_ptr kms_ = MakeKms(); + std::shared_ptr manager_; +}; + +} // namespace + +TEST_F(StandardEncryptionManagerFileTest, BatchOverloadsReachableFromConcreteAndBase) { + PlaintextEncryptionManager plaintext; + CheckBatch(&plaintext, false); + CheckBatch(manager_.get(), true); +} + +TEST_F(StandardEncryptionManagerFileTest, ReadsStreamWithRegisteredManifestListKeys) { + auto path = CreateNewTempFilePath(); + const std::string plain = "manifest list"; + ICEBERG_UNWRAP_OR_FAIL(auto output, io_->NewOutputFile(path)); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager_->Encrypt(std::move(output))); + auto* native = dynamic_cast(encrypted.get()); + ASSERT_NE(native, nullptr); + + const auto& key_metadata = native->key_metadata(); + const auto aad_prefix = key_metadata.aad_prefix(); + ASSERT_TRUE(aad_prefix.has_value()); + EXPECT_EQ(aad_prefix->size(), 16u); + ICEBERG_UNWRAP_OR_FAIL(auto initial_length, key_metadata.file_length()); + EXPECT_FALSE(initial_length.has_value()); + + EXPECT_EQ(native->location(), path); + ICEBERG_UNWRAP_OR_FAIL(auto stream, native->CreateOrOverwrite()); + ASSERT_THAT(stream->Write(std::as_bytes(std::span(plain))), IsOk()); + ASSERT_THAT(stream->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto stored, stream->StoredLength()); + EXPECT_GT(stored, static_cast(plain.size())); + EXPECT_EQ(stored, static_cast(std::filesystem::file_size(path))); + + // Reading a valid AGS1 file still requires its length in trusted key metadata. + ICEBERG_UNWRAP_OR_FAIL(auto raw_without_length, io_->NewInputFile(path)); + ICEBERG_UNWRAP_OR_FAIL( + auto input_without_length, + EncryptedFiles::EncryptedInput(std::move(raw_without_length), key_metadata.Copy())); + ICEBERG_UNWRAP_OR_FAIL(auto without_length, + manager_->Decrypt(std::move(input_without_length))); + EXPECT_THAT(without_length->Size(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(without_length->Open(), IsError(ErrorKind::kInvalid)); + + ICEBERG_UNWRAP_OR_FAIL(auto with_length, key_metadata.CopyWithLength(stored)); + EXPECT_TRUE( + std::ranges::equal(with_length->encryption_key(), key_metadata.encryption_key())); + const auto copied_aad_prefix = with_length->aad_prefix(); + ASSERT_TRUE(copied_aad_prefix.has_value()); + EXPECT_TRUE(std::ranges::equal(*copied_aad_prefix, *aad_prefix)); + ICEBERG_UNWRAP_OR_FAIL(auto copied_length, with_length->file_length()); + EXPECT_EQ(copied_length, stored); + ICEBERG_UNWRAP_OR_FAIL(auto original_length, key_metadata.file_length()); + EXPECT_FALSE(original_length.has_value()); + + ICEBERG_UNWRAP_OR_FAIL(auto keys, manager_->RegisterKeyMetadata(*with_length)); + EXPECT_EQ(keys.key_encryption_key.encrypted_by_id, "keyA"); + EXPECT_TRUE(keys.key_encryption_key.properties.contains("KEY_TIMESTAMP")); + EXPECT_EQ(keys.file_key.encrypted_by_id, keys.key_encryption_key.key_id); + EXPECT_EQ(kms_->wraps, 1); + EXPECT_EQ(manager_->encryption_keys().size(), 2u); + ICEBERG_UNWRAP_OR_FAIL( + auto reader, StandardEncryptionManager::Make( + {keys.key_encryption_key, keys.file_key}, "keyA", 16, MakeKms())); + EXPECT_THAT(reader->DecryptManifestListKeyMetadata(keys.key_encryption_key.key_id), + IsError(ErrorKind::kInvalid)); + EXPECT_THAT(reader->DecryptManifestListKeyMetadata("missing"), + IsError(ErrorKind::kInvalid)); + ICEBERG_UNWRAP_OR_FAIL(auto serialized, EncryptionUtil::DecryptManifestListKeyMetadata( + reader, keys.file_key.key_id)); + EXPECT_EQ(serialized, with_length->buffer()); + ICEBERG_UNWRAP_OR_FAIL(auto raw, io_->NewInputFile(path)); + ICEBERG_UNWRAP_OR_FAIL(auto input, + EncryptedFiles::EncryptedInput( + std::move(raw), std::make_shared( + std::move(serialized)))); + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, reader->Decrypt(std::move(input))); + ICEBERG_UNWRAP_OR_FAIL(auto size, decrypted->Size()); + ASSERT_EQ(size, static_cast(plain.size())); + ICEBERG_UNWRAP_OR_FAIL(auto read_stream, decrypted->Open()); + auto* native_input = dynamic_cast(decrypted.get()); + ASSERT_NE(native_input, nullptr); + auto detached = std::move(*native_input).DetachInputFile(); + ASSERT_NE(detached, nullptr); + decrypted.reset(); + detached.reset(); + + std::string bytes(plain.size(), '\0'); + ASSERT_THAT(read_stream->ReadFully(0, std::as_writable_bytes(std::span(bytes))), + IsOk()); + EXPECT_EQ(bytes, plain); +} + +TEST_F(StandardEncryptionManagerFileTest, NativeFilesExposeRawBytesWithoutFileLength) { + const std::string raw = "native format bytes"; + auto path = CreateNewTempFilePath(); + ICEBERG_UNWRAP_OR_FAIL(auto output, io_->NewOutputFile(path)); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager_->Encrypt(std::move(output))); + auto* native_output = dynamic_cast(encrypted.get()); + ASSERT_NE(native_output, nullptr); + ICEBERG_UNWRAP_OR_FAIL(auto stream, native_output->plain_output_file().Create()); + ASSERT_THAT(stream->Write(std::as_bytes(std::span(raw))), IsOk()); + ASSERT_THAT(stream->Close(), IsOk()); + + const auto& metadata = native_output->key_metadata(); + const auto aad_prefix = metadata.aad_prefix(); + ASSERT_TRUE(aad_prefix.has_value()); + std::vector> variants = { + metadata.Copy(), std::make_shared(metadata.buffer())}; + for (const auto& key_metadata : variants) { + ICEBERG_UNWRAP_OR_FAIL(auto input, io_->NewInputFile(path)); + auto* raw_handle = input.get(); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted_input, EncryptedFiles::EncryptedInput( + std::move(input), key_metadata)); + auto* wrapper = encrypted_input.get(); + EXPECT_EQ(EncryptedInputFile::AsNative(encrypted_input), nullptr); + ASSERT_EQ(encrypted_input.get(), wrapper); + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, manager_->Decrypt(std::move(encrypted_input))); + auto* native = dynamic_cast(decrypted.get()); + ASSERT_NE(native, nullptr); + EXPECT_TRUE(std::ranges::equal(native->key_metadata().encryption_key(), + metadata.encryption_key())); + const auto actual_aad_prefix = native->key_metadata().aad_prefix(); + ASSERT_TRUE(actual_aad_prefix.has_value()); + EXPECT_TRUE(std::ranges::equal(*actual_aad_prefix, *aad_prefix)); + decrypted.release(); + ICEBERG_UNWRAP_OR_FAIL( + auto second, manager_->Decrypt(std::unique_ptr(native))); + ASSERT_EQ(dynamic_cast(second.get()), native); + + auto detached = std::move(*native).DetachInputFile(); + ASSERT_EQ(detached.get(), raw_handle); + EXPECT_EQ(std::move(*native).DetachInputFile(), nullptr); + second.reset(); + EXPECT_THAT(ReadAll(*detached), HasValue(::testing::Eq(raw))); + } +} + +TEST(StandardEncryptionManagerTest, RegistersOpaqueNativeMetadataWithoutFileLength) { + MinimalNativeKeyMetadata metadata; + EXPECT_THAT(metadata.file_length(), IsError(ErrorKind::kNotSupported)); + EXPECT_THAT(metadata.CopyWithLength(1), IsError(ErrorKind::kNotSupported)); + ICEBERG_UNWRAP_OR_FAIL(auto manager, + StandardEncryptionManager::Make({}, "keyA", 16, MakeKms())); + ICEBERG_UNWRAP_OR_FAIL(auto keys, manager->RegisterKeyMetadata(metadata)); + EXPECT_THAT(manager->DecryptManifestListKeyMetadata(keys.file_key.key_id), + HasValue(::testing::Eq(metadata.buffer()))); +} + +class EncryptionUtilTest : public ::testing::Test { + protected: + void TearDown() override { + EncryptionManagerRegistry::Register({}); + encryption::RegisterAll(); + } +}; + +TEST_F(EncryptionUtilTest, SelectsManagerByTableKeyId) { + auto kms = MakeKms(); + auto custom = std::make_shared(); + int factory_calls = 0; + encryption::RegisterAll(); + EncryptionManagerRegistry::Register([&](const std::vector&, + const TableProperties&, + std::shared_ptr kms_client) + -> Result> { + ++factory_calls; + EXPECT_EQ(kms_client, kms); + return custom; + }); + encryption::RegisterAll(); + auto properties = TableProperties::FromMap({{"encryption.data-key-length", "unused"}}); + EXPECT_THAT(EncryptionUtil::MakeEncryptionManager({}, properties, nullptr), + IsError(ErrorKind::kInvalidArgument)); + ICEBERG_UNWRAP_OR_FAIL(auto plaintext, + EncryptionUtil::MakeEncryptionManager({}, properties, kms)); + EXPECT_NE(dynamic_cast(plaintext.get()), nullptr); + EXPECT_NE(plaintext, custom); + + properties.mutable_configs()["encryption.key-id"] = ""; + EXPECT_THAT(EncryptionUtil::MakeEncryptionManager({}, properties, kms), + IsError(ErrorKind::kInvalidArgument)); + properties.mutable_configs()["encryption.key-id"] = "custom-key"; + EXPECT_THAT(EncryptionUtil::MakeEncryptionManager({}, properties, nullptr), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_EQ(factory_calls, 0); + ICEBERG_UNWRAP_OR_FAIL(auto selected, + EncryptionUtil::MakeEncryptionManager({}, properties, kms)); + EXPECT_EQ(selected, custom); + EXPECT_EQ(factory_calls, 1); +} + +TEST(StandardEncryptionManagerTest, FactoryUsesTableProperties) { + EncryptionManagerRegistry::Register({}); + encryption::RegisterAll(); + EXPECT_TRUE(encryption::IsEncryptionAvailable()); + auto io = arrow::MakeLocalFileIO(); + auto properties = TableProperties::FromMap({{"encryption.key-id", "keyA"}}); + const auto& dek_length = TableProperties::kEncryptionDekLength.key(); + constexpr std::array, 4> lengths = { + {{nullptr, 16}, {"16", 16}, {"24", 24}, {"32", 32}}}; + for (const auto& [configured, expected] : lengths) { + if (configured) { + properties.mutable_configs()[dek_length] = configured; + } + ICEBERG_UNWRAP_OR_FAIL( + auto manager, EncryptionUtil::MakeEncryptionManager({}, properties, MakeKms())); + ICEBERG_UNWRAP_OR_FAIL(auto output, io->NewOutputFile("data-file.parquet")); + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager->Encrypt(std::move(output))); + auto* metadata = + dynamic_cast(&encrypted->key_metadata()); + ASSERT_NE(metadata, nullptr); + EXPECT_EQ(metadata->encryption_key().size(), expected); + } + + for (const auto* invalid : {"20", "invalid", "16x"}) { + properties.mutable_configs()[dek_length] = invalid; + EXPECT_THAT(EncryptionUtil::MakeEncryptionManager({}, properties, MakeKms()), + IsError(ErrorKind::kInvalidArgument)); + } +} + +} // namespace iceberg diff --git a/src/iceberg/test/standard_key_metadata_test.cc b/src/iceberg/test/standard_key_metadata_test.cc index dd83c1ce34..09a12bdded 100644 --- a/src/iceberg/test/standard_key_metadata_test.cc +++ b/src/iceberg/test/standard_key_metadata_test.cc @@ -19,6 +19,7 @@ #include "iceberg/encryption/standard_key_metadata.h" +#include #include #include @@ -60,48 +61,74 @@ TEST(StandardKeyMetadataTest, ParseJavaVectors) { const auto& with_length = kJavaKeyMetadataWithLength; ICEBERG_UNWRAP_OR_FAIL(auto parsed, StandardKeyMetadata::Parse(with_length)); - EXPECT_EQ(parsed.encryption_key, key); - EXPECT_EQ(parsed.aad_prefix, aad_prefix); - EXPECT_EQ(parsed.file_length, 1234567); + EXPECT_TRUE(std::ranges::equal(parsed.encryption_key(), key)); + ASSERT_TRUE(parsed.aad_prefix().has_value()); + EXPECT_TRUE(std::ranges::equal(*parsed.aad_prefix(), aad_prefix)); + ICEBERG_UNWRAP_OR_FAIL(auto length, parsed.file_length()); + EXPECT_EQ(length, 1234567); // Serialization is byte-for-byte identical to Java EXPECT_EQ(parsed.Serialize(), with_length); const auto& without_length = kJavaKeyMetadata; ICEBERG_UNWRAP_OR_FAIL(auto parsed2, StandardKeyMetadata::Parse(without_length)); - EXPECT_EQ(parsed2.encryption_key, key); - EXPECT_FALSE(parsed2.file_length.has_value()); + EXPECT_TRUE(std::ranges::equal(parsed2.encryption_key(), key)); + ICEBERG_UNWRAP_OR_FAIL(auto missing_length, parsed2.file_length()); + EXPECT_FALSE(missing_length.has_value()); EXPECT_EQ(parsed2.Serialize(), without_length); - EXPECT_EQ(parsed2.WithFileLength(1234567).Serialize(), with_length); + ICEBERG_UNWRAP_OR_FAIL(auto resized, parsed2.WithFileLength(1234567)); + EXPECT_EQ(resized.Serialize(), with_length); } TEST(StandardKeyMetadataTest, RoundTrip) { - StandardKeyMetadata metadata{.encryption_key = TestBytes(32, 7)}; + ICEBERG_UNWRAP_OR_FAIL(auto metadata, StandardKeyMetadata::Make(TestBytes(32, 7))); ICEBERG_UNWRAP_OR_FAIL(auto parsed, StandardKeyMetadata::Parse(metadata.Serialize())); EXPECT_EQ(parsed, metadata); + EXPECT_FALSE(parsed.aad_prefix().has_value()); - // Zig-zag varint boundaries, including negative values and ten-byte encodings - for (int64_t length : - {int64_t{0}, int64_t{63}, int64_t{64}, int64_t{1} << 40, int64_t{-1}, - std::numeric_limits::min(), std::numeric_limits::max()}) { - auto with_length = metadata.WithFileLength(length); + // Zig-zag varint boundaries, including a ten-byte encoding. + for (int64_t length : {int64_t{0}, int64_t{63}, int64_t{64}, int64_t{1} << 40, + std::numeric_limits::max()}) { + ICEBERG_UNWRAP_OR_FAIL(auto with_length, metadata.WithFileLength(length)); ICEBERG_UNWRAP_OR_FAIL(auto round_trip, StandardKeyMetadata::Parse(with_length.Serialize())); - EXPECT_EQ(round_trip, with_length); + ICEBERG_UNWRAP_OR_FAIL(auto parsed_length, round_trip.file_length()); + EXPECT_EQ(parsed_length, length); } + // Avro accepts signed lengths. Preserve their encoding when reading existing metadata. + auto serialized = metadata.Serialize(); + serialized.back() = 2; // file_length's long branch. + serialized.push_back(1); // -1 + ICEBERG_UNWRAP_OR_FAIL(auto negative, StandardKeyMetadata::Parse(serialized)); + ICEBERG_UNWRAP_OR_FAIL(auto negative_length, negative.file_length()); + EXPECT_EQ(negative_length, -1); + EXPECT_EQ(negative.Serialize(), serialized); + + serialized.pop_back(); + serialized.insert(serialized.end(), 9, 0xff); + serialized.push_back(1); // INT64_MIN + ICEBERG_UNWRAP_OR_FAIL(auto minimum, StandardKeyMetadata::Parse(serialized)); + ICEBERG_UNWRAP_OR_FAIL(auto minimum_length, minimum.file_length()); + EXPECT_EQ(minimum_length, std::numeric_limits::min()); + EXPECT_EQ(minimum.Serialize(), serialized); + // A present but empty AAD prefix is distinct from an absent one - StandardKeyMetadata empty_aad{.encryption_key = TestBytes(16, 7), - .aad_prefix = std::vector{}}; + ICEBERG_UNWRAP_OR_FAIL(auto empty_aad, StandardKeyMetadata::Make( + TestBytes(16, 7), std::vector{})); ICEBERG_UNWRAP_OR_FAIL(auto parsed_empty, StandardKeyMetadata::Parse(empty_aad.Serialize())); - ASSERT_TRUE(parsed_empty.aad_prefix.has_value()); - EXPECT_TRUE(parsed_empty.aad_prefix->empty()); - ICEBERG_UNWRAP_OR_FAIL(auto parsed_null, - StandardKeyMetadata::Parse(metadata.Serialize())); - EXPECT_FALSE(parsed_null.aad_prefix.has_value()); + ASSERT_TRUE(parsed_empty.aad_prefix().has_value()); + EXPECT_TRUE(parsed_empty.aad_prefix()->empty()); } TEST(StandardKeyMetadataTest, InvalidInput) { + EXPECT_THAT(StandardKeyMetadata::Make(TestBytes(15, 7)), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(StandardKeyMetadata::Make(TestBytes(16, 7), std::nullopt, -1), + IsError(ErrorKind::kInvalidArgument)); + ICEBERG_UNWRAP_OR_FAIL(auto metadata, StandardKeyMetadata::Make(TestBytes(16, 7))); + EXPECT_THAT(metadata.CopyWithLength(-1), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(StandardKeyMetadata::Parse(std::vector{}), IsError(ErrorKind::kInvalid)); // Unknown schema version diff --git a/src/iceberg/type_fwd.h b/src/iceberg/type_fwd.h index 354495e387..47ddcbdf5b 100644 --- a/src/iceberg/type_fwd.h +++ b/src/iceberg/type_fwd.h @@ -21,6 +21,8 @@ #include +#include "iceberg/encryption/type_fwd.h" + /// \file iceberg/type_fwd.h /// Forward declarations and enum definitions. When writing your own headers, /// you can include this instead of the "full" headers to help reduce compile @@ -295,7 +297,4 @@ class MetadataScanTaskReader; class RefsTable; class SnapshotsTable; -/// \brief Table encryption -struct EncryptedKey; - } // namespace iceberg