encryption

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package encryption defines interfaces and utilities for Iceberg table encryption. It provides:

Index

Constants

View Source
const KMSTypeKey = "kms-type"

KMSTypeKey is the catalog property that selects a KeyManagementClient implementation registered with a KMSRegistry (e.g. "memory"). It is an iceberg-go-specific property and is not portable to other Iceberg implementations.

View Source
const StandardDefaultDataKeyLength = 16

StandardDefaultDataKeyLength is the default length, in bytes, of the per-file data encryption key (DEK). It is 128-bit, matching the default of the encryption.data-key-length table property in the Java and Rust implementations.

Variables

View Source
var (
	// ErrKeyIDNotSupported is returned by [PlaintextEncryptionManager.NewEncryptedOutputFile]
	// when a caller supplies a non-empty keyID. Accepting the keyID but writing
	// plaintext would fail open: the caller believes the file is encrypted, but
	// no encryption is actually performed.
	ErrKeyIDNotSupported = errors.New("encryption: PlaintextEncryptionManager does not support a non-empty keyID; configure a real EncryptionManager")

	// ErrKeyMetadataNotSupported is returned by [PlaintextEncryptionManager.NewDecryptedInputFile]
	// when a caller supplies non-empty key metadata. Ignoring the metadata and
	// returning the raw bytes would fail open: the caller would silently read
	// encrypted bytes as if they were plaintext.
	ErrKeyMetadataNotSupported = errors.New("encryption: PlaintextEncryptionManager does not support non-empty key metadata; configure a real EncryptionManager")
)
View Source
var (
	// ErrUnknownKeyID is returned when a KMS client is asked to wrap or unwrap
	// with a key ID it does not know about.
	ErrUnknownKeyID = errors.New("encryption: unknown key ID")

	// ErrInvalidKeyLength is returned when a key or requested key length is not
	// valid for the underlying cipher (for example, a KEK that is not 16, 24,
	// or 32 bytes for AES, or a DEK request of length <= 0).
	ErrInvalidKeyLength = errors.New("encryption: invalid key length")

	// ErrCiphertextTooShort is returned when a wrapped key or encrypted payload
	// is smaller than the minimum required (e.g. the AES-GCM nonce prefix).
	ErrCiphertextTooShort = errors.New("encryption: ciphertext too short")

	// ErrAuthenticationFailed is returned when an authenticated decryption
	// primitive rejects its input (tampering, wrong key, or corruption).
	ErrAuthenticationFailed = errors.New("encryption: authentication failed")
)

Sentinel errors returned by KeyManagementClient implementations. Callers should test with errors.Is rather than string matching.

View Source
var (
	// ErrKMSTypeNotFound is returned by [KMSRegistry.Load] when the
	// requested KMS has not been registered.
	ErrKMSTypeNotFound = errors.New("encryption: kms type not found")

	// ErrKMSAlreadyRegistered is returned when a factory name is already in use.
	ErrKMSAlreadyRegistered = errors.New("encryption: kms factory already registered")

	// ErrInvalidKMSRegistration is returned for an empty name or nil factory.
	ErrInvalidKMSRegistration = errors.New("encryption: invalid kms registration")
)
View Source
var (
	// ErrKeyIDRequired is returned by
	// [StandardEncryptionManager.NewEncryptedOutputFile] when keyID is empty.
	// StandardEncryptionManager always encrypts, so it requires the table's
	// encryption key ID; use [PlaintextEncryptionManager] for unencrypted
	// tables instead of passing an empty keyID here.
	ErrKeyIDRequired = errors.New("encryption: StandardEncryptionManager requires a non-empty keyID")

	// ErrKeyMetadataRequired is returned by
	// [StandardEncryptionManager.NewDecryptedInputFile] and
	// [StandardEncryptionManager.NewDecryptedInputFileWithLength] when
	// keyMetadata is empty. StandardEncryptionManager always decrypts, so it requires the
	// per-file key metadata produced by
	// [StandardEncryptionManager.NewEncryptedOutputFile].
	ErrKeyMetadataRequired = errors.New("encryption: StandardEncryptionManager requires non-empty key metadata")

	// ErrUnsupportedKeyMetadataVersion is returned when key metadata starts
	// with a version byte other than the one this package understands.
	ErrUnsupportedKeyMetadataVersion = errors.New("encryption: unsupported key metadata version")

	// ErrInvalidStreamHeader is returned when the AES GCM Stream header (the
	// "AGS1" magic and little-endian plain block length at the start of an
	// encrypted file, per the Iceberg AES GCM Stream spec) is missing,
	// truncated, or declares a block length other than the fixed 1 MiB.
	ErrInvalidStreamHeader = errors.New("encryption: invalid AES GCM Stream header")

	// ErrInvalidKeyMetadata is returned by
	// [StandardEncryptionManager.NewDecryptedInputFile] and
	// [StandardEncryptionManager.NewDecryptedInputFileWithLength] when key
	// metadata is not a well-formed StandardKeyMetadata record or fails basic
	// sanity checks (e.g. a truncated record, a missing or wrong-sized AAD
	// prefix, or a missing or impossible encrypted length). Key metadata is
	// untrusted input on a crypto read path, so it is validated rather than
	// trusted blindly.
	ErrInvalidKeyMetadata = errors.New("encryption: invalid key metadata")

	// ErrOutputFileClosed is returned by [standardOutputFile.Write] when
	// called after a successful Close. It wraps [fs.ErrClosed] so callers can
	// test with errors.Is(err, fs.ErrClosed). A Write after a failed flush or
	// a failed Close returns that original error instead.
	ErrOutputFileClosed = fmt.Errorf("encryption: write to closed StandardEncryptionManager output file: %w", fs.ErrClosed)

	// ErrBlockTruncated is returned by [standardInputFile.ReadAt] when the
	// underlying storage returns fewer ciphertext bytes for a block than its
	// recorded length requires, indicating the file was truncated at rest.
	// This is distinct from [ErrCiphertextTooShort], which [KeyManagementClient]
	// implementations use for a too-short wrapped key or KMS-encrypted
	// payload; keeping them separate lets a caller tell a malformed KMS blob
	// apart from a short block read.
	ErrBlockTruncated = errors.New("encryption: block truncated: read fewer ciphertext bytes than expected")
)

Sentinel errors returned by StandardEncryptionManager.

Functions

func GetRegisteredKMSNames

func GetRegisteredKMSNames() []string

GetRegisteredKMSNames returns globally registered factory names, sorted.

func MustRegisterKMS added in v0.8.0

func MustRegisterKMS(name string, factory KMSFactory)

MustRegisterKMS registers a global KMS factory or panics. It is intended for use by KMS providers during package initialization.

func RegisterKMS

func RegisterKMS(name string, factory KMSFactory)

RegisterKMS adds a factory to the process-wide default registry. As in previous releases, invalid or duplicate registrations panic. Use a separate KMSRegistry and its Register method to handle registration errors.

func UnregisterKMS

func UnregisterKMS(name string)

UnregisterKMS removes a factory from the default registry. Existing independent registry snapshots are unaffected.

Types

type EncryptedInputFile

type EncryptedInputFile interface {
	icebergio.File
	// KeyMetadata returns the opaque per-file encryption key metadata.
	KeyMetadata() EncryptionKeyMetadata
}

EncryptedInputFile is a readable file that carries the per-file encryption key metadata required by an EncryptionManager to derive the decryption key.

type EncryptedOutputFile

type EncryptedOutputFile interface {
	icebergio.FileWriter
	// KeyMetadata returns the finalized per-file encryption key metadata.
	// The returned value is only guaranteed to be populated after Close has
	// been called.
	KeyMetadata() EncryptionKeyMetadata
}

EncryptedOutputFile is a writable file whose plaintext content is encrypted by the EncryptionManager. After the file has been closed, [KeyMetadata] returns the finalized per-file key metadata to embed in the corresponding manifest entry.

type EncryptionKeyMetadata

type EncryptionKeyMetadata []byte

EncryptionKeyMetadata is the opaque per-file key metadata blob embedded in manifest entries (DataFile.KeyMetadata, ManifestFile.KeyMetadata) and statistics files (StatisticsFile.KeyMetadata). The encoding is EncryptionManager-defined and typically envelopes the wrapped DEK together with any associated authenticated additional data (AAD).

type EncryptionManager

type EncryptionManager interface {
	// NewEncryptedOutputFile creates a new encrypted output file.
	// keyID is the table property encryption.key-id that identifies the key
	// encryption key (KEK) to use when wrapping the generated DEK.
	NewEncryptedOutputFile(ctx context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error)

	// NewDecryptedInputFile wraps an existing file for transparent decryption.
	// keyMetadata is the per-file opaque blob stored in the manifest entry
	// (DataFile.KeyMetadata or ManifestFile.KeyMetadata).
	NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error)
}

EncryptionManager handles envelope key derivation, file-level encryption, and decryption. It is the central coordination point between the KeyManagementClient (key encryption key operations) and the per-file data encryption keys (DEKs).

A PlaintextEncryptionManager is provided for tables that do not use encryption. Vendors and users can supply custom implementations to integrate with their KMS solutions.

type InMemoryKeyManagementClient

type InMemoryKeyManagementClient struct {
	// contains filtered or unexported fields
}

InMemoryKeyManagementClient is a KeyManagementClient backed by an in-memory map of master (key-encryption) keys. Key wrapping and unwrapping use AES-GCM.

Warning

InMemoryKeyManagementClient is intended for testing only. All keys are held in plaintext in process memory with no persistence, access control, or audit logging. Do not use it in production.

func NewInMemoryKeyManagementClient

func NewInMemoryKeyManagementClient() *InMemoryKeyManagementClient

NewInMemoryKeyManagementClient creates a new InMemoryKeyManagementClient with no pre-loaded keys. Register KEKs with [AddKey] before use.

func (*InMemoryKeyManagementClient) AddKey

func (c *InMemoryKeyManagementClient) AddKey(keyID string, masterKey []byte) error

AddKey registers a master key (KEK) under keyID. masterKey must be 16, 24, or 32 bytes for AES-128, AES-192, or AES-256 respectively. If keyID is already registered, its KEK is silently replaced.

func (*InMemoryKeyManagementClient) GenerateKey

func (c *InMemoryKeyManagementClient) GenerateKey(ctx context.Context, keyID string, length int) (plaintext, wrapped []byte, err error)

GenerateKey generates a cryptographically random DEK of the given byte length, wraps it with the KEK identified by keyID, and returns both the plaintext DEK and the wrapped form.

func (*InMemoryKeyManagementClient) SupportsKeyGeneration

func (c *InMemoryKeyManagementClient) SupportsKeyGeneration() bool

SupportsKeyGeneration returns true; the in-memory client generates DEKs locally using crypto/rand.

func (*InMemoryKeyManagementClient) UnwrapKey

func (c *InMemoryKeyManagementClient) UnwrapKey(_ context.Context, keyID string, wrappedKey []byte) ([]byte, error)

UnwrapKey decrypts wrappedKey using the KEK identified by keyID. The wrappedKey must have been produced by [WrapKey] or [GenerateKey].

func (*InMemoryKeyManagementClient) WrapKey

func (c *InMemoryKeyManagementClient) WrapKey(_ context.Context, keyID string, plaintextKey []byte) ([]byte, error)

WrapKey encrypts plaintextKey with the KEK identified by keyID using AES-GCM. The returned ciphertext layout is:

12-byte random nonce || AES-GCM ciphertext || 16-byte GCM authentication tag

type KMSFactory

type KMSFactory func(ctx context.Context, props map[string]string) (KeyManagementClient, error)

KMSFactory creates a KeyManagementClient from catalog/table properties. Factories receive the caller's context and full property map.

type KMSRegistry added in v0.8.0

type KMSRegistry struct {
	// contains filtered or unexported fields
}

KMSRegistry owns the named factories used to construct KMS clients. A registry is safe for concurrent use and must not be copied after first use. Its zero value is an empty, usable registry. Use NewKMSRegistry to clone the global default, which includes the built-in "memory" factory (for testing).

Separate registries let tests and catalog clients register the same name without modifying each other's factories.

func NewKMSRegistry added in v0.8.0

func NewKMSRegistry() *KMSRegistry

NewKMSRegistry returns an independent snapshot of the default registry. Providers should be imported before calling it. Initializing a package-level variable with NewKMSRegistry can miss registrations made by other packages.

func (*KMSRegistry) Clone added in v0.8.0

func (r *KMSRegistry) Clone() *KMSRegistry

Clone copies the registered factories into a separate registry. Factories themselves are shared, but future registrations and removals are isolated.

func (*KMSRegistry) Load added in v0.8.0

func (r *KMSRegistry) Load(ctx context.Context, props map[string]string) (KeyManagementClient, error)

Load resolves and constructs a KeyManagementClient from props. It looks up the name under KMSTypeKey and returns an error wrapping ErrKMSTypeNotFound when the property is empty or not registered. The factory is invoked outside the lock, so it may update this registry.

func (*KMSRegistry) MustRegister added in v0.8.0

func (r *KMSRegistry) MustRegister(name string, factory KMSFactory)

MustRegister registers a factory or panics. It is intended for init functions in KMS provider packages where registration failure is unrecoverable.

func (*KMSRegistry) Names added in v0.8.0

func (r *KMSRegistry) Names() []string

Names returns the currently registered factory names in sorted order. The returned slice is independent of the registry.

func (*KMSRegistry) Register added in v0.8.0

func (r *KMSRegistry) Register(name string, factory KMSFactory) error

Register adds a named KMS factory. It returns an error for an empty name, nil factory, or duplicate name. The registry is unchanged on error.

func (*KMSRegistry) Unregister added in v0.8.0

func (r *KMSRegistry) Unregister(name string)

Unregister removes a named factory. Removing an unknown name is a no-op.

type KeyManagementClient

type KeyManagementClient interface {
	// WrapKey encrypts (wraps) plaintextKey using the KEK identified by keyID.
	// The returned bytes are an opaque, KMS-specific wrapped key blob.
	WrapKey(ctx context.Context, keyID string, plaintextKey []byte) ([]byte, error)

	// UnwrapKey decrypts (unwraps) wrappedKey using the KEK identified by keyID.
	// It returns the original plaintext DEK.
	UnwrapKey(ctx context.Context, keyID string, wrappedKey []byte) ([]byte, error)

	// SupportsKeyGeneration reports whether this client can generate new DEKs
	// server-side. When false, callers should generate DEKs locally and use
	// [WrapKey] to protect them.
	SupportsKeyGeneration() bool

	// GenerateKey generates a new DEK of the given byte length, returning both
	// the plaintext DEK and its KMS-wrapped form. This is only valid when
	// [SupportsKeyGeneration] returns true.
	GenerateKey(ctx context.Context, keyID string, length int) (plaintext, wrapped []byte, err error)
}

KeyManagementClient is the interface for a Key Management Service (KMS) that wraps and unwraps data encryption keys (DEKs) using key encryption keys (KEKs) managed externally by the KMS.

In the standard envelope-encryption model:

  • A KEK is identified by a key ID (the table property encryption.key-id).
  • A fresh DEK is generated per-file (or per-rotation interval).
  • The DEK is wrapped by the KMS and stored in the file's key_metadata field.
  • On read, the wrapped DEK is unwrapped by the KMS to decrypt the file.

Implementations are responsible for authentication, authorization, and network communication with the KMS backend.

func LoadKeyManagementClient

func LoadKeyManagementClient(ctx context.Context, props map[string]string) (KeyManagementClient, error)

LoadKeyManagementClient constructs a KMS client using the default registry. Its context is forwarded to the selected factory.

type NativeEncryptionInputFile

type NativeEncryptionInputFile interface {
	EncryptedInputFile
	// NativeDecryptionProperties returns format-native decryption properties.
	// The concrete type is format-specific; callers should type-assert as
	// needed (e.g., *parquet.FileDecryptionProperties for Parquet files).
	NativeDecryptionProperties(ctx context.Context) (any, error)
}

NativeEncryptionInputFile extends EncryptedInputFile with access to format-native decryption properties (e.g., Parquet FileDecryptionProperties). An EncryptionManager may return a NativeEncryptionInputFile from EncryptionManager.NewDecryptedInputFile when native-format encryption is in use; callers should type-assert to retrieve the concrete properties.

type NativeEncryptionOutputFile

type NativeEncryptionOutputFile interface {
	EncryptedOutputFile
	// NativeEncryptionProperties returns format-native encryption properties.
	// The concrete type is format-specific; callers should type-assert as
	// needed (e.g., *parquet.FileEncryptionProperties for Parquet files).
	NativeEncryptionProperties(ctx context.Context) (any, error)
}

NativeEncryptionOutputFile extends EncryptedOutputFile with access to format-native encryption properties (e.g., Parquet FileEncryptionProperties). An EncryptionManager may return a NativeEncryptionOutputFile from EncryptionManager.NewEncryptedOutputFile when native-format encryption is in use; callers should type-assert to retrieve the concrete properties.

type PlaintextEncryptionManager

type PlaintextEncryptionManager struct{}

PlaintextEncryptionManager is a no-op EncryptionManager that passes all data through without any encryption or decryption. It is the default manager used when no KMS is configured or when a table carries no encryption-keys metadata. It fails closed: any call that supplies a non-empty keyID or non-empty key metadata returns an error rather than silently reading or writing plaintext, since doing so could mask a misconfigured encryption setup.

func (PlaintextEncryptionManager) NewDecryptedInputFile

NewDecryptedInputFile returns a pass-through EncryptedInputFile that reads data unmodified. It fails closed: non-empty keyMetadata indicates the underlying bytes were encrypted, and returning them unchanged would silently hand ciphertext to the caller as if it were plaintext, so it returns ErrKeyMetadataNotSupported rather than ignoring the metadata.

func (PlaintextEncryptionManager) NewEncryptedOutputFile

func (PlaintextEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error)

NewEncryptedOutputFile returns a pass-through EncryptedOutputFile that writes data unmodified and returns nil EncryptionKeyMetadata. It fails closed: a non-empty keyID indicates the caller expects the file to be encrypted, and returning nil here would silently write plaintext instead, so it returns ErrKeyIDNotSupported rather than ignoring the keyID.

type StandardEncryptionManager added in v0.8.0

type StandardEncryptionManager struct {
	// contains filtered or unexported fields
}

StandardEncryptionManager is a generic, format-agnostic EncryptionManager for arbitrary files (e.g. manifests, manifest lists, Puffin statistics). It reads and writes the same bytes as Java's StandardEncryptionManager, iceberg-rust and pyiceberg: an Iceberg AES GCM Stream ("AGS1") with fixed 1 MiB plaintext blocks, and key metadata in Iceberg's StandardKeyMetadata encoding.

Each file is encrypted under a fresh random data encryption key (DEK), generated locally with no KMS call. Each block carries its own random nonce and is authenticated with an AAD that binds it to the file and to its position. This bounds memory usage and supports random access (Seek/ReadAt) on the decrypted file without buffering or decrypting more than the requested blocks.

The key metadata returned by Close contains the raw DEK, so it is a secret: persist it only where something protects it, such as a manifest or manifest list that is itself encrypted under a key encryption key.

StandardEncryptionManager always encrypts and always decrypts: it fails closed, returning ErrKeyIDRequired or ErrKeyMetadataRequired rather than silently falling back to plaintext. Use PlaintextEncryptionManager for tables or files that are not encrypted.

func NewStandardEncryptionManager added in v0.8.0

func NewStandardEncryptionManager(opts ...StandardManagerOption) *StandardEncryptionManager

NewStandardEncryptionManager creates a StandardEncryptionManager.

func (*StandardEncryptionManager) NewDecryptedInputFile added in v0.8.0

func (m *StandardEncryptionManager) NewDecryptedInputFile(ctx context.Context, file icebergio.File, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error)

NewDecryptedInputFile wraps file for transparent block-level AES-GCM decryption. keyMetadata must be a non-empty StandardKeyMetadata record, as produced by StandardEncryptionManager.NewEncryptedOutputFile or another Iceberg implementation; otherwise ErrKeyMetadataRequired is returned. The record must carry a 16-byte AAD prefix and a file length.

The plaintext length is derived from that file length. For key metadata without one, use StandardEncryptionManager.NewDecryptedInputFileWithLength.

func (*StandardEncryptionManager) NewDecryptedInputFileWithLength added in v0.8.0

func (m *StandardEncryptionManager) NewDecryptedInputFileWithLength(ctx context.Context, file icebergio.File, encryptedLength int64, keyMetadata EncryptionKeyMetadata) (EncryptedInputFile, error)

NewDecryptedInputFileWithLength is like StandardEncryptionManager.NewDecryptedInputFile, but accepts key metadata without a file length, as Java writes for data files and manifests. encryptedLength is the length of the encrypted file, header included, as recorded in table metadata (DataFile.FileSizeBytes, ManifestFile.Length). A file length in the key metadata takes precedence.

func (*StandardEncryptionManager) NewEncryptedOutputFile added in v0.8.0

func (m *StandardEncryptionManager) NewEncryptedOutputFile(_ context.Context, writer icebergio.FileWriter, keyID string) (EncryptedOutputFile, error)

NewEncryptedOutputFile creates a new AES-GCM block-encrypted output file. keyID is the table's encryption key ID and must be non-empty; otherwise ErrKeyIDRequired is returned. keyID is only checked: the file's key metadata holds the raw DEK.

type StandardManagerOption added in v0.8.0

type StandardManagerOption func(*StandardEncryptionManager)

StandardManagerOption configures a StandardEncryptionManager created by NewStandardEncryptionManager.

func WithStandardDataKeyLength added in v0.8.0

func WithStandardDataKeyLength(length int) StandardManagerOption

WithStandardDataKeyLength sets the length, in bytes, of the per-file data encryption key. It corresponds to the encryption.data-key-length table property. Valid AES key lengths are 16, 24, or 32 bytes; the default is StandardDefaultDataKeyLength.

Directories

Path Synopsis
Package awskms implements Iceberg key wrapping with AWS Key Management Service.
Package awskms implements Iceberg key wrapping with AWS Key Management Service.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL