From c2742c5ad2075eac4309989b6e7e0b2f6eb64345 Mon Sep 17 00:00:00 2001 From: alice-shang Date: Fri, 9 Oct 2026 06:45:40 +0900 Subject: [PATCH 1/3] feat(kms): add AWS, GCP and Azure KMS clients Add the optional iceberg_kms library (CMake option ICEBERG_BUILD_KMS) with key management clients for AWS KMS, Google Cloud KMS and Azure Key Vault, registered in KmsRegistry as the `aws`, `gcp` and `azure` KMS types. The clients call the services' REST APIs through an injectable HTTP client (cpr by default, with redirects disabled so key material is never replayed to another host) instead of the cloud SDKs, and read the same catalog properties as Java where Java defines them. AWS requests are signed with SigV4 (OpenSSL HMAC-SHA256), tested against the AWS SigV4 test suite. Credentials come from properties or the standard AWS environment variables; GCP and Azure take an access token. CI builds the clients in the Ubuntu Debug job. --- .github/workflows/test.yml | 2 +- CMakeLists.txt | 3 + .../IcebergThirdpartyToolchain.cmake | 7 +- src/iceberg/CMakeLists.txt | 4 + src/iceberg/cpp20_compatibility_internal.h | 3 + .../encryption/key_management_client.cc | 5 +- src/iceberg/kms/CMakeLists.txt | 58 ++++ src/iceberg/kms/aws_sigv4.cc | 169 +++++++++ src/iceberg/kms/aws_sigv4_internal.h | 53 +++ src/iceberg/kms/iceberg_kms_export.h | 37 ++ src/iceberg/kms/kms_clients.cc | 328 ++++++++++++++++++ src/iceberg/kms/kms_clients.h | 151 ++++++++ src/iceberg/kms/kms_http_client.cc | 54 +++ src/iceberg/kms/kms_http_client.h | 57 +++ src/iceberg/test/CMakeLists.txt | 7 + src/iceberg/test/kms_clients_test.cc | 256 ++++++++++++++ 16 files changed, 1190 insertions(+), 4 deletions(-) create mode 100644 src/iceberg/kms/CMakeLists.txt create mode 100644 src/iceberg/kms/aws_sigv4.cc create mode 100644 src/iceberg/kms/aws_sigv4_internal.h create mode 100644 src/iceberg/kms/iceberg_kms_export.h create mode 100644 src/iceberg/kms/kms_clients.cc create mode 100644 src/iceberg/kms/kms_clients.h create mode 100644 src/iceberg/kms/kms_http_client.cc create mode 100644 src/iceberg/kms/kms_http_client.h create mode 100644 src/iceberg/test/kms_clients_test.cc diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2ccc699344..6700051171 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -58,7 +58,7 @@ jobs: matrix: include: - cmake_build_type: Debug - extra_cmake_args: "-DICEBERG_CXX20_COMPAT=ON -DICEBERG_ENCRYPTION=ON" + extra_cmake_args: "-DICEBERG_CXX20_COMPAT=ON -DICEBERG_ENCRYPTION=ON -DICEBERG_BUILD_KMS=ON" api_mode: C++20 Compat - cmake_build_type: RelWithDebInfo extra_cmake_args: "-DICEBERG_ENCRYPTION=ON" diff --git a/CMakeLists.txt b/CMakeLists.txt index d724585e71..f0adfa9e88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,6 +54,9 @@ option(ICEBERG_BUILD_BUNDLE "Build the battery included library" ON) option(ICEBERG_ENCRYPTION "Build table encryption support (Parquet modular encryption, AES GCM streams)" OFF) option(ICEBERG_BUILD_REST "Build rest catalog client" ON) +option(ICEBERG_BUILD_KMS + "Build the AWS KMS, Google Cloud KMS and Azure Key Vault clients (iceberg_kms)" + OFF) option(ICEBERG_BUILD_REST_INTEGRATION_TESTS "Build rest catalog integration tests" OFF) option(ICEBERG_BUILD_VERIFICATION_TESTS "Build conformance tests over the apache/iceberg-verification fixtures" OFF) diff --git a/cmake_modules/IcebergThirdpartyToolchain.cmake b/cmake_modules/IcebergThirdpartyToolchain.cmake index 1578c59a18..4dc317afc3 100644 --- a/cmake_modules/IcebergThirdpartyToolchain.cmake +++ b/cmake_modules/IcebergThirdpartyToolchain.cmake @@ -996,7 +996,12 @@ if(ICEBERG_BUILD_BUNDLE) resolve_zstd_dependency() endif() -if(ICEBERG_BUILD_REST) +# The KMS clients sign AWS requests with OpenSSL. +if(ICEBERG_BUILD_KMS AND NOT TARGET OpenSSL::Crypto) + resolve_openssl_for_encryption() +endif() + +if(ICEBERG_BUILD_REST OR ICEBERG_BUILD_KMS) resolve_cpr_dependency() endif() diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f9604e2575..54e01df4fa 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -454,6 +454,10 @@ if(ICEBERG_BUILD_BUNDLE) add_subdirectory(parquet) endif() +if(ICEBERG_BUILD_KMS) + add_subdirectory(kms) +endif() + iceberg_install_cmake_package(iceberg iceberg_targets) # When linking a system Thrift, downstream find_package(Iceberg) calls diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 93d716e950..6b96eb9034 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -94,6 +94,9 @@ #include "iceberg/inspect/metadata_table.h" #include "iceberg/inspect/refs_table.h" #include "iceberg/inspect/snapshots_table.h" +#include "iceberg/kms/iceberg_kms_export.h" +#include "iceberg/kms/kms_clients.h" +#include "iceberg/kms/kms_http_client.h" #include "iceberg/labels.h" #include "iceberg/location_provider.h" #include "iceberg/logging/cerr_logger.h" diff --git a/src/iceberg/encryption/key_management_client.cc b/src/iceberg/encryption/key_management_client.cc index 85f681f441..52edbdc1c8 100644 --- a/src/iceberg/encryption/key_management_client.cc +++ b/src/iceberg/encryption/key_management_client.cc @@ -55,8 +55,9 @@ Result> KmsRegistry::Load( auto it = state.factories.find(std::string(name)); if (it == state.factories.end()) { return NotFound( - "KMS client not found: {}. No built-in clients ship yet; register one with " - "KmsRegistry::Register and select it with encryption.kms-impl", + "KMS client not found: {}. Built-in clients must be enabled at build time " + "(ICEBERG_BUILD_KMS, library iceberg_kms); custom clients must be registered " + "with KmsRegistry::Register", name); } factory = it->second; diff --git a/src/iceberg/kms/CMakeLists.txt b/src/iceberg/kms/CMakeLists.txt new file mode 100644 index 0000000000..1d775f0f98 --- /dev/null +++ b/src/iceberg/kms/CMakeLists.txt @@ -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. + +set(ICEBERG_KMS_SOURCES aws_sigv4.cc kms_clients.cc kms_http_client.cc) + +set(ICEBERG_KMS_STATIC_BUILD_INTERFACE_LIBS) +set(ICEBERG_KMS_SHARED_BUILD_INTERFACE_LIBS) +set(ICEBERG_KMS_STATIC_INSTALL_INTERFACE_LIBS) +set(ICEBERG_KMS_SHARED_INSTALL_INTERFACE_LIBS) + +list(APPEND + ICEBERG_KMS_STATIC_BUILD_INTERFACE_LIBS + "$,iceberg_static,iceberg_shared>" + cpr::cpr + OpenSSL::Crypto) +list(APPEND + ICEBERG_KMS_SHARED_BUILD_INTERFACE_LIBS + "$,iceberg_shared,iceberg_static>" + cpr::cpr + OpenSSL::Crypto) +list(APPEND + ICEBERG_KMS_STATIC_INSTALL_INTERFACE_LIBS + "$,iceberg::iceberg_static,iceberg::iceberg_shared>" + "$,iceberg::cpr,cpr::cpr>" + OpenSSL::Crypto) +list(APPEND + ICEBERG_KMS_SHARED_INSTALL_INTERFACE_LIBS + "$,iceberg::iceberg_shared,iceberg::iceberg_static>" + "$,iceberg::cpr,cpr::cpr>" + OpenSSL::Crypto) + +add_iceberg_lib(iceberg_kms + SOURCES + ${ICEBERG_KMS_SOURCES} + SHARED_LINK_LIBS + ${ICEBERG_KMS_SHARED_BUILD_INTERFACE_LIBS} + STATIC_LINK_LIBS + ${ICEBERG_KMS_STATIC_BUILD_INTERFACE_LIBS} + STATIC_INSTALL_INTERFACE_LIBS + ${ICEBERG_KMS_STATIC_INSTALL_INTERFACE_LIBS} + SHARED_INSTALL_INTERFACE_LIBS + ${ICEBERG_KMS_SHARED_INSTALL_INTERFACE_LIBS}) + +iceberg_install_all_headers(iceberg/kms) diff --git a/src/iceberg/kms/aws_sigv4.cc b/src/iceberg/kms/aws_sigv4.cc new file mode 100644 index 0000000000..3855f772de --- /dev/null +++ b/src/iceberg/kms/aws_sigv4.cc @@ -0,0 +1,169 @@ +/* + * 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 +#include +#include +#include +#include + +#include +#include + +#include "iceberg/kms/aws_sigv4_internal.h" +#include "iceberg/util/macros.h" + +namespace iceberg::kms { + +namespace { + +std::string ToHex(const unsigned char* data, size_t length) { + static constexpr char kDigits[] = "0123456789abcdef"; + std::string out; + out.reserve(length * 2); + for (size_t i = 0; i < length; ++i) { + out.push_back(kDigits[data[i] >> 4]); + out.push_back(kDigits[data[i] & 0xF]); + } + return out; +} + +Result HmacSha256(std::string_view key, std::string_view data) { + std::array out{}; + unsigned int length = 0; + if (HMAC(EVP_sha256(), key.data(), static_cast(key.size()), + reinterpret_cast(data.data()), data.size(), out.data(), + &length) == nullptr) { + return IOError("HMAC-SHA256 failed"); + } + return std::string(reinterpret_cast(out.data()), length); +} + +std::string ToLower(std::string_view s) { + std::string out(s); + std::ranges::transform(out, out.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return out; +} + +std::string Trim(std::string_view s) { + auto begin = s.find_first_not_of(" \t"); + if (begin == std::string_view::npos) { + return ""; + } + auto end = s.find_last_not_of(" \t"); + return std::string(s.substr(begin, end - begin + 1)); +} + +struct UrlParts { + std::string host; + std::string path; + std::string query; +}; + +Result ParseUrl(std::string_view url) { + auto scheme_end = url.find("://"); + if (scheme_end == std::string_view::npos) { + return InvalidArgument("Invalid URL: {}", url); + } + auto rest = url.substr(scheme_end + 3); + auto path_start = rest.find('/'); + UrlParts parts; + parts.host = std::string(rest.substr(0, path_start)); + auto path_and_query = path_start == std::string_view::npos ? std::string_view("/") + : rest.substr(path_start); + auto query_start = path_and_query.find('?'); + parts.path = std::string(path_and_query.substr(0, query_start)); + if (query_start != std::string_view::npos) { + parts.query = std::string(path_and_query.substr(query_start + 1)); + } + return parts; +} + +} // namespace + +Result Sha256Hex(std::string_view data) { + std::array digest{}; + unsigned int length = 0; + if (EVP_Digest(data.data(), data.size(), digest.data(), &length, EVP_sha256(), + nullptr) != 1) { + return IOError("SHA-256 failed"); + } + return ToHex(digest.data(), length); +} + +Status SignAwsRequest(HttpRequest& request, std::string_view method, + std::string_view region, std::string_view service, + const AwsCredentials& credentials, std::string_view amz_date) { + ICEBERG_PRECHECK(amz_date.size() == 16, "Invalid AWS date: {}", amz_date); + ICEBERG_PRECHECK( + !credentials.access_key_id.empty() && !credentials.secret_access_key.empty(), + "AWS credentials are required to sign KMS requests"); + ICEBERG_ASSIGN_OR_RAISE(auto url, ParseUrl(request.url)); + + request.headers["X-Amz-Date"] = std::string(amz_date); + if (!credentials.session_token.empty()) { + request.headers["X-Amz-Security-Token"] = credentials.session_token; + } + + // Canonical headers: lower-case names, sorted, with Host + std::map canonical; + canonical["host"] = url.host; + for (const auto& [name, value] : request.headers) { + canonical[ToLower(name)] = Trim(value); + } + std::string canonical_headers; + std::string signed_headers; + for (const auto& [name, value] : canonical) { + canonical_headers += name + ":" + value + "\n"; + if (!signed_headers.empty()) { + signed_headers += ";"; + } + signed_headers += name; + } + + ICEBERG_ASSIGN_OR_RAISE(auto payload_hash, Sha256Hex(request.body)); + // The KMS JSON API uses no query parameters; a query, if any, must already be in + // canonical (sorted, encoded) form. + std::string canonical_request = + std::format("{}\n{}\n{}\n{}\n{}\n{}", method, url.path, url.query, + canonical_headers, signed_headers, payload_hash); + + std::string date(amz_date.substr(0, 8)); + std::string scope = std::format("{}/{}/{}/aws4_request", date, region, service); + ICEBERG_ASSIGN_OR_RAISE(auto canonical_hash, Sha256Hex(canonical_request)); + std::string string_to_sign = + std::format("AWS4-HMAC-SHA256\n{}\n{}\n{}", amz_date, scope, canonical_hash); + + ICEBERG_ASSIGN_OR_RAISE(auto k_date, + HmacSha256("AWS4" + credentials.secret_access_key, date)); + ICEBERG_ASSIGN_OR_RAISE(auto k_region, HmacSha256(k_date, region)); + ICEBERG_ASSIGN_OR_RAISE(auto k_service, HmacSha256(k_region, service)); + ICEBERG_ASSIGN_OR_RAISE(auto k_signing, HmacSha256(k_service, "aws4_request")); + ICEBERG_ASSIGN_OR_RAISE(auto signature, HmacSha256(k_signing, string_to_sign)); + + request.headers["Authorization"] = std::format( + "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}", + credentials.access_key_id, scope, signed_headers, + ToHex(reinterpret_cast(signature.data()), signature.size())); + return {}; +} + +} // namespace iceberg::kms diff --git a/src/iceberg/kms/aws_sigv4_internal.h b/src/iceberg/kms/aws_sigv4_internal.h new file mode 100644 index 0000000000..3049977007 --- /dev/null +++ b/src/iceberg/kms/aws_sigv4_internal.h @@ -0,0 +1,53 @@ +/* + * 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/kms/aws_sigv4_internal.h +/// AWS Signature Version 4 signing of HTTP requests. + +#include +#include +#include + +#include "iceberg/kms/kms_http_client.h" +#include "iceberg/result.h" + +namespace iceberg::kms { + +struct AwsCredentials { + std::string access_key_id; + std::string secret_access_key; + std::string session_token; +}; + +/// \brief Lower-case hex SHA-256 of `data`. +Result Sha256Hex(std::string_view data); + +/// \brief Sign `request` (method `method`) for AWS SigV4. +/// +/// Adds the X-Amz-Date, X-Amz-Security-Token (if any) and Authorization headers. All +/// headers of the request, and Host (from the URL), are signed. +/// +/// \param amz_date the request time, as yyyyMMdd'T'HHmmss'Z' +Status SignAwsRequest(HttpRequest& request, std::string_view method, + std::string_view region, std::string_view service, + const AwsCredentials& credentials, std::string_view amz_date); + +} // namespace iceberg::kms diff --git a/src/iceberg/kms/iceberg_kms_export.h b/src/iceberg/kms/iceberg_kms_export.h new file mode 100644 index 0000000000..62543981cd --- /dev/null +++ b/src/iceberg/kms/iceberg_kms_export.h @@ -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. + */ + +#pragma once + +/// \file iceberg/kms/iceberg_kms_export.h +/// \brief Define symbol visibility macros for the cloud KMS client library. + +#if defined(_WIN32) || defined(__CYGWIN__) +# ifdef ICEBERG_KMS_STATIC +# define ICEBERG_KMS_EXPORT +# elif defined(ICEBERG_KMS_EXPORTING) +# define ICEBERG_KMS_EXPORT __declspec(dllexport) +# else +# define ICEBERG_KMS_EXPORT __declspec(dllimport) +# endif +#else // Not Windows +# ifndef ICEBERG_KMS_EXPORT +# define ICEBERG_KMS_EXPORT __attribute__((visibility("default"))) +# endif +#endif diff --git a/src/iceberg/kms/kms_clients.cc b/src/iceberg/kms/kms_clients.cc new file mode 100644 index 0000000000..73c5730448 --- /dev/null +++ b/src/iceberg/kms/kms_clients.cc @@ -0,0 +1,328 @@ +/* + * 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/kms/kms_clients.h" + +#include +#include +#include + +#include + +#include "iceberg/kms/aws_sigv4_internal.h" +#include "iceberg/util/base64.h" +#include "iceberg/util/macros.h" + +namespace iceberg::kms { + +namespace { + +std::string ToString(std::span bytes) { + return {reinterpret_cast(bytes.data()), bytes.size()}; +} + +std::vector ToBytes(std::string_view s) { return {s.begin(), s.end()}; } + +std::string PropertyOr(const Properties& properties, std::string_view name, + std::string_view default_value) { + auto it = properties.find(std::string(name)); + return it != properties.end() && !it->second.empty() ? it->second + : std::string(default_value); +} + +std::string PropertyOrEnv(const Properties& properties, std::string_view name, + const char* env) { + const char* value = std::getenv(env); + return PropertyOr(properties, name, value != nullptr ? value : ""); +} + +/// POST a JSON request and parse the JSON response; non-2xx responses are errors. +Result PostJson(HttpClient& http, HttpRequest request, + std::string_view service) { + ICEBERG_ASSIGN_OR_RAISE(auto response, http.Post(request)); + if (response.status_code < 200 || response.status_code >= 300) { + return IOError("{} request failed with HTTP {}: {}", service, response.status_code, + response.body); + } + auto json = nlohmann::json::parse(response.body, nullptr, /*allow_exceptions=*/false); + if (json.is_discarded() || !json.is_object()) { + return IOError("Invalid {} response: {}", service, response.body); + } + return json; +} + +Result GetString(const nlohmann::json& json, std::string_view field, + std::string_view service) { + auto it = json.find(field); + if (it == json.end() || !it->is_string()) { + return IOError("Invalid {} response: missing string field {}", service, field); + } + return it->get(); +} + +std::string AwsNow() { + return std::format("{:%Y%m%dT%H%M%SZ}", std::chrono::floor( + std::chrono::system_clock::now())); +} + +} // namespace + +// --------------------------------------------------------------------------- +// AWS KMS + +struct AwsKmsClient::Impl { + std::shared_ptr http; + Clock clock; + std::string region; + std::string endpoint; + std::string encryption_algorithm; + std::string data_key_spec; + AwsCredentials credentials; + + Result Call(std::string_view action, const nlohmann::json& body) { + ICEBERG_PRECHECK(!endpoint.empty(), "AWS KMS client is not initialized"); + HttpRequest request{ + .url = endpoint, + .headers = {{"Content-Type", "application/x-amz-json-1.1"}, + {"X-Amz-Target", std::format("TrentService.{}", action)}}, + .body = body.dump()}; + ICEBERG_RETURN_UNEXPECTED( + SignAwsRequest(request, "POST", region, "kms", credentials, clock())); + return PostJson(*http, std::move(request), "AWS KMS"); + } +}; + +AwsKmsClient::AwsKmsClient(std::shared_ptr http, Clock clock) + : impl_(std::make_unique()) { + impl_->http = http != nullptr ? std::move(http) : HttpClient::MakeDefault(); + impl_->clock = clock ? std::move(clock) : Clock(AwsNow); +} + +AwsKmsClient::~AwsKmsClient() = default; + +Status AwsKmsClient::Initialize(const Properties& properties) { + impl_->region = PropertyOrEnv(properties, kRegion, "AWS_REGION"); + ICEBERG_PRECHECK(!impl_->region.empty(), "AWS KMS client requires {} or AWS_REGION", + kRegion); + impl_->endpoint = PropertyOr( + properties, kEndpoint, std::format("https://kms.{}.amazonaws.com/", impl_->region)); + if (!impl_->endpoint.ends_with('/')) { + impl_->endpoint += '/'; + } + impl_->encryption_algorithm = + PropertyOr(properties, kEncryptionAlgorithmSpec, "SYMMETRIC_DEFAULT"); + impl_->data_key_spec = PropertyOr(properties, kDataKeySpec, "AES_256"); + impl_->credentials = AwsCredentials{ + .access_key_id = PropertyOrEnv(properties, kAccessKeyId, "AWS_ACCESS_KEY_ID"), + .secret_access_key = + PropertyOrEnv(properties, kSecretAccessKey, "AWS_SECRET_ACCESS_KEY"), + .session_token = PropertyOrEnv(properties, kSessionToken, "AWS_SESSION_TOKEN")}; + ICEBERG_PRECHECK(!impl_->credentials.access_key_id.empty() && + !impl_->credentials.secret_access_key.empty(), + "AWS KMS client requires credentials ({}, {} or AWS_ACCESS_KEY_ID, " + "AWS_SECRET_ACCESS_KEY)", + kAccessKeyId, kSecretAccessKey); + return {}; +} + +Result> AwsKmsClient::WrapKey(std::span key, + std::string_view wrapping_key_id) { + ICEBERG_ASSIGN_OR_RAISE( + auto response, + impl_->Call("Encrypt", {{"KeyId", wrapping_key_id}, + {"Plaintext", Base64::Encode(ToString(key))}, + {"EncryptionAlgorithm", impl_->encryption_algorithm}})); + ICEBERG_ASSIGN_OR_RAISE(auto blob, GetString(response, "CiphertextBlob", "AWS KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto wrapped, Base64::Decode(blob)); + return ToBytes(wrapped); +} + +Result> AwsKmsClient::UnwrapKey(std::span wrapped_key, + std::string_view wrapping_key_id) { + ICEBERG_ASSIGN_OR_RAISE( + auto response, + impl_->Call("Decrypt", {{"KeyId", wrapping_key_id}, + {"CiphertextBlob", Base64::Encode(ToString(wrapped_key))}, + {"EncryptionAlgorithm", impl_->encryption_algorithm}})); + ICEBERG_ASSIGN_OR_RAISE(auto plaintext, GetString(response, "Plaintext", "AWS KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto key, Base64::Decode(plaintext)); + return ToBytes(key); +} + +Result AwsKmsClient::GenerateKey( + std::string_view wrapping_key_id) { + ICEBERG_ASSIGN_OR_RAISE( + auto response, impl_->Call("GenerateDataKey", {{"KeyId", wrapping_key_id}, + {"KeySpec", impl_->data_key_spec}})); + ICEBERG_ASSIGN_OR_RAISE(auto plaintext, GetString(response, "Plaintext", "AWS KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto blob, GetString(response, "CiphertextBlob", "AWS KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto key, Base64::Decode(plaintext)); + ICEBERG_ASSIGN_OR_RAISE(auto wrapped, Base64::Decode(blob)); + return GeneratedKey{.key = ToBytes(key), .wrapped_key = ToBytes(wrapped)}; +} + +// --------------------------------------------------------------------------- +// Google Cloud KMS + +struct GcpKmsClient::Impl { + std::shared_ptr http; + std::string endpoint; + std::string token; + + Result Call(std::string_view key_name, std::string_view method, + const nlohmann::json& body) { + ICEBERG_PRECHECK(!token.empty(), "GCP KMS client is not initialized"); + HttpRequest request{.url = std::format("{}/v1/{}:{}", endpoint, key_name, method), + .headers = {{"Content-Type", "application/json"}, + {"Authorization", "Bearer " + token}}, + .body = body.dump()}; + return PostJson(*http, std::move(request), "GCP KMS"); + } +}; + +GcpKmsClient::GcpKmsClient(std::shared_ptr http) + : impl_(std::make_unique()) { + impl_->http = http != nullptr ? std::move(http) : HttpClient::MakeDefault(); +} + +GcpKmsClient::~GcpKmsClient() = default; + +Status GcpKmsClient::Initialize(const Properties& properties) { + impl_->endpoint = PropertyOr(properties, kEndpoint, "https://cloudkms.googleapis.com"); + while (impl_->endpoint.ends_with('/')) { + impl_->endpoint.pop_back(); + } + impl_->token = PropertyOr(properties, kOAuth2Token, ""); + if (impl_->token.empty()) { + return NotSupported( + "GCP KMS client requires an OAuth2 token ({}); application default credentials " + "are not supported", + kOAuth2Token); + } + return {}; +} + +Result> GcpKmsClient::WrapKey(std::span key, + std::string_view wrapping_key_id) { + ICEBERG_ASSIGN_OR_RAISE(auto response, + impl_->Call(wrapping_key_id, "encrypt", + {{"plaintext", Base64::Encode(ToString(key))}})); + ICEBERG_ASSIGN_OR_RAISE(auto ciphertext, GetString(response, "ciphertext", "GCP KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto wrapped, Base64::Decode(ciphertext)); + return ToBytes(wrapped); +} + +Result> GcpKmsClient::UnwrapKey(std::span wrapped_key, + std::string_view wrapping_key_id) { + ICEBERG_ASSIGN_OR_RAISE( + auto response, + impl_->Call(wrapping_key_id, "decrypt", + {{"ciphertext", Base64::Encode(ToString(wrapped_key))}})); + ICEBERG_ASSIGN_OR_RAISE(auto plaintext, GetString(response, "plaintext", "GCP KMS")); + ICEBERG_ASSIGN_OR_RAISE(auto key, Base64::Decode(plaintext)); + return ToBytes(key); +} + +// --------------------------------------------------------------------------- +// Azure Key Vault + +struct AzureKmsClient::Impl { + static constexpr std::string_view kApiVersion = "7.4"; + + std::shared_ptr http; + std::string vault_url; + std::string algorithm; + std::string token; + + Result> Call(std::string_view key_name, std::string_view method, + std::span value) { + ICEBERG_PRECHECK(!vault_url.empty(), "Azure KMS client is not initialized"); + nlohmann::json body{{"alg", algorithm}, + {"value", Base64::UrlEncode(ToString(value))}}; + HttpRequest request{.url = std::format("{}/keys/{}/{}?api-version={}", vault_url, + key_name, method, kApiVersion), + .headers = {{"Content-Type", "application/json"}, + {"Authorization", "Bearer " + token}}, + .body = body.dump()}; + ICEBERG_ASSIGN_OR_RAISE(auto response, + PostJson(*http, std::move(request), "Azure Key Vault")); + ICEBERG_ASSIGN_OR_RAISE(auto result, GetString(response, "value", "Azure Key Vault")); + ICEBERG_ASSIGN_OR_RAISE(auto bytes, Base64::UrlDecode(result)); + return ToBytes(bytes); + } +}; + +AzureKmsClient::AzureKmsClient(std::shared_ptr http) + : impl_(std::make_unique()) { + impl_->http = http != nullptr ? std::move(http) : HttpClient::MakeDefault(); +} + +AzureKmsClient::~AzureKmsClient() = default; + +Status AzureKmsClient::Initialize(const Properties& properties) { + impl_->vault_url = PropertyOr(properties, kVaultUrl, ""); + ICEBERG_PRECHECK(!impl_->vault_url.empty(), "Azure KMS client requires {}", kVaultUrl); + while (impl_->vault_url.ends_with('/')) { + impl_->vault_url.pop_back(); + } + impl_->algorithm = PropertyOr(properties, kKeyWrapAlgorithm, "RSA-OAEP-256"); + impl_->token = PropertyOr(properties, kToken, ""); + ICEBERG_PRECHECK(!impl_->token.empty(), + "Azure KMS client requires an access token ({})", kToken); + return {}; +} + +Result> AzureKmsClient::WrapKey(std::span key, + std::string_view wrapping_key_id) { + return impl_->Call(wrapping_key_id, "wrapkey", key); +} + +Result> AzureKmsClient::UnwrapKey( + std::span wrapped_key, std::string_view wrapping_key_id) { + return impl_->Call(wrapping_key_id, "unwrapkey", wrapped_key); +} + +// --------------------------------------------------------------------------- +// Registration + +void RegisterAll() { + KmsRegistry::Register(std::string(KmsRegistry::kKmsTypeAws), + []() -> Result> { + return std::make_unique(); + }); + KmsRegistry::Register(std::string(KmsRegistry::kKmsTypeGcp), + []() -> Result> { + return std::make_unique(); + }); + KmsRegistry::Register(std::string(KmsRegistry::kKmsTypeAzure), + []() -> Result> { + return std::make_unique(); + }); +} + +namespace { + +[[maybe_unused]] const bool kKmsClientsRegistered = []() { + RegisterAll(); + return true; +}(); + +} // namespace + +} // namespace iceberg::kms diff --git a/src/iceberg/kms/kms_clients.h b/src/iceberg/kms/kms_clients.h new file mode 100644 index 0000000000..aa6f07ad2a --- /dev/null +++ b/src/iceberg/kms/kms_clients.h @@ -0,0 +1,151 @@ +/* + * 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/kms/kms_clients.h +/// KMS clients of AWS KMS, Google Cloud KMS and Azure Key Vault. +/// +/// The clients call the services' REST APIs directly (no cloud SDK). They read the +/// same catalog properties as their Java counterparts where Java defines one; +/// properties marked "C++ only" have no Java equivalent, because Java takes them from +/// the cloud SDK's default credential chain. That chain itself (AWS profiles, ECS and EC2 +/// instance roles, web identity; Google application default credentials; Azure managed +/// identities) is not implemented: pass credentials or a token through the properties +/// below, or register a custom client. + +#include +#include +#include +#include + +#include "iceberg/encryption/key_management_client.h" +#include "iceberg/kms/iceberg_kms_export.h" +#include "iceberg/kms/kms_http_client.h" + +namespace iceberg::kms { + +using Properties = std::unordered_map; + +/// \brief AWS KMS client (Java: org.apache.iceberg.aws.AwsKeyManagementClient). +/// +/// The wrapping key ID is a KMS key ID, ARN or alias. Properties: +/// - `client.region`: the AWS region (default: the AWS_REGION environment variable); +/// - `kms.endpoint` (C++ only): endpoint override, e.g. for LocalStack; +/// - `kms.encryption-algorithm-spec`: default SYMMETRIC_DEFAULT; +/// - `kms.data-key-spec`: key spec of GenerateKey, default AES_256; +/// - `kms.access-key-id`, `kms.secret-access-key`, `kms.session-token` (C++ only): +/// credentials; default: the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and +/// AWS_SESSION_TOKEN environment variables. +/// +/// Requests are signed with AWS Signature Version 4. +class ICEBERG_KMS_EXPORT AwsKmsClient : public KeyManagementClient { + public: + static constexpr std::string_view kRegion = "client.region"; + static constexpr std::string_view kEndpoint = "kms.endpoint"; + static constexpr std::string_view kEncryptionAlgorithmSpec = + "kms.encryption-algorithm-spec"; + static constexpr std::string_view kDataKeySpec = "kms.data-key-spec"; + static constexpr std::string_view kAccessKeyId = "kms.access-key-id"; + static constexpr std::string_view kSecretAccessKey = "kms.secret-access-key"; + static constexpr std::string_view kSessionToken = "kms.session-token"; + + /// \brief Returns the current time as yyyyMMdd'T'HHmmss'Z'. + using Clock = std::function; + + explicit AwsKmsClient(std::shared_ptr http = nullptr, Clock clock = {}); + ~AwsKmsClient() override; + + Status Initialize(const Properties& properties) override; + Result> WrapKey(std::span key, + std::string_view wrapping_key_id) override; + Result> UnwrapKey(std::span wrapped_key, + std::string_view wrapping_key_id) override; + bool SupportsKeyGeneration() const override { return true; } + Result GenerateKey(std::string_view wrapping_key_id) override; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +/// \brief Google Cloud KMS client (Java: org.apache.iceberg.gcp.GcpKeyManagementClient). +/// +/// The wrapping key ID is the key resource name, +/// `projects/*/locations/*/keyRings/*/cryptoKeys/*`. Properties: +/// - `gcs.oauth2.token`: OAuth2 access token (required; application default +/// credentials are not supported); +/// - `gcp.kms.endpoint` (C++ only): default https://cloudkms.googleapis.com. +class ICEBERG_KMS_EXPORT GcpKmsClient : public KeyManagementClient { + public: + static constexpr std::string_view kOAuth2Token = "gcs.oauth2.token"; + static constexpr std::string_view kEndpoint = "gcp.kms.endpoint"; + + explicit GcpKmsClient(std::shared_ptr http = nullptr); + ~GcpKmsClient() override; + + Status Initialize(const Properties& properties) override; + Result> WrapKey(std::span key, + std::string_view wrapping_key_id) override; + Result> UnwrapKey(std::span wrapped_key, + std::string_view wrapping_key_id) override; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +/// \brief Azure Key Vault client +/// (Java: org.apache.iceberg.azure.keymanagement.AzureKeyManagementClient). +/// +/// The wrapping key ID is the key name, optionally followed by `/`. +/// Properties: +/// - `azure.keyvault.url`: the vault URL, e.g. https://myvault.vault.azure.net +/// (required); +/// - `azure.keyvault.key-wrap-algorithm`: default RSA-OAEP-256; +/// - `azure.keyvault.token` (C++ only): Microsoft Entra access token (required). +class ICEBERG_KMS_EXPORT AzureKmsClient : public KeyManagementClient { + public: + static constexpr std::string_view kVaultUrl = "azure.keyvault.url"; + static constexpr std::string_view kKeyWrapAlgorithm = + "azure.keyvault.key-wrap-algorithm"; + static constexpr std::string_view kToken = "azure.keyvault.token"; + + explicit AzureKmsClient(std::shared_ptr http = nullptr); + ~AzureKmsClient() override; + + Status Initialize(const Properties& properties) override; + Result> WrapKey(std::span key, + std::string_view wrapping_key_id) override; + Result> UnwrapKey(std::span wrapped_key, + std::string_view wrapping_key_id) override; + + private: + struct Impl; + std::unique_ptr impl_; +}; + +/// \brief Register the clients in KmsRegistry as `aws`, `gcp` and `azure`. +/// +/// Also done at static initialization when this library is linked. A static archive +/// link may drop that initializer when nothing else references this library, so call +/// RegisterAll() explicitly when a built-in type is not found. +ICEBERG_KMS_EXPORT void RegisterAll(); + +} // namespace iceberg::kms diff --git a/src/iceberg/kms/kms_http_client.cc b/src/iceberg/kms/kms_http_client.cc new file mode 100644 index 0000000000..2510b43ee7 --- /dev/null +++ b/src/iceberg/kms/kms_http_client.cc @@ -0,0 +1,54 @@ +/* + * 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/kms/kms_http_client.h" + +#include + +namespace iceberg::kms { + +namespace { + +class CprHttpClient : public HttpClient { + public: + Result Post(const HttpRequest& request) override { + cpr::Header headers; + for (const auto& [name, value] : request.headers) { + headers.emplace(name, value); + } + auto response = cpr::Post(cpr::Url{request.url}, headers, cpr::Body{request.body}, + cpr::Timeout{std::chrono::seconds(30)}, + // Never follow redirects: the body carries plaintext key + // material and the credentials are bound to this host. + cpr::Redirect(false)); + if (response.error) { + return IOError("KMS request to {} failed: {}", request.url, response.error.message); + } + return HttpResponse{.status_code = static_cast(response.status_code), + .body = std::move(response.text)}; + } +}; + +} // namespace + +std::shared_ptr HttpClient::MakeDefault() { + return std::make_shared(); +} + +} // namespace iceberg::kms diff --git a/src/iceberg/kms/kms_http_client.h b/src/iceberg/kms/kms_http_client.h new file mode 100644 index 0000000000..7813ecf935 --- /dev/null +++ b/src/iceberg/kms/kms_http_client.h @@ -0,0 +1,57 @@ +/* + * 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/kms/kms_http_client.h +/// Minimal HTTP transport used by the cloud KMS clients. + +#include +#include +#include + +#include "iceberg/kms/iceberg_kms_export.h" +#include "iceberg/result.h" + +namespace iceberg::kms { + +struct ICEBERG_KMS_EXPORT HttpRequest { + std::string url; + std::map headers; + std::string body; +}; + +struct ICEBERG_KMS_EXPORT HttpResponse { + int32_t status_code = 0; + std::string body; +}; + +/// \brief Sends KMS requests. Replaceable in tests. +class ICEBERG_KMS_EXPORT HttpClient { + public: + virtual ~HttpClient() = default; + + /// \brief POST the request and return the response, whatever its status code. + virtual Result Post(const HttpRequest& request) = 0; + + /// \brief The default client (cpr / libcurl). + static std::shared_ptr MakeDefault(); +}; + +} // namespace iceberg::kms diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 125ba128a3..75e30ce63e 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -365,6 +365,13 @@ if(ICEBERG_BUILD_SQL_CATALOG add_test(NAME sql_catalog_test COMMAND sql_catalog_test) endif() +if(ICEBERG_BUILD_KMS) + add_iceberg_test(kms_clients_test SOURCES kms_clients_test.cc) + target_link_libraries(kms_clients_test + PRIVATE "$,iceberg_kms_static,iceberg_kms_shared>" + ) +endif() + if(ICEBERG_BUILD_REST) function(add_rest_iceberg_test test_name) set(options USE_BUNDLE) diff --git a/src/iceberg/test/kms_clients_test.cc b/src/iceberg/test/kms_clients_test.cc new file mode 100644 index 0000000000..697e144b88 --- /dev/null +++ b/src/iceberg/test/kms_clients_test.cc @@ -0,0 +1,256 @@ +/* + * 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/kms/kms_clients.h" + +#include +#include +#include + +#include "iceberg/kms/aws_sigv4_internal.h" +#include "iceberg/test/matchers.h" +#include "iceberg/util/base64.h" + +namespace iceberg::kms { + +namespace { + +using ::testing::HasSubstr; +using ::testing::StartsWith; + +/// Records requests and answers with a fixed response. +class FakeHttpClient : public HttpClient { + public: + Result Post(const HttpRequest& request) override { + requests.push_back(request); + return response; + } + + nlohmann::json LastBody() const { return nlohmann::json::parse(requests.back().body); } + + HttpResponse response{.status_code = 200, .body = "{}"}; + std::vector requests; +}; + +std::string ToString(const std::vector& bytes) { + return {bytes.begin(), bytes.end()}; +} + +const std::vector kKey{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0xFB}; +const std::vector kWrapped{0xFF, 0xFE, 0x3E, 0x3F, 42}; + +} // namespace + +// AWS Signature Version 4 test suite, get-vanilla and post-vanilla. +TEST(AwsSigV4Test, TestSuiteVectors) { + AwsCredentials credentials{ + .access_key_id = "AKIDEXAMPLE", + .secret_access_key = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"}; + for (const auto& [method, signature] : std::vector>{ + {"GET", "5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31"}, + {"POST", + "5da7c1a2acd57cee7505fc6676e4e544621c30862966e37dddb68e92efbe5d6b"}}) { + HttpRequest request{.url = "https://example.amazonaws.com/"}; + ASSERT_THAT(SignAwsRequest(request, method, "us-east-1", "service", credentials, + "20150830T123600Z"), + IsOk()); + EXPECT_EQ(request.headers.at("Authorization"), + "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/" + "aws4_request, SignedHeaders=host;x-amz-date, Signature=" + + signature) + << method; + } +} + +TEST(AwsSigV4Test, SessionTokenIsSigned) { + AwsCredentials credentials{ + .access_key_id = "AKID", .secret_access_key = "SECRET", .session_token = "TOKEN"}; + HttpRequest request{.url = "https://kms.us-west-2.amazonaws.com/"}; + ASSERT_THAT(SignAwsRequest(request, "POST", "us-west-2", "kms", credentials, + "20240101T000000Z"), + IsOk()); + EXPECT_EQ(request.headers.at("X-Amz-Security-Token"), "TOKEN"); + EXPECT_THAT(request.headers.at("Authorization"), + HasSubstr("SignedHeaders=host;x-amz-date;x-amz-security-token,")); +} + +TEST(AwsKmsClientTest, WrapUnwrapAndGenerate) { + auto http = std::make_shared(); + AwsKmsClient client(http, [] { return std::string("20240102T030405Z"); }); + ASSERT_THAT(client.Initialize({{"client.region", "us-west-2"}, + {"kms.access-key-id", "AKID"}, + {"kms.secret-access-key", "SECRET"}}), + IsOk()); + EXPECT_TRUE(client.SupportsKeyGeneration()); + + http->response.body = + nlohmann::json{{"CiphertextBlob", Base64::Encode(ToString(kWrapped))}}.dump(); + ICEBERG_UNWRAP_OR_FAIL(auto wrapped, client.WrapKey(kKey, "alias/table")); + EXPECT_EQ(wrapped, kWrapped); + const HttpRequest& request = http->requests.back(); + EXPECT_EQ(request.url, "https://kms.us-west-2.amazonaws.com/"); + EXPECT_EQ(request.headers.at("X-Amz-Target"), "TrentService.Encrypt"); + EXPECT_EQ(request.headers.at("Content-Type"), "application/x-amz-json-1.1"); + EXPECT_THAT(request.headers.at("Authorization"), + StartsWith("AWS4-HMAC-SHA256 Credential=AKID/20240102/us-west-2/kms/" + "aws4_request, SignedHeaders=content-type;host;x-amz-date;" + "x-amz-target, Signature=")); + EXPECT_EQ(http->LastBody(), + (nlohmann::json{{"KeyId", "alias/table"}, + {"Plaintext", Base64::Encode(ToString(kKey))}, + {"EncryptionAlgorithm", "SYMMETRIC_DEFAULT"}})); + + http->response.body = + nlohmann::json{{"Plaintext", Base64::Encode(ToString(kKey))}}.dump(); + ICEBERG_UNWRAP_OR_FAIL(auto unwrapped, client.UnwrapKey(kWrapped, "alias/table")); + EXPECT_EQ(unwrapped, kKey); + EXPECT_EQ(http->requests.back().headers.at("X-Amz-Target"), "TrentService.Decrypt"); + EXPECT_EQ(http->LastBody()["CiphertextBlob"], Base64::Encode(ToString(kWrapped))); + + http->response.body = + nlohmann::json{{"Plaintext", Base64::Encode(ToString(kKey))}, + {"CiphertextBlob", Base64::Encode(ToString(kWrapped))}} + .dump(); + ICEBERG_UNWRAP_OR_FAIL(auto generated, client.GenerateKey("alias/table")); + EXPECT_EQ(generated.key, kKey); + EXPECT_EQ(generated.wrapped_key, kWrapped); + EXPECT_EQ(http->requests.back().headers.at("X-Amz-Target"), + "TrentService.GenerateDataKey"); + EXPECT_EQ(http->LastBody(), + (nlohmann::json{{"KeyId", "alias/table"}, {"KeySpec", "AES_256"}})); +} + +TEST(AwsKmsClientTest, EndpointOverrideAndErrors) { + auto http = std::make_shared(); + AwsKmsClient client(http); + ASSERT_THAT(client.Initialize({{"client.region", "us-east-1"}, + {"kms.endpoint", "http://localhost:4566"}, + {"kms.access-key-id", "AKID"}, + {"kms.secret-access-key", "SECRET"}}), + IsOk()); + + http->response = {.status_code = 400, .body = R"({"__type":"NotFoundException"})"}; + auto result = client.WrapKey(kKey, "missing"); + EXPECT_THAT(result, IsError(ErrorKind::kIOError)); + EXPECT_THAT(result, HasErrorMessage("NotFoundException")); + EXPECT_EQ(http->requests.back().url, "http://localhost:4566/"); + + http->response = {.status_code = 200, .body = "{}"}; + EXPECT_THAT(client.UnwrapKey(kWrapped, "key"), HasErrorMessage("Plaintext")); +} + +TEST(AwsKmsClientTest, RequiresRegionAndCredentials) { + AwsKmsClient client(std::make_shared()); + if (std::getenv("AWS_REGION") == nullptr) { + EXPECT_THAT(client.Initialize({}), IsError(ErrorKind::kInvalidArgument)); + } + if (std::getenv("AWS_ACCESS_KEY_ID") == nullptr) { + EXPECT_THAT(client.Initialize({{"client.region", "us-east-1"}}), + IsError(ErrorKind::kInvalidArgument)); + } +} + +TEST(GcpKmsClientTest, WrapAndUnwrap) { + auto http = std::make_shared(); + GcpKmsClient client(http); + ASSERT_THAT(client.Initialize({{"gcs.oauth2.token", "ya29.token"}}), IsOk()); + EXPECT_FALSE(client.SupportsKeyGeneration()); + const std::string key_name = "projects/p/locations/global/keyRings/r/cryptoKeys/k"; + + http->response.body = + nlohmann::json{{"ciphertext", Base64::Encode(ToString(kWrapped))}}.dump(); + ICEBERG_UNWRAP_OR_FAIL(auto wrapped, client.WrapKey(kKey, key_name)); + EXPECT_EQ(wrapped, kWrapped); + EXPECT_EQ(http->requests.back().url, + "https://cloudkms.googleapis.com/v1/" + key_name + ":encrypt"); + EXPECT_EQ(http->requests.back().headers.at("Authorization"), "Bearer ya29.token"); + EXPECT_EQ(http->LastBody(), + (nlohmann::json{{"plaintext", Base64::Encode(ToString(kKey))}})); + + http->response.body = + nlohmann::json{{"plaintext", Base64::Encode(ToString(kKey))}}.dump(); + ICEBERG_UNWRAP_OR_FAIL(auto unwrapped, client.UnwrapKey(kWrapped, key_name)); + EXPECT_EQ(unwrapped, kKey); + EXPECT_EQ(http->requests.back().url, + "https://cloudkms.googleapis.com/v1/" + key_name + ":decrypt"); +} + +TEST(GcpKmsClientTest, RequiresToken) { + GcpKmsClient client(std::make_shared()); + EXPECT_THAT(client.Initialize({}), IsError(ErrorKind::kNotSupported)); +} + +TEST(AzureKmsClientTest, WrapAndUnwrap) { + auto http = std::make_shared(); + AzureKmsClient client(http); + ASSERT_THAT(client.Initialize({{"azure.keyvault.url", "https://vault.vault.azure.net/"}, + {"azure.keyvault.token", "entra-token"}}), + IsOk()); + + http->response.body = nlohmann::json{{"kid", "https://vault.vault.azure.net/keys/k/v1"}, + {"value", Base64::UrlEncode(ToString(kWrapped))}} + .dump(); + ICEBERG_UNWRAP_OR_FAIL(auto wrapped, client.WrapKey(kKey, "k/v1")); + EXPECT_EQ(wrapped, kWrapped); + EXPECT_EQ(http->requests.back().url, + "https://vault.vault.azure.net/keys/k/v1/wrapkey?api-version=7.4"); + EXPECT_EQ(http->requests.back().headers.at("Authorization"), "Bearer entra-token"); + EXPECT_EQ(http->LastBody(), + (nlohmann::json{{"alg", "RSA-OAEP-256"}, + {"value", Base64::UrlEncode(ToString(kKey))}})); + + http->response.body = + nlohmann::json{{"value", Base64::UrlEncode(ToString(kKey))}}.dump(); + ICEBERG_UNWRAP_OR_FAIL(auto unwrapped, client.UnwrapKey(kWrapped, "k/v1")); + EXPECT_EQ(unwrapped, kKey); + EXPECT_EQ(http->requests.back().url, + "https://vault.vault.azure.net/keys/k/v1/unwrapkey?api-version=7.4"); +} + +TEST(AzureKmsClientTest, RequiresVaultUrlAndToken) { + AzureKmsClient client(std::make_shared()); + EXPECT_THAT(client.Initialize({{"azure.keyvault.token", "t"}}), + IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(client.Initialize({{"azure.keyvault.url", "https://v.vault.azure.net"}}), + IsError(ErrorKind::kInvalidArgument)); +} + +TEST(KmsClientsTest, RegisteredByType) { + RegisterAll(); + ICEBERG_UNWRAP_OR_FAIL(auto client, + KmsRegistry::FromCatalogProperties( + {{"encryption.kms-type", "azure"}, + {"azure.keyvault.url", "https://v.vault.azure.net"}, + {"azure.keyvault.token", "t"}})); + EXPECT_NE(dynamic_cast(client.get()), nullptr); + + ICEBERG_UNWRAP_OR_FAIL( + client, KmsRegistry::FromCatalogProperties( + {{"encryption.kms-type", "GCP"}, {"gcs.oauth2.token", "t"}})); + EXPECT_NE(dynamic_cast(client.get()), nullptr); + + ICEBERG_UNWRAP_OR_FAIL( + client, KmsRegistry::FromCatalogProperties({{"encryption.kms-type", "aws"}, + {"client.region", "eu-west-1"}, + {"kms.access-key-id", "AKID"}, + {"kms.secret-access-key", "SECRET"}})); + EXPECT_NE(dynamic_cast(client.get()), nullptr); +} + +} // namespace iceberg::kms From 1c72904c7d6cdc60c0aff2abc0026f0273bf6536 Mon Sep 17 00:00:00 2001 From: shangxinli Date: Thu, 3 Dec 2026 11:42:21 -0800 Subject: [PATCH 2/3] fix(kms): avoid C-style array in aws_sigv4 ToHex --- src/iceberg/kms/aws_sigv4.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/iceberg/kms/aws_sigv4.cc b/src/iceberg/kms/aws_sigv4.cc index 3855f772de..2df4219d15 100644 --- a/src/iceberg/kms/aws_sigv4.cc +++ b/src/iceberg/kms/aws_sigv4.cc @@ -34,7 +34,7 @@ namespace iceberg::kms { namespace { std::string ToHex(const unsigned char* data, size_t length) { - static constexpr char kDigits[] = "0123456789abcdef"; + static constexpr std::string_view kDigits = "0123456789abcdef"; std::string out; out.reserve(length * 2); for (size_t i = 0; i < length; ++i) { From 75b02300596b4149b9eb483c34827bfc1dc50130 Mon Sep 17 00:00:00 2001 From: shangxinli Date: Thu, 3 Dec 2026 13:51:20 -0800 Subject: [PATCH 3/3] ci: build with ICEBERG_ENCRYPTION and ICEBERG_BUILD_KMS in cpp-linter so KMS sources get a compile database --- .github/workflows/cpp-linter.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cpp-linter.yml b/.github/workflows/cpp-linter.yml index 07a33701f9..1bae57c5c5 100644 --- a/.github/workflows/cpp-linter.yml +++ b/.github/workflows/cpp-linter.yml @@ -90,7 +90,9 @@ jobs: -DICEBERG_SQL_SQLITE=ON \ -DICEBERG_SQL_POSTGRESQL=ON \ -DICEBERG_SQL_MYSQL=ON \ - -DICEBERG_BUILD_HIVE=ON + -DICEBERG_BUILD_HIVE=ON \ + -DICEBERG_ENCRYPTION=ON \ + -DICEBERG_BUILD_KMS=ON cmake --build . - name: Save sccache if: always()