encrypt

package
v3.6.7 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 34 Imported by: 0

README

encrypt — transparent column encryption for bun

Go-native field encryption at rest for bun models, using AES-256-GCM. Designed as a drop-in over existing plaintext tables: deploy it, and existing plaintext rows keep reading while new writes are encrypted — no separate migration step required to start.

Encoding & drop-in behaviour

Encrypted values are stored as:

<ENC>\0gcm1\0<keyId>:<base64(nonce || ciphertext+tag)>

The <ENC>\0gcm1\0 marker lets reads distinguish ciphertext from plaintext:

  • Decrypt returns an unmarked value (legacy/un-migrated plaintext) unchanged — that pass-through is what lets a column be encrypted one write at a time.
  • Decrypt fails on a marked value whose payload no longer decodes (malformed body, a key id outside ^[A-Za-z0-9_.-]{1,32}$ — the grammar the write side seals under, so such an id never reaches the KeyProvider —, invalid base64, shorter than a nonce). The marker is written by this cipher and nothing else, so a broken body behind it is damage, not plaintext — in practice a column too narrow for the ciphertext under a non-strict sql_mode, where MySQL truncates the write and only warns. Reading it back verbatim would hand the application a marker plus half a base64 blob as if it had stored them. Scan and the bulk Migrator report it for the same reason.
  • Decrypt fails as well on a value that begins with <ENC>\0 under a format this build does not read, the format named only when it is a lower-case token of at most 16 characters: the NUL after <ENC> is the claim of provenance, so a seal of a newer build, the fourth major's column-bound gcm2 seal included, or a damaged marker is never served as text, and the Scan of every column type over the package cipher and every Migrator mode, whatever its cipher, stop on it the same way; a binary of this major rolled back over such a column fails its reads instead of sealing the values again as data. An equality lookup through CiphertextCandidates answers gcm1 candidates only, so it finds no row of another format, with no error: a rolled-back binary misses the rows the fourth major re-sealed under a bound deterministic column. Through a wrapped or foreign cipher a column's Value refuses to write a value of that family, as it refuses a gcm1 one.
  • Encrypt is a no-op on an already-marked value (no double-encryption). A value of the <ENC>\0 family under another format is not marked to the write side: Encrypt and EncryptWithKeyId seal it as data, like any application value, so code that handles raw stored values outside the column types reads them through Decrypt first, which refuses it. The deterministic doors ask one question more: a marked value that authenticates but was sealed with a random nonce is not passed through by EncryptDeterministic — it is re-sealed deterministically under the key id it already carries (never the door's, so it is not a rotation), because a random-nonce seal in a deterministic column is a value CiphertextCandidates can never produce and the equality lookup would miss the row; a seal that is deterministic already passes through, whatever key it carries. The marker alone is not trusted: a marked value passes through only if it actually decrypts under its (known) key, so a plaintext that merely looks like ciphertext is sealed normally instead of being stored raw and poisoning later reads. A marked value carrying an unknown keyId is sealed the same way — to the write path it is application data, since this cipher only ever writes ids from its own key set. That is why a retired key must stay in the KeyProvider until every value sealed under it has been re-encrypted: drop it early and the next write that touches such a value seals it a second time, unrecoverably. The bulk Migrator is the strict counterpart: reading STORED values, it stops the run on any marked value that no longer decrypts — a missing key or a truncated write — instead of sealing over it.
  • The column types (EncryptedString, EncryptedStringFor, EncryptedDeterministicString, EncryptedDeterministicStringFor) do not take that pass-through: their Value seals every application value, a marked one included, and reading the column back returns the value as it was written. Otherwise a column an attacker can write and later read in the clear would hand back the plaintext of any seal of the compartment, from any row, column or table. The Migrator keeps that guarantee across its runs: it decides on the STORED value alone — whether it is sealed, under which key, deterministically or not — and seals the value it decrypted as data, so a rotation or a re-run never turns a seal stored as data back into a bare seal. A Cipher implemented outside this package, a wrapper over NewCipher for metrics or tracing included, loses the seal-as-data door: the column types refuse a value that carries the encryption marker instead of storing a bare seal, and the Migrator stops on such a row (see decrypt below). Install the package cipher directly where applications may store ciphertext as data.
  • The keyId travels in the value, so decryption always uses the key that wrote it (rotation-safe).

A sealed value is binary, never a string argument. The marker's two \0 glue bytes are what makes it a marker, and bun's formatter drops embedded NUL bytes when it inlines a string into the SQL text. Through the model — EncryptedString, EncryptedDeterministicString, or a pointer to either — this never arises: their Value() returns []byte, so bun emits a binary literal and every byte survives. It arises when userland writes the raw statement itself: db.ExecContext(ctx, "update ... set email = ?", string(sealed)) stores the value with its glue bytes stripped, which no longer matches the marker, so the next read takes the unmarked pass-through and hands the application the base64 body as if it were plaintext. Pass []byte for a sealed value in a raw statement, and see Searchable (deterministic) encryption for the same reason behind CiphertextCandidates returning [][]byte.

Column sizing

Encryption expands the value, so a column that held the plaintext will not hold the ciphertext. The stored form is 11 marker characters, the key id, a colon, and the base64 of a 12-byte nonce + the plaintext + a 16-byte GCM tag:

width = 12 + len(keyId) + ceil(4 * (plaintextBytes + 28) / 3)

That is roughly 1.34 characters per plaintext byte, plus 52. The expansion is over bytes, not characters, so a multi-byte UTF-8 character costs its full encoded length. Reference points for a two-character key id such as v1:

Longest plaintext Column width needed
32 bytes 94
64 bytes 137
152 bytes 254
153 bytes 256 — a VARCHAR(255) no longer fits
255 bytes 392

Widen the column before running the bulk migration. MigrateEncrypt and MigrateReencrypt refuse to start when a target column is too narrow for the widest value it holds — the check runs inside the migration itself, so the CLI command and the programmatic caller are covered alike, and the refusal reports the requiredWidth; the standalone Migrator.EnsureColumnCapacity answers the same question without running anything. The TEXT family is measured in bytes (CHARACTER_OCTET_LENGTH), which is what bounds the pure-ASCII ciphertext there; a VARCHAR(n) in its n characters. The check matters most on a server whose sql_mode is not strict: MySQL then accepts an overflowing UPDATE with a warning, storing a truncated ciphertext that can never be decrypted again while reporting the row as migrated and exiting 0.

The check measures the column once, before the first row, so it cannot bound a longer value written while the run is in flight.

A key rotation grows the column too: the key id is stored inside every sealed value, so rotating from v1 to 2026-07-rotated adds thirteen characters to every row at once, and a column sized exactly to the ciphertext it already holds is then too narrow for all of it. mode=reencrypt is checked against that growth as well — Migrator.EnsureColumnCapacityForReencrypt for programmatic callers — and the refusal names the targetKeyId alongside the requiredWidth. Rotating onto a key id of the same length or a shorter one needs no room and is never refused.

Nullable columns: EncryptedString/EncryptedDeterministicString are non-nullable value types — a SQL NULL scans to the Go zero value "", and writing it back encrypts the empty string into a non-NULL ciphertext (and, for a deterministic column, makes the row match an equality search on the empty plaintext). For a nullable column declare the field as a pointer (*EncryptedString / *EncryptedDeterministicString): bun leaves a NULL column as a nil pointer and never calls Value, so NULL round-trips faithfully.

Quick start

provider := encrypt.NewStaticKeyProvider("v1", map[string][]byte{"v1": key32Bytes})
encrypt.UseCipher(encrypt.NewCipher(provider)) // process-wide, set once at boot

Generate every key from crypto/rand (32 bytes). NewStaticKeyProvider refuses a key of the wrong length and a key of all zero bytes — the shape of a key that was never generated — and judges nothing else about a key: its strength is yours.

Type a column as EncryptedString to encrypt it transparently:

type User struct {
    Id    int64                  `bun:"id,pk"`
    Email encrypt.EncryptedString `bun:"email"`
}

EncryptedString masks its plaintext in fmt/slog/error/json output (String/LogValue/MarshalJSON return <redacted>); use an explicit string(value) conversion to read the real value. The redaction is one-way on purpose: UnmarshalJSON decodes a plaintext string as itself and leaves the value untouched on null, but refuses the placeholder — a document this package redacted, decoded back into the column, would otherwise seal <redacted> over the secret on the next write. It fails closed — Value/Scan return an error if no cipher is configured, so a misconfigured app never silently writes plaintext into an "encrypted" column.

Key rotation

KeyProvider exposes every active key; encrypt under a chosen key explicitly:

provider := encrypt.NewStaticKeyProvider("v2", map[string][]byte{"v1": oldKey, "v2": newKey})
provider.ActiveKeyIds()          // ["v2", "v1"] — current first
cipher.EncryptWithKeyId(value, "v2")

Bulk re-encrypt a table after rotating keys with the melody:encrypt:database command (see below).

Multiple key compartments (multi-context binaries)

UseCipher installs one process-wide default cipher — fine for one database, but a binary consolidating several apps should keep each context's keys in its own compartment instead of merging the key maps under a single current key. Install one named cipher per compartment and bind columns through a zero-size marker type:

encrypt.UseCipherNamed("crm", encrypt.NewCipher(crmProvider))
encrypt.UseCipherNamed("billing", encrypt.NewCipher(billingProvider))

type CrmCipher struct{}

func (instance CrmCipher) CipherName() string {
    return "crm"
}

type Customer struct {
    Iban encrypt.EncryptedStringFor[CrmCipher] `bun:"iban"`
}

The marker parameterizes the generic column types EncryptedStringFor[R] and EncryptedDeterministicStringFor[R], so the binding lives in the Go type — the only channel available, because database/sql gives Value()/Scan() no context. Compartments are isolated only as far as their keys are: the name selects the registry entry and is not bound into the ciphertext, so two compartments whose providers hold the same key under the same id decrypt each other's ciphertext. Give each compartment keys of its own. Key rotation inside one compartment keeps working through the key id embedded in each ciphertext. The plain EncryptedString keeps using the default cipher.

Two designs were considered and rejected: per-column key ids over one merged KeyProvider (the compartments stay merged — either context can decrypt the other's rows, exactly the isolation loss the feature exists to prevent) and a cipher per bunorm.Manager (a driver.Valuer has no manager context; bun query hooks would miss raw SQL paths).

For the bulk command with several compartments, declare command contexts on the module — each gets its own melody:encrypt:database:<name>:

app.RegisterModule(encrypt.NewModule(encrypt.ModuleConfig{
    Contexts: []encrypt.CommandContextConfig{
        {Name: "crm", Database: crmDatabase, Cipher: crmCipher},
        {Name: "billing", Database: billingDatabase, Cipher: billingCipher},
    },
}))

Searchable (deterministic) encryption

Random nonces make a column un-queryable. For lookup columns, EncryptedDeterministicString derives the nonce from the plaintext, so equal plaintext yields equal ciphertext under a key:

type User struct {
    Email encrypt.EncryptedDeterministicString `bun:"email"`
}

// build the right-hand side of an equality / IN lookup (one candidate per active key, rotation-safe):
candidates, _ := cipher.CiphertextCandidates("user@example.com")
db.NewSelect().Model(&user).Where("email IN (?)", bun.In(candidates)).Scan(ctx)

CiphertextCandidates returns [][]byte (not []string) on purpose: the ciphertext marker carries \0 glue bytes, and bun inlines a string argument into the SQL text through a formatter that drops embedded NUL bytes — which would corrupt the right-hand side and break the match. As [][]byte each candidate is emitted as an X'…' binary literal, so every byte survives and the lookup compares equal to the stored EncryptedDeterministicString column (whose Value() is likewise a binary []byte).

⚠️ Deterministic mode reveals plaintext equality (equal values produce identical ciphertext). The nonce is keyed only by (key, plaintext), so equal plaintext yields byte-identical ciphertext across every deterministic column and table under the same key — an observer of the stored values can correlate equal values across rows and tables, not just within one column. Use it only on low-entropy lookup fields, never on secrets where cross-column equality must stay hidden. Use EncryptedString (random nonce) everywhere else.

Bulk migration

Migrator (and the melody:encrypt:database CLI command) stream a table in keyset-paginated batches:

Mode What it does
encrypt encrypt plaintext columns (idempotent — already-encrypted values are skipped)
reencrypt decrypt with whichever key wrote each value, re-encrypt under --target-key (rotation)
decrypt rewrite columns as plaintext
melody melody:encrypt:database --table=users --primary-key=id --column=email --column=ssn --mode=encrypt
melody melody:encrypt:database --table=users --column=email --mode=reencrypt --target-key=v2

decrypt stops on a row whose decrypted value begins with <ENC>\0, a seal of this cipher or of any other format — an application stored a ciphertext as data — and names the row in the error's id, leaving it sealed: written bare, the value would be read as a seal by a column type that still decrypts, and would hand back another row's secret. Rewrite or clear that value through the application, then re-run. With a Cipher implemented outside this package, reencrypt and a deterministic encrypt stop on such a row the same way, since its own doors may pass the seal through. The column types over such a cipher refuse the write of a marker-shaped value for the same reason. encrypt over a column that still holds plaintext cannot tell a ciphertext an application stored there before the column was encrypted from one it wrote itself, and skips both as already sealed: run it before untrusted writers can reach the column.

⚠️ A reencrypt onto another key keeps each value's mode, so a searchable column stays searchable without the flag. Set TableSpec.Deterministic = true / --deterministic to CONVERT a random column to searchable while rotating; to convert a searchable column to random, run reencrypt onto the key it already carries without the flag.

Register as a module

The melody:encrypt:database command is not registered automatically — like every Melody command it has to be wired into the application. The integration ships a self-registering module so a single call does it:

app.RegisterModule(encrypt.NewModule(encrypt.ModuleConfig{
    Database: database, // *bun.DB (MySQL dialect)
    Cipher:   cipher,
}))

This implements CliModule and registers the command through RegisterCliCommands. If you wire the application's RegisterCliCommands by hand instead, append the slice from encrypt.Commands(database, cipher).

Registration is skipped only when Database, DatabaseFactory and Cipher are all nil — an entirely unconfigured module contributes no command. A partially configured one is a wiring mistake and panics at registration (module.go):

  • a Database (or DatabaseFactory) with no Cipher, or a Cipher with neither — encrypt module needs a database and a cipher;
  • both Database and DatabaseFactory set — encrypt module received both a database and a database factory - set exactly one.

ModuleConfig.Contexts is stricter: there is no all-nil carve-out per entry. Every entry present in the slice is validated unconditionally, so a zero-value entry panics rather than being skipped — the empty-Name check runs first (encrypt command context name is empty), followed by the same needs-a-database-and-a-cipher and exactly-one-of-database-or-factory checks, each naming the offending context. Omit an entry entirely rather than leaving it blank.

Formatting boundaries

The column types redact their plaintext when fmt calls their String or GoString method, which it does for the value itself under every verb but %p, whose misuse on a string prints the value in its bad-verb form. It is not an access-control boundary: a value held in an unexported field of another struct is printed by reflection without calling any method, so fmt.Sprintf("%+v", holder) prints the plaintext, and an explicit string(value) conversion is the plaintext. Format the encrypted value itself, and do not log the structs that hold it or the key material.

Testing / dev

encrypt.NewFakeCipher() is an identity cipher (no confidentiality) for tests and local development. Never install it in production.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Commands

func Commands(database *bun.DB, cipher Cipher) []clicontract.Command

func CommandsFromResolver added in v3.3.0

func CommandsFromResolver(databaseResolver func() (*bun.DB, error), cipher Cipher) []clicontract.Command

CommandsFromResolver is Commands against a lazily-resolved database: the resolver runs at the first command run instead of at construction, so the database is opened once the container is fully booted.

func UseCipher

func UseCipher(cipherInstance Cipher)

UseCipher installs the process-wide default cipher used by EncryptedString and EncryptedDeterministicString. A single-database application needs nothing else; a binary with several key compartments installs one named cipher per compartment with UseCipherNamed and binds columns via EncryptedStringFor.

func UseCipherNamed added in v3.2.0

func UseCipherNamed(name string, cipherInstance Cipher)

UseCipherNamed installs a named cipher — one key compartment — for columns bound through a CipherRef marker. Each named cipher owns its KeyProvider, so compartments are isolated as long as each provider holds keys of its own: the name selects the registry entry and is not bound into the ciphertext, so two compartments holding the same key under the same id decrypt each other. Merging every key into one provider loses even that, since either context can read the other's rows.

Types

type Cipher

type Cipher interface {
	Encrypt(plaintext string) (string, error)

	EncryptWithKeyId(plaintext string, keyId string) (string, error)

	EncryptDeterministic(plaintext string) (string, error)

	EncryptDeterministicWithKeyId(plaintext string, keyId string) (string, error)

	CiphertextCandidates(plaintext string) ([][]byte, error)

	Decrypt(encoded string) (string, error)
}

func NewCipher

func NewCipher(keys KeyProvider) Cipher

func NewFakeCipher

func NewFakeCipher() Cipher

NewFakeCipher answers a cipher whose every operation is the identity, for tests and local development. In production it writes plaintext into every encrypted column with no error, where having no cipher fails closed at the first write, so no production wiring path may reach it.

type CipherRef added in v3.2.0

type CipherRef interface {
	CipherName() string
}

CipherRef binds a column type to a named cipher through the type system: a zero-size marker type implementing CipherName parameterizes EncryptedStringFor and EncryptedDeterministicStringFor, since database/sql gives Value and Scan no context.

type CommandContextConfig added in v3.2.0

type CommandContextConfig struct {
	Name            string
	Database        *bun.DB
	Cipher          Cipher
	DatabaseFactory func(resolver containercontract.Resolver) (*bun.DB, error)
}

CommandContextConfig binds one compartment's database and cipher to a suffixed bulk command. Supply a DatabaseFactory to resolve the compartment's database from the container at the first command run; setting it together with Database is ambiguous and panics at registration.

type EncryptDatabaseCommand

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

func NewEncryptDatabaseCommand

func NewEncryptDatabaseCommand(database *bun.DB, cipher Cipher) *EncryptDatabaseCommand

func NewEncryptDatabaseCommandFromResolver added in v3.3.0

func NewEncryptDatabaseCommandFromResolver(databaseResolver func() (*bun.DB, error), cipher Cipher) *EncryptDatabaseCommand

NewEncryptDatabaseCommandFromResolver builds the command against a lazily-resolved database: the resolver runs at the first command run rather than at construction, so a registry-backed database is opened once the container is fully booted instead of at module registration. A resolver success is memoized and reused by subsequent runs; a resolver error is returned from the run and retried on the next one.

func NewEncryptDatabaseCommandFromResolverWithName added in v3.3.0

func NewEncryptDatabaseCommandFromResolverWithName(
	databaseResolver func() (*bun.DB, error),
	cipher Cipher,
	commandName string,
) *EncryptDatabaseCommand

NewEncryptDatabaseCommandFromResolverWithName is NewEncryptDatabaseCommandFromResolver under an explicit command name, so a multi-context binary can expose one lazily-resolved bulk command per compartment (melody:encrypt:database:<context>).

func NewEncryptDatabaseCommandWithName added in v3.2.0

func NewEncryptDatabaseCommandWithName(database *bun.DB, cipher Cipher, commandName string) *EncryptDatabaseCommand

NewEncryptDatabaseCommandWithName is NewEncryptDatabaseCommand under an explicit command name, so a multi-context binary can expose one bulk command per compartment (melody:encrypt:database:<context>).

func (*EncryptDatabaseCommand) Description

func (instance *EncryptDatabaseCommand) Description() string

func (*EncryptDatabaseCommand) Flags

func (instance *EncryptDatabaseCommand) Flags() []clicontract.Flag

func (*EncryptDatabaseCommand) Name

func (instance *EncryptDatabaseCommand) Name() string

func (*EncryptDatabaseCommand) Run

func (instance *EncryptDatabaseCommand) Run(
	runtimeInstance runtimecontract.Runtime,
	commandContext *clicontract.CommandContext,
) error

type EncryptedColumn added in v3.6.0

type EncryptedColumn interface {
	// contains filtered or unexported methods
}

EncryptedColumn marks every encrypted column type, the generic instantiations included. A consumer such as the audit trail's auto-redaction matches this interface, since each generic instantiation is a distinct reflect.Type.

type EncryptedDeterministicString

type EncryptedDeterministicString string

EncryptedDeterministicString is EncryptedString with the nonce derived from the plaintext, so equal plaintext seals to equal ciphertext and the column answers an equality lookup through Cipher.CiphertextCandidates. The nonce is keyed by the key and the plaintext alone, so equal values are correlatable across every deterministic column and table sealed under the same key; the readme's "Searchable (deterministic) encryption" section says what that rules the type out for.

func (EncryptedDeterministicString) Format added in v3.6.0

func (instance EncryptedDeterministicString) Format(state fmt.State, verb rune)

Format answers every verb that reaches it, the numeric ones included, with the redacted rendering; its limits are on EncryptedString.Format.

func (EncryptedDeterministicString) GoString deprecated added in v3.2.0

func (instance EncryptedDeterministicString) GoString() string

Deprecated: GoString is never reached — fmt consults Formatter before GoStringer, and this type implements Format, so Format answers %#v too. It is kept only because it was released in integrations/bunorm/v3.2.0 and dropping an exported method is a breaking change; it is removed at v4. String and Format carry the redaction.

func (EncryptedDeterministicString) LogValue

func (instance EncryptedDeterministicString) LogValue() slog.Value

func (EncryptedDeterministicString) MarshalJSON

func (instance EncryptedDeterministicString) MarshalJSON() ([]byte, error)

func (*EncryptedDeterministicString) Scan

func (instance *EncryptedDeterministicString) Scan(source any) error

func (EncryptedDeterministicString) String

func (instance EncryptedDeterministicString) String() string

func (*EncryptedDeterministicString) UnmarshalJSON added in v3.6.0

func (instance *EncryptedDeterministicString) UnmarshalJSON(data []byte) error

UnmarshalJSON refuses the redaction placeholder MarshalJSON writes and decodes any other string, for the reason on EncryptedString.UnmarshalJSON.

func (EncryptedDeterministicString) Value

func (instance EncryptedDeterministicString) Value() (driver.Value, error)

type EncryptedDeterministicStringFor added in v3.2.0

type EncryptedDeterministicStringFor[R CipherRef] string

EncryptedDeterministicStringFor is EncryptedDeterministicString bound to the named cipher the CipherRef marker R selects; see EncryptedStringFor for the compartment semantics and EncryptedDeterministicString for what the plaintext-derived nonce reveals.

func (EncryptedDeterministicStringFor[R]) Format added in v3.6.0

func (instance EncryptedDeterministicStringFor[R]) Format(state fmt.State, verb rune)

Format answers every verb that reaches it, the numeric ones included, with the redacted rendering; its limits are on EncryptedString.Format.

func (EncryptedDeterministicStringFor[R]) GoString deprecated added in v3.2.0

func (instance EncryptedDeterministicStringFor[R]) GoString() string

Deprecated: GoString is never reached — fmt consults Formatter before GoStringer, and this type implements Format, so Format answers %#v too. It is kept only because it was released in integrations/bunorm/v3.2.0 and dropping an exported method is a breaking change; it is removed at v4. String and Format carry the redaction.

func (EncryptedDeterministicStringFor[R]) LogValue added in v3.2.0

func (instance EncryptedDeterministicStringFor[R]) LogValue() slog.Value

func (EncryptedDeterministicStringFor[R]) MarshalJSON added in v3.2.0

func (instance EncryptedDeterministicStringFor[R]) MarshalJSON() ([]byte, error)

func (*EncryptedDeterministicStringFor[R]) Scan added in v3.2.0

func (instance *EncryptedDeterministicStringFor[R]) Scan(source any) error

func (EncryptedDeterministicStringFor[R]) String added in v3.2.0

func (instance EncryptedDeterministicStringFor[R]) String() string

func (*EncryptedDeterministicStringFor[R]) UnmarshalJSON added in v3.6.0

func (instance *EncryptedDeterministicStringFor[R]) UnmarshalJSON(data []byte) error

UnmarshalJSON refuses the redaction placeholder MarshalJSON writes and decodes any other string, for the reason on EncryptedString.UnmarshalJSON.

func (EncryptedDeterministicStringFor[R]) Value added in v3.2.0

func (instance EncryptedDeterministicStringFor[R]) Value() (driver.Value, error)

type EncryptedString

type EncryptedString string

func (EncryptedString) Format added in v3.6.0

func (instance EncryptedString) Format(state fmt.State, verb rune)

Format answers every verb that reaches it, the numeric ones included, with the redacted rendering. %p and %w never reach it, since fmt prints the operand by reflection first, and a value in an unexported field of a struct rendered with %v is walked by reflection with no method called.

func (EncryptedString) GoString deprecated added in v3.2.0

func (instance EncryptedString) GoString() string

Deprecated: GoString is never reached — fmt consults Formatter before GoStringer, and this type implements Format, so Format answers %#v too. It is kept only because it was released in integrations/bunorm/v3.2.0 and dropping an exported method is a breaking change; it is removed at v4. String and Format carry the redaction.

func (EncryptedString) LogValue

func (instance EncryptedString) LogValue() slog.Value

func (EncryptedString) MarshalJSON

func (instance EncryptedString) MarshalJSON() ([]byte, error)

func (*EncryptedString) Scan

func (instance *EncryptedString) Scan(source any) error

func (EncryptedString) String

func (instance EncryptedString) String() string

func (*EncryptedString) UnmarshalJSON added in v3.6.0

func (instance *EncryptedString) UnmarshalJSON(data []byte) error

UnmarshalJSON refuses the redaction placeholder MarshalJSON writes, so a round-tripped document cannot seal the placeholder over the secret. Any other string is the plaintext, and a json null leaves the value untouched.

func (EncryptedString) Value

func (instance EncryptedString) Value() (driver.Value, error)

type EncryptedStringFor added in v3.2.0

type EncryptedStringFor[R CipherRef] string
EncryptedStringFor is EncryptedString bound to the named cipher selected by the CipherRef marker R, so a multi-context binary keeps one key compartment per context:

   type CrmCipher struct{}

   func (instance CrmCipher) CipherName() string {
       return "crm"
   }

   type Customer struct {
       Iban encrypt.EncryptedStringFor[CrmCipher] `bun:"iban"`
   }

Install the compartment with encrypt.UseCipherNamed("crm", cipher). Each named cipher owns its KeyProvider: key rotation inside the compartment keeps working through the key id embedded in the ciphertext, and a column of one compartment cannot decrypt another's as long as each provider holds keys of its own, since the name is not bound into the ciphertext.

func (EncryptedStringFor[R]) Format added in v3.6.0

func (instance EncryptedStringFor[R]) Format(state fmt.State, verb rune)

Format answers every verb that reaches it, the numeric ones included, with the redacted rendering; its limits are on EncryptedString.Format.

func (EncryptedStringFor[R]) GoString deprecated added in v3.2.0

func (instance EncryptedStringFor[R]) GoString() string

Deprecated: GoString is never reached — fmt consults Formatter before GoStringer, and this type implements Format, so Format answers %#v too. It is kept only because it was released in integrations/bunorm/v3.2.0 and dropping an exported method is a breaking change; it is removed at v4. String and Format carry the redaction.

func (EncryptedStringFor[R]) LogValue added in v3.2.0

func (instance EncryptedStringFor[R]) LogValue() slog.Value

func (EncryptedStringFor[R]) MarshalJSON added in v3.2.0

func (instance EncryptedStringFor[R]) MarshalJSON() ([]byte, error)

func (*EncryptedStringFor[R]) Scan added in v3.2.0

func (instance *EncryptedStringFor[R]) Scan(source any) error

func (EncryptedStringFor[R]) String added in v3.2.0

func (instance EncryptedStringFor[R]) String() string

func (*EncryptedStringFor[R]) UnmarshalJSON added in v3.6.0

func (instance *EncryptedStringFor[R]) UnmarshalJSON(data []byte) error

UnmarshalJSON refuses the redaction placeholder MarshalJSON writes and decodes any other string, for the reason on EncryptedString.UnmarshalJSON.

func (EncryptedStringFor[R]) Value added in v3.2.0

func (instance EncryptedStringFor[R]) Value() (driver.Value, error)

type KeyProvider

type KeyProvider interface {
	CurrentKeyId() string

	ActiveKeyIds() []string

	Key(keyId string) ([]byte, error)
}

KeyProvider hands the cipher its keys. The contract has three obligations the compiler cannot see. Every id CurrentKeyId or ActiveKeyIds answers must stay resolvable through Key for as long as it is answered — the cipher reads in two steps (the id, then the key), so a provider that retires an id between the two fails a write that should have succeeded. Every id must match the key id grammar (`^[A-Za-z0-9_.-]{1,32}$`): the id is written into the stored value in front of a ":" separator, and seal refuses one that would corrupt the wire format. And a retired key must STAY in the set until every value sealed under it has been re-encrypted — the cipher treats a marker-shaped value under an unknown id as ordinary plaintext and seals it, so dropping a key while its ciphertexts remain makes them unrecoverable at the next write that touches them.

type Migrator

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

func NewMigrator

func NewMigrator(db *bun.DB, cipher Cipher) *Migrator

func (*Migrator) EnsureColumnCapacity added in v3.6.0

func (instance *Migrator) EnsureColumnCapacity(ctx context.Context, spec TableSpec) error

func (*Migrator) EnsureColumnCapacityForReencrypt added in v3.6.0

func (instance *Migrator) EnsureColumnCapacityForReencrypt(ctx context.Context, spec TableSpec, targetKeyId string) error

func (*Migrator) MigrateDecrypt

func (instance *Migrator) MigrateDecrypt(ctx context.Context, spec TableSpec) (int, error)

MigrateDecrypt reads the stored format before the cipher does, so a pass-through cipher cannot turn an unknown seal into plaintext, and stops on a decrypted value of the marker family, which written bare would read back as a seal.

func (*Migrator) MigrateEncrypt

func (instance *Migrator) MigrateEncrypt(ctx context.Context, spec TableSpec) (int, error)

func (*Migrator) MigrateReencrypt

func (instance *Migrator) MigrateReencrypt(ctx context.Context, spec TableSpec, targetKeyId string) (int, error)

type Module

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

func NewModule

func NewModule(config ModuleConfig) *Module

func (*Module) Description

func (instance *Module) Description() string

func (*Module) Name

func (instance *Module) Name() string

func (*Module) RegisterCliCommands

func (instance *Module) RegisterCliCommands(kernelInstance kernelcontract.Kernel) []clicontract.Command

type ModuleConfig

type ModuleConfig struct {
	Database *bun.DB
	Cipher   Cipher

	/* DatabaseFactory resolves the database for the unsuffixed command at the first command run, after Boot, and a success is memoized. A database it opens is not closed by the container, and a non-MySQL dialect panics at that first run. */
	DatabaseFactory func(resolver containercontract.Resolver) (*bun.DB, error)

	/* Contexts adds one bulk command per key compartment — melody:encrypt:database:<name> — for a multi-context binary; it composes with the legacy fields above, which keep the unsuffixed command. */
	Contexts []CommandContextConfig
}

ModuleConfig wires the melody:encrypt:database bulk command from a prebuilt *bun.DB or from a DatabaseFactory evaluated at the first command run, so a process in another mode never opens the database. Setting both panics at registration; with Database, DatabaseFactory and Cipher all nil no unsuffixed command is registered, and any other partial combination panics.

type StaticKeyProvider

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

func NewStaticKeyProvider

func NewStaticKeyProvider(currentKeyId string, keysById map[string][]byte) *StaticKeyProvider

NewStaticKeyProvider holds the keys it is handed for the life of the process. Every key must be 32 bytes, the AES-256 size, and not all zero bytes, the key of a buffer nobody wrote to; nothing beyond that is judged.

func (*StaticKeyProvider) ActiveKeyIds

func (instance *StaticKeyProvider) ActiveKeyIds() []string

func (*StaticKeyProvider) CurrentKeyId

func (instance *StaticKeyProvider) CurrentKeyId() string

func (StaticKeyProvider) Format added in v3.2.0

func (instance StaticKeyProvider) Format(state fmt.State, verb rune)

Format answers every verb that reaches it, the numeric ones included, with the String rendering, so no verb walks the keys by reflection. %p and %w never reach it: fmt prints the operand by reflection before consulting any method.

func (StaticKeyProvider) GoString deprecated added in v3.2.0

func (instance StaticKeyProvider) GoString() string

Deprecated: GoString is never reached — fmt consults Formatter before GoStringer, and this type implements Format, so Format answers %#v too. It is kept only because it was released in integrations/bunorm/v3.2.0 and dropping an exported method is a breaking change; it is removed at v4. String and Format carry the redaction.

func (*StaticKeyProvider) Key

func (instance *StaticKeyProvider) Key(keyId string) ([]byte, error)

func (StaticKeyProvider) String added in v3.2.0

func (instance StaticKeyProvider) String() string

String keeps the master keys out of every rendering fmt routes through this value's methods, naming only the current key id. A provider held in an unexported field of another struct is walked by reflection with no method called, so it is not embedded that way.

type TableSpec

type TableSpec struct {
	Table      string
	PrimaryKey string
	Columns    []string
	BatchSize  int

	Deterministic bool
}

Jump to

Keyboard shortcuts

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