diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 4cde4fb23f..93b4d64b13 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 @@ -325,6 +327,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_data_util.cc parquet/parquet_metrics.cc parquet/parquet_metrics_row_group_filter.cc @@ -339,7 +342,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}. @@ -414,6 +419,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 d9c64d36a2..58bc0de876 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -48,7 +48,11 @@ #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/exception.h" @@ -217,6 +221,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" @@ -224,7 +229,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..7ddb2797cb 100644 --- a/src/iceberg/encryption/CMakeLists.txt +++ b/src/iceberg/encryption/CMakeLists.txt @@ -17,14 +17,27 @@ 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) +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/encrypted_file.h b/src/iceberg/encryption/encrypted_file.h new file mode 100644 index 0000000000..e49cc77fbc --- /dev/null +++ b/src/iceberg/encryption/encrypted_file.h @@ -0,0 +1,142 @@ +/* + * 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 + +#include "iceberg/encryption/encryption_key_metadata.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 Give up the still-encrypted raw input file. + virtual std::unique_ptr ReleaseInputFile() = 0; + + /// \brief The key metadata needed to decrypt this file. + virtual const EncryptionKeyMetadata& key_metadata() const = 0; +}; + +/// \brief EncryptedInputFile backed by a plain InputFile and opaque key metadata. +class ICEBERG_EXPORT BaseEncryptedInputFile : public EncryptedInputFile { + public: + BaseEncryptedInputFile(std::unique_ptr encrypted_file, + std::shared_ptr key_metadata) + : encrypted_file_(std::move(encrypted_file)), + key_metadata_(std::move(key_metadata)) {} + + std::unique_ptr ReleaseInputFile() override { + return std::move(encrypted_file_); + } + + const EncryptionKeyMetadata& key_metadata() const override { return *key_metadata_; } + + private: + std::unique_ptr encrypted_file_; + std::shared_ptr key_metadata_; +}; + +/// \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: +/// ReleaseInputFile() gives the still-encrypted raw file and key_metadata() gives the +/// key parameters (and AAD prefix) the native reader needs. +/// - 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; +}; + +/// \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 The output file that writers should use. + /// + /// Unlike EncryptedInputFile::ReleaseInputFile, this is a non-consuming accessor: + /// implementations may need to keep ownership to finalize encryption on Close. + 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 EncryptedOutputFile backed by a plain OutputFile and opaque key metadata. +class ICEBERG_EXPORT BaseEncryptedOutputFile : public EncryptedOutputFile { + public: + BaseEncryptedOutputFile(std::unique_ptr output_file, + std::shared_ptr key_metadata) + : output_file_(std::move(output_file)), key_metadata_(std::move(key_metadata)) {} + + OutputFile& encrypting_output_file() const override { return *output_file_; } + const EncryptionKeyMetadata& key_metadata() const override { return *key_metadata_; } + + private: + std::unique_ptr output_file_; + std::shared_ptr key_metadata_; +}; + +/// \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..ad3c5471f2 --- /dev/null +++ b/src/iceberg/encryption/encrypted_files.cc @@ -0,0 +1,40 @@ +/* + * 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 + +namespace iceberg { + +std::unique_ptr EncryptedFiles::Encrypted( + std::unique_ptr encrypted_file, + std::shared_ptr key_metadata) { + return std::make_unique(std::move(encrypted_file), + std::move(key_metadata)); +} + +std::unique_ptr EncryptedFiles::Encrypted( + std::unique_ptr output_file, + std::shared_ptr key_metadata) { + return std::make_unique(std::move(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..ee77cebc31 --- /dev/null +++ b/src/iceberg/encryption/encrypted_files.h @@ -0,0 +1,50 @@ +/* + * 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/encrypted_file.h" +#include "iceberg/iceberg_export.h" + +namespace iceberg { + +/// \brief Builds EncryptedInputFile / EncryptedOutputFile wrappers around a plain file +/// and its key metadata, for callers that do not need the native (modular) encryption +/// wrappers. +class ICEBERG_EXPORT EncryptedFiles { + public: + /// \brief Wrap a still-encrypted input file together with its key metadata. + static std::unique_ptr Encrypted( + std::unique_ptr encrypted_file, + std::shared_ptr key_metadata); + + /// \brief Wrap a plaintext output file together with the key metadata used (or to be + /// used) to encrypt it. + static std::unique_ptr Encrypted( + std::unique_ptr 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..c780594ad4 --- /dev/null +++ b/src/iceberg/encryption/encryption_key_metadata.h @@ -0,0 +1,122 @@ +/* + * 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 "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 The serialized form of this key metadata. + /// + /// Implementations must not cache this value if their fields can change after + /// construction; it is recomputed on every call where that matters. + 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. +class ICEBERG_EXPORT NativeEncryptionKeyMetadata : public EncryptionKeyMetadata { + public: + /// \brief The data encryption key. + virtual const std::vector& EncryptionKey() const = 0; + + /// \brief The AAD prefix (file ID) used to bind ciphertext to this file, if any. + virtual const std::optional>& AadPrefix() 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> FileLength() const { + return NotSupported("FileLength 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..538720d424 --- /dev/null +++ b/src/iceberg/encryption/encryption_manager.cc @@ -0,0 +1,105 @@ +/* + * 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/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) { + return encrypted->ReleaseInputFile(); +} + +Result> PlaintextEncryptionManager::Encrypt( + std::unique_ptr plain) { + return std::make_unique(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 = std::move(factory); +} + +Result> EncryptionManagerRegistry::Make( + Options options) { + ICEBERG_PRECHECK(!options.table_key_id.empty(), "Invalid encryption key ID: empty"); + ICEBERG_PRECHECK(options.data_key_length == 16 || options.data_key_length == 24 || + options.data_key_length == 32, + "Invalid data key length: {} (must be 16, 24, or 32)", + options.data_key_length); + ICEBERG_PRECHECK(options.kms != nullptr, + "Cannot create an encryption manager without a KMS client; set the " + "encryption.kms-type or encryption.kms-impl catalog property"); + Factory factory; + { + auto& state = State(); + std::lock_guard lock(state.mutex); + factory = state.factory; + } + if (!factory) { + return NotSupported( + "Table encryption is not available: link iceberg_bundle built with " + "ICEBERG_ENCRYPTION=ON and call iceberg::encryption::RegisterAll()"); + } + return factory(std::move(options)); +} + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_manager.h b/src/iceberg/encryption/encryption_manager.h new file mode 100644 index 0000000000..c6cde92c7f --- /dev/null +++ b/src/iceberg/encryption/encryption_manager.h @@ -0,0 +1,119 @@ +/* + * 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 +#include + +#include "iceberg/encryption/encrypted_file.h" +#include "iceberg/encryption/encrypted_key.h" +#include "iceberg/encryption/key_management_client.h" +#include "iceberg/file_io.h" +#include "iceberg/iceberg_export.h" +#include "iceberg/result.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) and of EncryptedFiles / EncryptionUtil, which build the EncryptedInputFile / +/// EncryptedOutputFile wrappers this interface consumes. 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. + 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 registers the standard implementation (see +/// iceberg::encryption::RegisterAll()). Without it, encrypted tables cannot be read or +/// written. A registry is used so that the core library can reach a standard-specific +/// implementation without depending on it directly; Options is therefore +/// standard-specific and not part of the general EncryptionManager contract. +class ICEBERG_EXPORT EncryptionManagerRegistry { + public: + struct Options { + /// The table master key ID in the KMS (table property `encryption.key-id`), taken + /// from a trusted source. + std::string table_key_id; + /// Length of generated data keys: 16, 24 or 32 bytes. + int32_t data_key_length = 16; + /// The table metadata `encryption-keys`. + std::vector encryption_keys; + /// The catalog's KMS client. + std::shared_ptr kms; + }; + + using Factory = + std::function>(Options options)>; + + /// \brief Register the encryption manager implementation. + static void Register(Factory factory); + + /// \brief Create an encryption manager. + static Result> Make(Options options); +}; + +} // namespace iceberg diff --git a/src/iceberg/encryption/encryption_register.cc b/src/iceberg/encryption/encryption_register.cc new file mode 100644 index 0000000000..3df7383c2b --- /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" + +#if ICEBERG_ENCRYPTION_ENABLED +# include "iceberg/encryption/standard_encryption_manager.h" +#endif + +namespace iceberg::encryption { + +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..beacad013e --- /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 encryption manager, if the bundle was built with +/// ICEBERG_ENCRYPTION=ON. Otherwise a no-op, and encrypted tables are not supported. +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..bfa981ca0f --- /dev/null +++ b/src/iceberg/encryption/encryption_util.cc @@ -0,0 +1,37 @@ +/* + * 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 "iceberg/encryption/standard_encryption_manager.h" + +namespace iceberg { + +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..d8c9ff1e08 --- /dev/null +++ b/src/iceberg/encryption/encryption_util.h @@ -0,0 +1,48 @@ +/* + * 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/encryption_manager.h" +#include "iceberg/iceberg_bundle_export.h" +#include "iceberg/result.h" + +namespace iceberg { + +/// \brief Standard-specific operations reached through a generic EncryptionManager. +class ICEBERG_BUNDLE_EXPORT EncryptionUtil { + public: + /// \brief Decrypt manifest list key metadata, as stored in 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/standard_encryption_manager.cc b/src/iceberg/encryption/standard_encryption_manager.cc new file mode 100644 index 0000000000..97fe947eb9 --- /dev/null +++ b/src/iceberg/encryption/standard_encryption_manager.cc @@ -0,0 +1,398 @@ +/* + * 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/util/base64.h" +#include "iceberg/util/macros.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)); +} + +std::optional ParseTimestamp(const EncryptedKey& key) { + auto it = key.properties.find(std::string(StandardEncryptionManager::kKeyTimestamp)); + if (it == key.properties.end()) { + return std::nullopt; + } + 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 std::nullopt; + } + return value; +} + +// Forwards to a file owned elsewhere, so one underlying file can serve both the native +// path and the AGS1 stream path of a Native wrapper. +class SharedInputFile : public InputFile { + public: + explicit SharedInputFile(std::shared_ptr file) : file_(std::move(file)) {} + + std::string_view location() const override { return file_->location(); } + Result Size() const override { return file_->Size(); } + Result> Open() override { return file_->Open(); } + + private: + std::shared_ptr file_; +}; + +class SharedOutputFile : public OutputFile { + public: + explicit SharedOutputFile(std::shared_ptr file) : file_(std::move(file)) {} + + std::string_view location() const override { return file_->location(); } + Result> Create() override { + return file_->Create(); + } + Result> CreateOrOverwrite() override { + return file_->CreateOrOverwrite(); + } + + private: + std::shared_ptr file_; +}; + +// Mirrors Java's StandardDecryptedInputFile: the raw file and key metadata are available +// to native readers right away, while the AGS1 reader, which needs the encrypted file +// length from the key metadata, is built on first use of the InputFile methods. +class StandardDecryptedInputFile : public NativeEncryptionInputFile { + public: + StandardDecryptedInputFile(std::shared_ptr raw, StandardKeyMetadata metadata) + : raw_(std::move(raw)), metadata_(std::move(metadata)) {} + + std::unique_ptr ReleaseInputFile() override { + return std::make_unique(raw_); + } + const NativeEncryptionKeyMetadata& key_metadata() const override { return metadata_; } + + std::string_view location() const override { return raw_->location(); } + Result Size() const override { + ICEBERG_ASSIGN_OR_RAISE(auto file, Decrypting()); + return file->Size(); + } + Result> Open() override { + ICEBERG_ASSIGN_OR_RAISE(auto file, Decrypting()); + return file->Open(); + } + + private: + Result Decrypting() const { + if (decrypting_ == nullptr) { + if (!metadata_.file_length.has_value()) { + // The length must come from trusted key metadata, not from the file system, so + // that truncation is detected (format/gcm-stream-spec.md, "File length"). + return Invalid("Cannot read AES GCM stream {}: key metadata has no file length", + raw_->location()); + } + decrypting_ = std::make_unique( + std::make_unique(raw_), metadata_.encryption_key, + metadata_.aad_prefix.value_or(std::vector{}), *metadata_.file_length); + } + return decrypting_.get(); + } + + std::shared_ptr raw_; + StandardKeyMetadata metadata_; + mutable std::unique_ptr decrypting_; +}; + +// Mirrors Java's StandardEncryptedOutputFile: native writers use the plain file and the +// key metadata; the AGS1 writer over the same file and key is built on first use. +class StandardEncryptedOutputFile : public NativeEncryptionOutputFile { + public: + StandardEncryptedOutputFile(std::shared_ptr plain, + StandardKeyMetadata metadata) + : plain_(std::move(plain)), metadata_(std::move(metadata)) {} + + OutputFile& plain_output_file() const override { return *plain_; } + OutputFile& encrypting_output_file() const override { + if (encrypting_ == nullptr) { + encrypting_ = std::make_unique( + std::make_unique(plain_), metadata_.encryption_key, + metadata_.aad_prefix.value_or(std::vector{})); + } + return *encrypting_; + } + const NativeEncryptionKeyMetadata& key_metadata() const override { return metadata_; } + + private: + std::shared_ptr plain_; + StandardKeyMetadata metadata_; + mutable std::unique_ptr encrypting_; +}; + +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); +} + +} // namespace + +Result> StandardEncryptionManager::Make( + EncryptionManagerRegistry::Options options) { + ICEBERG_PRECHECK(!options.table_key_id.empty(), "Invalid encryption key ID: empty"); + ICEBERG_PRECHECK(options.data_key_length == 16 || options.data_key_length == 24 || + options.data_key_length == 32, + "Invalid data key length: {} (must be 16, 24, or 32)", + options.data_key_length); + ICEBERG_PRECHECK(options.kms != nullptr, "Invalid KMS client: null"); + return std::shared_ptr( + new StandardEncryptionManager(std::move(options))); +} + +StandardEncryptionManager::StandardEncryptionManager( + EncryptionManagerRegistry::Options options) + : table_key_id_(std::move(options.table_key_id)), + data_key_length_(options.data_key_length), + kms_(std::move(options.kms)) { + for (auto& key : options.encryption_keys) { + AddKey(std::move(key)); + } +} + +void StandardEncryptionManager::AddKey(EncryptedKey key) { + auto key_id = key.key_id; + if (keys_.insert_or_assign(key_id, std::move(key)).second) { + key_order_.push_back(std::move(key_id)); + } +} + +void StandardEncryptionManager::SetTestTimeShift(std::chrono::milliseconds shift) { + std::lock_guard lock(mutex_); + time_shift_ = shift; +} + +int64_t StandardEncryptionManager::NowMs() const { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch() + time_shift_) + .count(); +} + +Result StandardEncryptionManager::NewKeyMetadata() { + StandardKeyMetadata metadata; + metadata.encryption_key.resize(data_key_length_); + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(metadata.encryption_key)); + metadata.aad_prefix.emplace(kAadPrefixLength); + ICEBERG_RETURN_UNEXPECTED(SecureRandomBytes(*metadata.aad_prefix)); + return metadata; +} + +Result> StandardEncryptionManager::NewDecryptingInputFile( + std::unique_ptr encrypted, std::span key_metadata) { + ICEBERG_PRECHECK(encrypted != nullptr, "Encrypted input file cannot be null"); + ICEBERG_ASSIGN_OR_RAISE(auto metadata, StandardKeyMetadata::Parse(key_metadata)); + if (!metadata.file_length.has_value()) { + // The length must come from trusted key metadata, not from the file system, so that + // truncation is detected (format/gcm-stream-spec.md, "File length"). + return Invalid("Cannot read AES GCM stream {}: key metadata has no file length", + encrypted->location()); + } + return std::make_unique( + std::move(encrypted), std::move(metadata.encryption_key), + metadata.aad_prefix.value_or(std::vector{}), *metadata.file_length); +} + +Result> StandardEncryptionManager::NewEncryptingOutputFile( + std::unique_ptr plain, const StandardKeyMetadata& key_metadata) { + ICEBERG_PRECHECK(plain != nullptr, "Output file cannot be null"); + return std::make_unique( + std::move(plain), key_metadata.encryption_key, + key_metadata.aad_prefix.value_or(std::vector{})); +} + +Result> StandardEncryptionManager::UnwrapKek( + const std::string& kek_id) { + int64_t now = NowMs(); + if (auto it = unwrapped_keks_.find(kek_id); it != unwrapped_keks_.end()) { + if (now - it->second.unwrapped_at_ms < kUnwrappedKekCacheExpiry.count()) { + return it->second.key; + } + unwrapped_keks_.erase(it); + } + auto it = keys_.find(kek_id); + if (it == keys_.end()) { + return Invalid("Cannot find key encryption key with id {}", kek_id); + } + ICEBERG_ASSIGN_OR_RAISE( + auto kek, + kms_->UnwrapKey(AsBytes(it->second.encrypted_key_metadata), table_key_id_)); + unwrapped_keks_.insert_or_assign(kek_id, CachedKek{.key = kek, .unwrapped_at_ms = now}); + return kek; +} + +Result> StandardEncryptionManager::DecryptManifestListKeyMetadata( + std::string_view manifest_list_key_id) { + std::lock_guard lock(mutex_); + auto it = keys_.find(std::string(manifest_list_key_id)); + if (it == 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 = keys_.at(kek_id).properties.find(std::string(kKeyTimestamp)); + if (timestamp == 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::CurrentKekId() { + int64_t now = NowMs(); + for (const auto& key_id : key_order_) { + const EncryptedKey& key = keys_.at(key_id); + if (key.encrypted_by_id != table_key_id_) { + continue; + } + auto timestamp = ParseTimestamp(key); + if (timestamp.has_value() && 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_->WrapKey(kek, table_key_id_)); + 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(now)}}}); + unwrapped_keks_.insert_or_assign( + kek_id, CachedKek{.key = std::move(kek), .unwrapped_at_ms = now}); + return kek_id; +} + +Result StandardEncryptionManager::RegisterManifestListKeyMetadata( + const StandardKeyMetadata& key_metadata) { + ICEBERG_PRECHECK(key_metadata.file_length.has_value(), + "Manifest list key metadata must include the file length"); + std::lock_guard lock(mutex_); + ICEBERG_ASSIGN_OR_RAISE(auto kek_id, CurrentKekId()); + ICEBERG_ASSIGN_OR_RAISE(auto kek, UnwrapKek(kek_id)); + const EncryptedKey& kek_entry = 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(key_metadata.Serialize(), 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 = 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"); + // A native wrapper already carries both the native and the stream path. + if (auto* native = dynamic_cast(encrypted.get())) { + encrypted.release(); + return std::unique_ptr(native); + } + ICEBERG_ASSIGN_OR_RAISE(auto metadata, CastOrParse(encrypted->key_metadata())); + std::shared_ptr raw = encrypted->ReleaseInputFile(); + 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()); + return std::make_unique(std::move(plain), + std::move(key_metadata)); +} + +std::vector StandardEncryptionManager::encryption_keys() const { + std::lock_guard lock(mutex_); + std::vector result; + result.reserve(key_order_.size()); + for (const auto& key_id : key_order_) { + result.push_back(keys_.at(key_id)); + } + return result; +} + +namespace encryption { + +void RegisterStandardEncryptionManager() { + EncryptionManagerRegistry::Register([](EncryptionManagerRegistry::Options options) + -> Result> { + ICEBERG_ASSIGN_OR_RAISE(auto manager, + StandardEncryptionManager::Make(std::move(options))); + return manager; + }); +} + +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..18bd5f7861 --- /dev/null +++ b/src/iceberg/encryption/standard_encryption_manager.h @@ -0,0 +1,144 @@ +/* + * 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/encryption_manager.h" +#include "iceberg/encryption/standard_key_metadata.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. +/// +/// Unwrapped KEKs are cached for one hour. Thread-safe. +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( + EncryptionManagerRegistry::Options options); + + // EncryptionManager. The batch overloads are re-exposed because overriding the + // single-file ones would otherwise hide them from callers of the concrete type. + using EncryptionManager::Decrypt; + using EncryptionManager::Encrypt; + + /// \brief Decrypt a file. + /// + /// If the argument is already a NativeEncryptionInputFile it is returned unchanged. + /// Otherwise the result is a NativeEncryptionInputFile (callers can dynamic_cast to it + /// to reach the native path) whose key metadata is parsed here but whose AGS1 stream + /// reader is only built when the file is opened or sized; only that stream path needs + /// the key metadata to carry the encrypted file length. + Result> Decrypt( + std::unique_ptr encrypted) override; + + /// \brief Wrap a plain output file for encryption. + /// + /// The result is a NativeEncryptionOutputFile (callers can dynamic_cast to it to reach + /// the native path): plain_output_file() is the plain file for native writers, and + /// encrypting_output_file() writes an AGS1 stream with the same key and AAD prefix. + /// Neither is thread-safe. + Result> Encrypt( + std::unique_ptr plain) override; + + Result NewKeyMetadata(); + Result> NewDecryptingInputFile( + std::unique_ptr encrypted, std::span key_metadata); + Result> NewEncryptingOutputFile( + std::unique_ptr plain, const StandardKeyMetadata& key_metadata); + Result> DecryptManifestListKeyMetadata( + std::string_view manifest_list_key_id); + Result RegisterManifestListKeyMetadata( + const StandardKeyMetadata& key_metadata); + + /// \brief All keys: those from table metadata and those created by this manager. + std::vector encryption_keys() const; + + const std::string& table_key_id() const { return table_key_id_; } + + /// \brief Shift the clock, for tests of KEK rotation and cache expiry. + void SetTestTimeShift(std::chrono::milliseconds shift); + + private: + struct CachedKek { + std::vector key; + int64_t unwrapped_at_ms; + }; + + explicit StandardEncryptionManager(EncryptionManagerRegistry::Options options); + + // The following require mutex_ to be held. + Result> UnwrapKek(const std::string& kek_id); + Result CurrentKekId(); + void AddKey(EncryptedKey key); + + int64_t NowMs() const; + + const std::string table_key_id_; + const int32_t data_key_length_; + const std::shared_ptr kms_; + + mutable std::mutex mutex_; + std::chrono::milliseconds time_shift_{0}; + std::vector key_order_; + std::unordered_map keys_; + std::unordered_map unwrapped_keks_; +}; + +namespace encryption { + +/// \brief Register StandardEncryptionManager in EncryptionManagerRegistry. +ICEBERG_BUNDLE_EXPORT void RegisterStandardEncryptionManager(); + +} // namespace encryption + +} // namespace iceberg diff --git a/src/iceberg/encryption/standard_key_metadata.h b/src/iceberg/encryption/standard_key_metadata.h index 7e788eae56..f304ee1d68 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,7 +48,7 @@ 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 { +struct ICEBERG_EXPORT StandardKeyMetadata : public NativeEncryptionKeyMetadata { static constexpr uint8_t kV1 = 1; /// \brief The data encryption key (16, 24 or 32 bytes). @@ -56,6 +58,16 @@ struct ICEBERG_EXPORT StandardKeyMetadata { /// \brief The encrypted (stored) file length, required to read AES GCM streams. std::optional file_length; + StandardKeyMetadata() = default; + + explicit StandardKeyMetadata( + std::vector encryption_key, + std::optional> aad_prefix = std::nullopt, + std::optional file_length = std::nullopt) + : encryption_key(std::move(encryption_key)), + aad_prefix(std::move(aad_prefix)), + file_length(file_length) {} + /// \brief Parse serialized key metadata. static Result Parse(std::span buffer); @@ -65,8 +77,24 @@ struct ICEBERG_EXPORT StandardKeyMetadata { /// \brief Return a copy with the given encrypted file length. StandardKeyMetadata 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); + } + const std::vector& EncryptionKey() const override { return encryption_key; } + const std::optional>& AadPrefix() const override { + return aad_prefix; + } + Result> FileLength() const override { return file_length; } + Result> CopyWithLength( + int64_t length) const override { + return std::make_shared(WithFileLength(length)); + } + + 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; + } }; } // namespace iceberg diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 1874fc25e8..bf91103af1 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -244,7 +244,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/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..db01f3ddd2 --- /dev/null +++ b/src/iceberg/test/standard_encryption_manager_test.cc @@ -0,0 +1,519 @@ +/* + * 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 "iceberg/arrow/arrow_io_util.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/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 { + +/// \brief Deterministic test bytes: byte i is (i * 31 + seed). +std::vector VectorBytes(size_t length, int seed) { + std::vector bytes(length); + for (size_t i = 0; i < length; ++i) { + bytes[i] = static_cast(static_cast(i) * 31 + seed); + } + return bytes; +} + +// 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 InMemoryKms { + public: + using InMemoryKms::InMemoryKms; + Result> WrapKey(std::span key, + std::string_view id) override { + ++wraps; + return InMemoryKms::WrapKey(key, id); + } + Result> UnwrapKey(std::span wrapped, + std::string_view id) override { + ++unwraps; + return InMemoryKms::UnwrapKey(wrapped, id); + } + int wraps = 0; + int unwraps = 0; +}; + +std::shared_ptr MakeKms() { + return std::make_shared( + std::unordered_map>{{"keyA", kMasterKeyA}}); +} + +} // 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); + + // Through the registry, as catalogs do + encryption::RegisterAll(); + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, EncryptionManagerRegistry::Make( + {.table_key_id = "keyA", + .encryption_keys = metadata->encryption_keys, + .kms = kms})); + + for (const auto& snapshot : metadata->snapshots) { + 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); + EXPECT_EQ(key_metadata.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(); + EXPECT_EQ( + key_metadata.file_length, + std::filesystem::file_size(GetResourcePath("encryption/table/metadata/" + name))); + } + // One key encryption key for all snapshots, unwrapped once + EXPECT_EQ(kms->unwraps, 1); +} + +TEST(StandardEncryptionManagerTest, RegisterAndDecryptManifestListKeyMetadata) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, StandardEncryptionManager::Make( + {.table_key_id = "keyA", .kms = kms})); + + ICEBERG_UNWRAP_OR_FAIL(auto key_metadata, manager->NewKeyMetadata()); + EXPECT_EQ(key_metadata.encryption_key.size(), 16); + EXPECT_EQ(key_metadata.aad_prefix->size(), 16); + EXPECT_FALSE(key_metadata.file_length.has_value()); + // The manifest list length is required + EXPECT_THAT(manager->RegisterManifestListKeyMetadata(key_metadata), + IsError(ErrorKind::kInvalidArgument)); + key_metadata.file_length = 999; + + ICEBERG_UNWRAP_OR_FAIL(auto keys, + manager->RegisterManifestListKeyMetadata(key_metadata)); + 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(), 2); + + // A reader that only has the committed keys and the KMS can decrypt it + ICEBERG_UNWRAP_OR_FAIL(auto reader, + StandardEncryptionManager::Make( + {.table_key_id = "keyA", + .encryption_keys = {keys.key_encryption_key, keys.file_key}, + .kms = kms})); + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, + reader->DecryptManifestListKeyMetadata(keys.file_key.key_id)); + EXPECT_EQ(decrypted, key_metadata.Serialize()); + + // Key encryption keys and unknown IDs are rejected + EXPECT_THAT(reader->DecryptManifestListKeyMetadata(keys.key_encryption_key.key_id), + IsError(ErrorKind::kInvalid)); + EXPECT_THAT(reader->DecryptManifestListKeyMetadata("missing"), + IsError(ErrorKind::kInvalid)); +} + +TEST(StandardEncryptionManagerTest, RotatesKeyEncryptionKeys) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, StandardEncryptionManager::Make( + {.table_key_id = "keyA", .kms = kms})); + StandardKeyMetadata key_metadata(VectorBytes(16, 1), VectorBytes(16, 2), 100); + + ICEBERG_UNWRAP_OR_FAIL(auto first, + manager->RegisterManifestListKeyMetadata(key_metadata)); + ICEBERG_UNWRAP_OR_FAIL(auto second, + manager->RegisterManifestListKeyMetadata(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); + + manager->SetTestTimeShift(StandardEncryptionManager::kKekLifespan); + ICEBERG_UNWRAP_OR_FAIL(auto third, + manager->RegisterManifestListKeyMetadata(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, IgnoresOutOfRangeKeyTimestamp) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, StandardEncryptionManager::Make( + {.table_key_id = "keyA", .kms = kms})); + StandardKeyMetadata key_metadata(VectorBytes(16, 1), VectorBytes(16, 2), 100); + ICEBERG_UNWRAP_OR_FAIL(auto first, + manager->RegisterManifestListKeyMetadata(key_metadata)); + EXPECT_EQ(kms->wraps, 1); + + // A KEK whose KEY_TIMESTAMP is corrupted to INT64_MIN must never reach the + // "now - timestamp" subtraction, which would overflow. It should instead be + // treated as unparseable, forcing a fresh key encryption key to be created. + std::vector keys = manager->encryption_keys(); + for (auto& key : keys) { + if (key.encrypted_by_id == "keyA") { + key.properties[std::string(StandardEncryptionManager::kKeyTimestamp)] = + "-9223372036854775808"; + } + } + ICEBERG_UNWRAP_OR_FAIL( + auto reader, StandardEncryptionManager::Make( + {.table_key_id = "keyA", .encryption_keys = keys, .kms = kms})); + ICEBERG_UNWRAP_OR_FAIL(auto second, + reader->RegisterManifestListKeyMetadata(key_metadata)); + EXPECT_NE(second.key_encryption_key.key_id, first.key_encryption_key.key_id); + EXPECT_EQ(kms->wraps, 2); +} + +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( + {.table_key_id = "keyA", + .encryption_keys = metadata->encryption_keys, + .kms = kms})); + const auto& key_id = *metadata->snapshots.front()->key_id; + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + EXPECT_EQ(kms->unwraps, 1); + + manager->SetTestTimeShift(StandardEncryptionManager::kUnwrappedKekCacheExpiry); + ASSERT_THAT(manager->DecryptManifestListKeyMetadata(key_id), IsOk()); + EXPECT_EQ(kms->unwraps, 2); +} + +TEST(StandardEncryptionManagerTest, DecryptingFileRequiresLength) { + auto kms = MakeKms(); + ICEBERG_UNWRAP_OR_FAIL(auto manager, StandardEncryptionManager::Make( + {.table_key_id = "keyA", .kms = kms})); + StandardKeyMetadata no_length(VectorBytes(16, 1)); + + class NullInputFile : public InputFile { + public: + std::string_view location() const override { return "file"; } + Result Size() const override { return 0; } + Result> Open() override { + return NotImplemented(""); + } + }; + EXPECT_THAT(manager->NewDecryptingInputFile(std::make_unique(), + no_length.Serialize()), + IsError(ErrorKind::kInvalid)); +} + +namespace { + +Result> ReadAll(InputFile& file) { + ICEBERG_ASSIGN_OR_RAISE(auto size, file.Size()); + ICEBERG_ASSIGN_OR_RAISE(auto stream, file.Open()); + std::vector out(size); + if (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 key_; } + std::shared_ptr Copy() const override { + return std::make_shared(*this); + } + const std::vector& EncryptionKey() const override { return key_; } + const std::optional>& AadPrefix() const override { return aad_; } + + private: + std::vector key_ = VectorBytes(16, 1); + std::optional> aad_; +}; + +class StandardEncryptionManagerFileTest : public TempFileTestBase { + protected: + void SetUp() override { + TempFileTestBase::SetUp(); + io_ = std::shared_ptr(arrow::MakeLocalFileIO()); + } + + std::shared_ptr NewManager() { + auto manager = + StandardEncryptionManager::Make({.table_key_id = "keyA", .kms = MakeKms()}); + EXPECT_THAT(manager, IsOk()); + return manager.value(); + } + + std::unique_ptr NewOut(const std::string& path) { + auto out = io_->NewOutputFile(path); + EXPECT_THAT(out, IsOk()); + return std::move(out.value()); + } + + std::unique_ptr NewIn(const std::string& path) { + auto in = io_->NewInputFile(path); + EXPECT_THAT(in, IsOk()); + return std::move(in.value()); + } + + std::string WriteRaw(const std::vector& bytes) { + auto path = CreateNewTempFilePath(); + std::ofstream out(path, std::ios::binary); + out.write(reinterpret_cast(bytes.data()), + static_cast(bytes.size())); + return path; + } + + /// Encrypt and decrypt two files through the batch overloads of `manager`. + template + void RoundTripBatch(Manager& manager) { + const std::vector> plains = {VectorBytes(100, 1), + VectorBytes(3000, 2)}; + std::vector paths = {CreateNewTempFilePath(), CreateNewTempFilePath()}; + std::vector> outs; + for (const auto& path : paths) { + outs.push_back(NewOut(path)); + } + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager.Encrypt(std::move(outs))); + ASSERT_EQ(encrypted.size(), 2u); + + std::vector> ins; + for (size_t i = 0; i < encrypted.size(); ++i) { + ICEBERG_UNWRAP_OR_FAIL(auto stream, + encrypted[i]->encrypting_output_file().CreateOrOverwrite()); + ASSERT_THAT(stream->Write(std::as_bytes(std::span(plains[i]))), IsOk()); + ASSERT_THAT(stream->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto stored, stream->StoredLength()); + + std::shared_ptr key_metadata; + if (const auto* native = dynamic_cast( + &encrypted[i]->key_metadata())) { + ICEBERG_UNWRAP_OR_FAIL(auto with_length, native->CopyWithLength(stored)); + key_metadata = with_length; + } else { + key_metadata = encrypted[i]->key_metadata().Copy(); + } + ins.push_back(EncryptedFiles::Encrypted(NewIn(paths[i]), key_metadata)); + } + + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, manager.Decrypt(std::move(ins))); + ASSERT_EQ(decrypted.size(), 2u); + for (size_t i = 0; i < decrypted.size(); ++i) { + ICEBERG_UNWRAP_OR_FAIL(auto bytes, ReadAll(*decrypted[i])); + EXPECT_EQ(bytes, plains[i]); + } + } + + std::shared_ptr io_; +}; + +} // namespace + +TEST_F(StandardEncryptionManagerFileTest, BatchOverloadsReachableFromConcreteAndBase) { + auto standard = NewManager(); + std::shared_ptr standard_as_base = standard; + auto plaintext = std::make_shared(); + std::shared_ptr plaintext_as_base = plaintext; + + // Calls through the concrete types only compile if the batch overloads are not hidden. + RoundTripBatch(*standard); + RoundTripBatch(*standard_as_base); + RoundTripBatch(*plaintext); + RoundTripBatch(*plaintext_as_base); +} + +TEST_F(StandardEncryptionManagerFileTest, EncryptExposesNativeAndStreamPaths) { + auto manager = NewManager(); + auto path = CreateNewTempFilePath(); + const auto plain = VectorBytes(5000, 7); + + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, manager->Encrypt(NewOut(path))); + auto* native = dynamic_cast(encrypted.get()); + ASSERT_NE(native, nullptr); + + // Native path: the plain file, and the key parameters. + EXPECT_EQ(native->plain_output_file().location(), path); + EXPECT_NE(&native->encrypting_output_file(), &native->plain_output_file()); + const auto& key_metadata = native->key_metadata(); + EXPECT_EQ(key_metadata.EncryptionKey().size(), 16u); + ASSERT_TRUE(key_metadata.AadPrefix().has_value()); + EXPECT_EQ(key_metadata.AadPrefix()->size(), + static_cast(StandardEncryptionManager::kAadPrefixLength)); + ICEBERG_UNWRAP_OR_FAIL(auto initial_length, key_metadata.FileLength()); + EXPECT_FALSE(initial_length.has_value()); + + // Stream path: the OutputFile methods write an AGS1 stream. + 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))); + + // The writer records the stored length on a copy that keeps the same key and AAD. + ICEBERG_UNWRAP_OR_FAIL(auto with_length, key_metadata.CopyWithLength(stored)); + EXPECT_EQ(with_length->EncryptionKey(), key_metadata.EncryptionKey()); + EXPECT_EQ(with_length->AadPrefix(), key_metadata.AadPrefix()); + ICEBERG_UNWRAP_OR_FAIL(auto copied_length, with_length->FileLength()); + EXPECT_EQ(copied_length, stored); + ICEBERG_UNWRAP_OR_FAIL(auto original_length, key_metadata.FileLength()); + EXPECT_FALSE(original_length.has_value()); + + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, manager->Decrypt(EncryptedFiles::Encrypted( + NewIn(path), with_length))); + EXPECT_NE(dynamic_cast(decrypted.get()), nullptr); + ICEBERG_UNWRAP_OR_FAIL(auto bytes, ReadAll(*decrypted)); + EXPECT_EQ(bytes, plain); +} + +TEST_F(StandardEncryptionManagerFileTest, NativeReadDoesNotRequireFileLength) { + auto manager = NewManager(); + const auto raw = VectorBytes(64, 3); + auto path = WriteRaw(raw); + auto no_length = + std::make_shared(VectorBytes(16, 1), VectorBytes(16, 2)); + + // Both an in-memory StandardKeyMetadata and its serialized form are accepted. + std::vector> variants = { + no_length, std::make_shared(no_length->Serialize())}; + for (const auto& key_metadata : variants) { + ICEBERG_UNWRAP_OR_FAIL(auto decrypted, manager->Decrypt(EncryptedFiles::Encrypted( + NewIn(path), key_metadata))); + auto* native = dynamic_cast(decrypted.get()); + ASSERT_NE(native, nullptr); + EXPECT_EQ(native->key_metadata().EncryptionKey(), no_length->encryption_key); + EXPECT_EQ(native->key_metadata().AadPrefix(), no_length->aad_prefix); + + // Native path: the still-encrypted raw bytes. + auto released = native->ReleaseInputFile(); + ASSERT_NE(released, nullptr); + ICEBERG_UNWRAP_OR_FAIL(auto bytes, ReadAll(*released)); + EXPECT_EQ(bytes, raw); + + // Stream path: needs the file length. + EXPECT_THAT(native->Size(), IsError(ErrorKind::kInvalid)); + EXPECT_THAT(native->Open(), IsError(ErrorKind::kInvalid)); + } +} + +TEST_F(StandardEncryptionManagerFileTest, DecryptReturnsNativeInputUnchanged) { + auto manager = NewManager(); + auto path = WriteRaw(VectorBytes(64, 3)); + auto key_metadata = + std::make_shared(VectorBytes(16, 1), VectorBytes(16, 2)); + + ICEBERG_UNWRAP_OR_FAIL( + auto first, manager->Decrypt(EncryptedFiles::Encrypted(NewIn(path), key_metadata))); + auto* native = dynamic_cast(first.release()); + ASSERT_NE(native, nullptr); + + ICEBERG_UNWRAP_OR_FAIL(auto second, + manager->Decrypt(std::unique_ptr(native))); + EXPECT_EQ(dynamic_cast(second.get()), native); +} + +TEST(NativeEncryptionKeyMetadataTest, StandardKeyMetadataCopiesWithLength) { + StandardKeyMetadata metadata(VectorBytes(16, 1), VectorBytes(16, 2)); + ICEBERG_UNWRAP_OR_FAIL(auto no_length, metadata.FileLength()); + EXPECT_FALSE(no_length.has_value()); + + ICEBERG_UNWRAP_OR_FAIL(auto copy, metadata.CopyWithLength(4242)); + EXPECT_EQ(copy->EncryptionKey(), metadata.encryption_key); + EXPECT_EQ(copy->AadPrefix(), metadata.aad_prefix); + ICEBERG_UNWRAP_OR_FAIL(auto length, copy->FileLength()); + EXPECT_EQ(length, 4242); + EXPECT_FALSE(metadata.file_length.has_value()); +} + +TEST(NativeEncryptionKeyMetadataTest, FileLengthIsNotSupportedByDefault) { + MinimalNativeKeyMetadata metadata; + EXPECT_THAT(metadata.FileLength(), IsError(ErrorKind::kNotSupported)); + EXPECT_THAT(metadata.CopyWithLength(1), IsError(ErrorKind::kNotSupported)); +} + +TEST(BaseEncryptionKeyMetadataTest, DistinguishesAbsentFromEmpty) { + auto absent = BaseEncryptionKeyMetadata::Empty(); + BaseEncryptionKeyMetadata empty_bytes(std::vector{}); + BaseEncryptionKeyMetadata some_bytes(VectorBytes(4, 1)); + + // Through the base interface, as generic code would see it. + const EncryptionKeyMetadata& absent_base = *absent; + const EncryptionKeyMetadata& empty_base = empty_bytes; + EXPECT_FALSE(absent_base.has_value()); + EXPECT_TRUE(empty_base.has_value()); + EXPECT_TRUE(some_bytes.has_value()); + EXPECT_TRUE(StandardKeyMetadata(VectorBytes(16, 1)).has_value()); + EXPECT_TRUE(absent->buffer().empty()); + EXPECT_TRUE(empty_bytes.buffer().empty()); + + // Copies preserve presence. + auto absent_copy = std::dynamic_pointer_cast(absent->Copy()); + auto empty_copy = + std::dynamic_pointer_cast(empty_bytes.Copy()); + ASSERT_NE(absent_copy, nullptr); + ASSERT_NE(empty_copy, nullptr); + EXPECT_FALSE(absent_copy->has_value()); + EXPECT_TRUE(empty_copy->has_value()); + EXPECT_EQ(some_bytes.Copy()->buffer(), some_bytes.buffer()); +} + +TEST_F(StandardEncryptionManagerFileTest, PlaintextManagerReportsAbsentKeyMetadata) { + PlaintextEncryptionManager manager; + ICEBERG_UNWRAP_OR_FAIL(auto encrypted, + manager.Encrypt(NewOut(CreateNewTempFilePath()))); + EXPECT_FALSE(encrypted->key_metadata().has_value()); +} + +TEST(EncryptionManagerRegistryTest, ValidatesOptions) { + encryption::RegisterAll(); + EXPECT_TRUE(encryption::IsEncryptionAvailable()); + EXPECT_THAT(EncryptionManagerRegistry::Make({.table_key_id = "keyA"}), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(EncryptionManagerRegistry::Make({.table_key_id = "", .kms = MakeKms()}), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(EncryptionManagerRegistry::Make( + {.table_key_id = "keyA", .data_key_length = 20, .kms = 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..695b94dab8 100644 --- a/src/iceberg/test/standard_key_metadata_test.cc +++ b/src/iceberg/test/standard_key_metadata_test.cc @@ -75,7 +75,7 @@ TEST(StandardKeyMetadataTest, ParseJavaVectors) { } TEST(StandardKeyMetadataTest, RoundTrip) { - StandardKeyMetadata metadata{.encryption_key = TestBytes(32, 7)}; + StandardKeyMetadata metadata(TestBytes(32, 7)); ICEBERG_UNWRAP_OR_FAIL(auto parsed, StandardKeyMetadata::Parse(metadata.Serialize())); EXPECT_EQ(parsed, metadata); @@ -90,8 +90,7 @@ TEST(StandardKeyMetadataTest, RoundTrip) { } // A present but empty AAD prefix is distinct from an absent one - StandardKeyMetadata empty_aad{.encryption_key = TestBytes(16, 7), - .aad_prefix = std::vector{}}; + StandardKeyMetadata empty_aad(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());