Repository navigation
feat(encryption): add EncryptionManager with plaintext and standard implementations - #1071
Conversation
| deletes/position_delete_index.cc | ||
| deletes/position_delete_range_consumer.cc | ||
| deletes/roaring_position_bitmap.cc | ||
| encryption/encryption_manager.cc |
There was a problem hiding this comment.
The new public headers are missing from the explicit install lists: encryption_manager.h, encryption_register.h and standard_encryption_manager.h. Please add them to the core, bundle and encryption groups respectively and regenerate the public-header coverage. Installed consumers currently cannot include these APIs; the registration header should remain available when the bundle is built with encryption disabled.
There was a problem hiding this comment.
Added the three missing headers to the install lists — encryption_manager.h as core, encryption_register.h tagged ICEBERG_PUBLIC_HEADERS_BUNDLE so it stays available with encryption disabled, and standard_encryption_manager.h in the existing encryption group — and regenerated cpp20_compatibility_internal.h.
| continue; | ||
| } | ||
| auto timestamp = ParseTimestamp(key); | ||
| if (timestamp.has_value() && now - *timestamp < kKekLifespan.count()) { |
There was a problem hiding this comment.
ParseTimestamp accepts INT64_MIN, so KEY_TIMESTAMP=-9223372036854775808 causes signed overflow in now - *timestamp. Please validate the range or use an overflow-safe comparison, and add a boundary test.
There was a problem hiding this comment.
Good catch — ParseTimestamp now rejects negative values so a corrupted INT64_MIN timestamp can't reach the now - timestamp subtraction, and added a boundary test covering it.
| @@ -0,0 +1 @@ | |||
| {"format-version":3,"table-uuid":"2091a278-2727-4bc0-8427-ffb04a2b7e6d","location":"/tmp/iceberg-cpp-encryption-fixture/encrypted_table","last-sequence-number":0,"last-updated-ms":1791460592557,"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":null,"next-row-id":0,"refs":{},"snapshots":[],"statistics":[],"partition-statistics":[],"snapshot-log":[],"metadata-log":[]} | |||
There was a problem hiding this comment.
Is it possible to remove some unused files here? Will they be used in the future? I think eventually these files should be generated on-demand like what the Java implementation does.
BTW, we need to add them to dev/release/rat_exclude_files.txt to not fail the future release.
There was a problem hiding this comment.
removed the unused v1-v4 metadata, version-hint.text, the per-snapshot m0.avro manifests, and the sample data files, keeping only v5.metadata.json and the manifest-list avros it actually reads in the test. test/resources/** and *.json are already in rat_exclude_files.txt so no change needed there.
|
@wgtmac addressed both rounds of feedback above, PTAL when you get a chance. |
wgtmac
left a comment
There was a problem hiding this comment.
I would prefer to align the public class design with Java. The current EncryptionManager exposes StandardKeyMetadata, AGS1 wrappers, and manifest-list key management. This makes standard-scheme details part of the contract for every implementation.
EncryptionManager
├── PlaintextEncryptionManager
└── StandardEncryptionManager
EncryptionKeyMetadata // opaque serialized metadata
├── BaseEncryptionKeyMetadata
└── NativeEncryptionKeyMetadata // key, AAD, optional file length
└── StandardKeyMetadata
EncryptedInputFile // raw input + metadata
├── BaseEncryptedInputFile
└── NativeEncryptionInputFile // also implements InputFile
EncryptedOutputFile // encrypting output + metadata
├── BaseEncryptedOutputFile
└── NativeEncryptionOutputFile // also implements OutputFile
The main responsibilities would match Java:
EncryptionManagerexposesencryptanddecrypt, including their batch variants. It does not require a particular metadata encoding or encryption algorithm.EncryptedInputFile/EncryptedOutputFilekeep the file and its metadata together. Callers should not need to generate a key separately and manually pair it with an output file.- Native interfaces expose the raw file and key parameters for format-native encryption, such as Parquet. They keep that path separate from AGS1 stream encryption.
StandardEncryptionManagerowns standard-specific key generation, KEK rotation, caching, andregisterKeyMetadata. Its result should use Java’s name,FileEncryptionKeys.EncryptedFilesprovides the wrapper factories.EncryptionUtilprovides manager construction and standard-specific helpers, includingdecryptManifestListKeyMetadata. These helpers should not become mandatory methods on the general manager.
A registry is fine for the C++ core/bundle dependency boundary, but it should not force all managers to accept standard-specific options.
This should let us reuse most of the current crypto implementation while preserving Java’s extension points.
1fb4842 to
1f5785f
Compare
| std::vector<uint8_t> key_metadata = encrypted->key_metadata().buffer(); | ||
| return NewDecryptingInputFile(encrypted->ReleaseInputFile(), key_metadata); |
There was a problem hiding this comment.
Please preserve the native-format path instead of always constructing an AGS1 reader. Native Parquet metadata without file_length is rejected here, and adding the length still selects the wrong reader. Java returns Native wrappers with raw-file/key access and a separate AGS1 stream path. Encrypt and the new Native wrappers need the same two-path contract.
There was a problem hiding this comment.
Done in 330e3ca: Encrypt and Decrypt now return Native wrappers with the raw/plain path plus a lazily built AGS1 stream path, so native reads no longer need a file length.
| class ICEBERG_EXPORT NativeEncryptionKeyMetadata : public EncryptionKeyMetadata { | ||
| public: | ||
| /// \brief The data encryption key. | ||
| virtual const std::vector<uint8_t>& EncryptionKey() const = 0; | ||
|
|
||
| /// \brief The AAD prefix (file ID) used to bind ciphertext to this file, if any. | ||
| virtual const std::optional<std::vector<uint8_t>>& AadPrefix() const = 0; |
There was a problem hiding this comment.
The Native metadata contract is still missing FileLength and CopyWithLength. Java writers use CopyWithLength after closing the file, while keeping the same key and AAD. Please support that flow through the interface. The base metadata also needs explicit empty and copy semantics; an empty vector cannot distinguish absent metadata from present empty bytes.
There was a problem hiding this comment.
Done in 330e3ca: added FileLength and CopyWithLength to the native metadata, and absent vs present-but-empty is now explicit through has_value, Empty and Copy.
| Result<std::unique_ptr<InputFile>> Decrypt( | ||
| std::unique_ptr<EncryptedInputFile> encrypted) override; | ||
| Result<std::unique_ptr<EncryptedOutputFile>> Encrypt( | ||
| std::unique_ptr<OutputFile> plain) override; |
There was a problem hiding this comment.
These single-file overrides hide the batch overloads from EncryptionManager. A caller using the concrete pointer returned by Make cannot call Encrypt or Decrypt with a vector. Please expose the base overloads in both StandardEncryptionManager and PlaintextEncryptionManager, and cover calls through concrete and base pointers.
There was a problem hiding this comment.
Done in 330e3ca: both managers now expose the batch overloads, with tests through concrete and base pointers.
- EncryptionManager (core): per-table interface to generate key metadata, open AES GCM Stream files for reading and writing, and encrypt and decrypt manifest list key metadata. - EncryptionManagerRegistry (core): creates the manager of an encrypted table from the trusted table key ID, the table's encryption-keys and the catalog's KMS client. The bundle registers the implementation, so the core library has no crypto dependency. - StandardEncryptionManager (bundle): Java's envelope encryption. Key encryption keys are wrapped by the table master key in the KMS, timestamped, used for 730 days and then rotated; manifest list key metadata is encrypted by a KEK with the KEK timestamp as AAD. Unwrapped KEKs are cached for one hour. Thread-safe. - encryption::RegisterAll() / IsEncryptionAvailable() in the bundle; a no-op when built with ICEBERG_ENCRYPTION=OFF. Adds the Java-written encrypted table fixture under test/resources/encryption/table. Tests decrypt the manifest list key metadata of every Java snapshot and check that its file length is the stored size of the manifest list.
Resolves modernize-use-designated-initializers clang-tidy warnings.
…verflow Register encryption_manager.h, encryption_register.h, and standard_encryption_manager.h in the public header install lists so installed consumers can include the new encryption APIs. encryption_register.h is grouped as a bundle header (not encryption-only) so it stays available when the bundle is built with encryption disabled. Also reject negative KEY_TIMESTAMP values in ParseTimestamp to avoid signed overflow in CurrentKekId's now - timestamp comparison when the stored timestamp is corrupted to INT64_MIN.
Keep only v5.metadata.json and the 4 manifest-list avro files its snapshots reference at runtime; v1-v4.metadata.json, version-hint.text, the per-snapshot m0.avro manifest files, and the sample data files under data/ are not read by any test.
…er design Slim EncryptionManager to Encrypt/Decrypt over EncryptedInputFile and EncryptedOutputFile, with sequential batch defaults, so the base interface no longer leaks standard-encryption-specific types. StandardEncryptionManager keeps its envelope-encryption-specific methods as additional public methods. Add PlaintextEncryptionManager for unencrypted tables, EncryptedFiles as a core factory for wrapping plain files without native (modular) encryption support, and EncryptionUtil as a bundle-only helper that reaches StandardEncryptionManager-specific operations through a generic EncryptionManager pointer via dynamic_cast.
…a and files - Native wrappers are now abstract: the raw/plain file plus key metadata is the native path, the InputFile/OutputFile methods are the AGS1 stream path. - StandardEncryptionManager::Encrypt/Decrypt return such wrappers; the AGS1 reader is built lazily, so native reads no longer require a file length, and a NativeEncryptionInputFile passed to Decrypt is returned unchanged. - Add FileLength/CopyWithLength to NativeEncryptionKeyMetadata and implement them in StandardKeyMetadata. - Distinguish absent from present-but-empty key metadata (has_value, Empty, Copy). - Expose the batch Encrypt/Decrypt overloads in both managers.
- Rebased the branch on main. - Added EncryptionUtil::MakeEncryptionManager. It checks the KMS client first, picks plaintext when the table has no key ID, and rejects an explicitly empty ID. - Removed the registry Options struct. Factories now get the keys, table properties, and KMS client directly. Custom factories can use a null KMS; RegisterAll() preserves them, and Make() rejects a null result. - Moved DEK length parsing into the standard factory and reused the AES key-length check. Plaintext reads now warn if key metadata is present. - Renamed the wrapper factories to EncryptedInput and EncryptedOutput, moved the Base wrappers into the .cc file, and added null checks. - Replaced ReleaseInputFile() with DetachInputFile() && and added AsNative() for native input passthrough. AGS1 now opens directly from InputFile&, so the extra shared-file wrapper is gone. Output access stays borrowed. - Made StandardKeyMetadata fields private. The snake_case key and AAD getters return borrowed spans; buffer() still returns owned bytes. Added validated Make factories for metadata, AES-GCM files, and InMemoryKms. - Changed RegisterKeyMetadata to accept NativeEncryptionKeyMetadata. Writers can pass CopyWithLength() directly. Registration also works without a file length; AGS1 reads still require a trusted length. - Kept Encrypt/Decrypt as the file entry points and removed the duplicate AGS1 helpers. Made key generation and test clock controls private. Batch calls still use vectors, with a TODO for lazy streams. - Reject invalid KEK timestamps, timestamp new KEKs after KMS wrapping, and use a monotonic clock for cache expiry. Standard writes require a 16-byte AAD prefix; reads still support files without one. - Added encryption/type_fwd.h, updated header installation and C++20 coverage, and fixed the release RAT exclusion for the encryption fixtures. - Consolidated overlapping tests and moved core-only cases out of the crypto suite. Added coverage for factory selection, KEK rotation and expiry, native/AGS1 ownership, and the manifest-list write/read round trip. The interop test now opens all four Java manifest lists.
Exercise missing metadata length on a valid AGS1 file and isolate the block-count limit. Verify that cache hits do not extend the KEK lifetime, and propagate setup failures in the stream test helpers.
330e3ca to
01169a2
Compare
wgtmac
left a comment
There was a problem hiding this comment.
Thanks for the work on this! I rebased the branch and pushed a few follow-up changes to bring the encryption APIs closer to Java and follow the C++ conventions we use in this repo.
MakeEncryptionManagernow handles plaintext selection, and the standard factory leaves room for custom managers.RegisterKeyMetadatanow accepts the result ofCopyWithLength()directly, matching the Java writer flow.- I made input file ownership explicit with
DetachInputFile(), usedMakefactories for validation, and switched the key and AAD getters tostd::span.
Part of the envelope encryption stack for #988.
Adds
EncryptionManager/EncryptionManagerRegistry(the pluggable manager interfaceand factory) and
StandardEncryptionManager, the envelope encryption manager compatiblewith Java's
StandardEncryptionManager:on demand after 730 days (NIST SP 800-57), manifest-list key metadata AES-GCM encrypted
by a KEK with the KEK timestamp as AAD.
provide an AGS1 stream path. AGS1 reads use the encrypted length from key metadata.
The manager interface, registry, and plaintext implementation live in core. The standard
implementation is gated behind
ICEBERG_ENCRYPTIONin the bundle.EncryptionUtil::MakeEncryptionManagerselects plaintext for tables without a key ID and uses the registered factory for encrypted tables.
Extends
encryption_testandcrypto_testto cover manager selection, manifest-listdecryption against a Java-produced fixture, key registration/decryption round trips,
KEK rotation, and unwrapped-key cache expiry.