fieldcrypt

package
v0.9.14 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 21 Imported by: 0 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 fieldcrypt encrypts the fields a collection marks `encrypt` before they reach the database, and decrypts them for readers (design/field-encryption.md §4 and §5).

Envelope encryption: a field key (a `key` secret the developer holds a copy of) only wraps data keys; data keys encrypt values. Replacing a field key re-wraps a handful of data keys and rewrites no document.

Index

Constants

View Source
const (
	IDSize    = 16
	NonceSize = 12
	KeySize   = 32
	// Overhead is what encrypting adds to a value: version, data key id, nonce and GCM tag.
	Overhead = 1 + IDSize + NonceSize + 16
)

Sizes of the parts of an encrypted value.

View Source
const (
	KindData  = "data"
	KindIndex = "index"
)

Kinds of keys a field has: the data key encrypts its values, the index key keys its blind index.

View Source
const (
	StatusActive      = "active"
	StatusDecryptOnly = "decrypt_only"
	StatusRetired     = "retired"
)

Statuses of a data key.

View Source
const Version byte = 1

Version is the first byte of every encrypted value.

Variables

View Source
var (
	// ErrUnavailable means a key needed to read or write an encrypted field can't be used: it
	// does not exist, the instance has no secrets key, or a data key can't be opened with it.
	ErrUnavailable = errors.New("the key of an encrypted field is not available")
	// ErrCorrupt means a stored value is not a well-formed encrypted value, or fails its
	// authentication: it was altered, or moved to another document or field.
	ErrCorrupt = errors.New("an encrypted value can't be authenticated")
)

Errors. None of them ever carries a value.

Functions

func CanonicalJSON

func CanonicalJSON(v any) ([]byte, error)

CanonicalJSON serializes a value the way the format specifies: JSON without insignificant white space, object keys sorted, and no HTML escaping (`<`, `>` and `&` stay as they are).

func EncodeKeyLine

func EncodeKeyLine(r Record) ([]byte, error)

EncodeKeyLine renders a key record as one line of a package (no newline).

func NewDataKey

func NewDataKey() (id, key []byte, err error)

NewDataKey makes a random data key and its id.

func Normalize

func Normalize(ops []string, v any) any

Normalize applies a field's normalizations (trim, lower, upper) to a value; only strings change.

func Open

func Open(dataKey []byte, c Ciphertext, associated []byte) ([]byte, error)

Open decrypts a value with the data key its id names; a value that fails authentication (altered, or from another document or field) gives ErrCorrupt.

func OpenWith

func OpenWith(fieldKey []byte, rec Record, sourceRealm string, ct Ciphertext, docID string) (any, error)

OpenWith opens a value of an export package with the field key that wraps the value's data key: rec is the data key's record from the package, sourceRealm the realm the package was exported from (it is part of what the value is bound to), docID the id of the document. It returns the value as JSON text. Neither the server nor a master key is involved.

func ParseID

func ParseID(c Ciphertext) ([]byte, error)

ParseID returns the data key id of an encrypted value without opening it.

func Rewrap

func Rewrap(ctx context.Context, store Store, realm, key string, m Material) (int, error)

Rewrap re-wraps, with the current version of a field key, every data key wrapped by an older one, and returns how many it changed. It is safe to run again after an interruption, and alongside another process doing the same: a key already re-wrapped is skipped.

func Unwrap

func Unwrap(fieldKey, wrapped, id []byte, f Field, kind string) ([]byte, error)

Unwrap is the inverse of Wrap; a wrong field key gives ErrUnavailable.

func ValueAD

func ValueAD(f Field, docID string) []byte

ValueAD, WrapAD and BlindAD are the associated data the format specifies, exported for the tools that implement it and the tests that pin it down.

func Wrap

func Wrap(fieldKey, dataKey, id []byte, f Field, kind string) ([]byte, error)

Wrap encrypts a data key under a field key (AES-256-GCM, with the id and the field as associated data): nonce followed by ciphertext and tag.

func WrapAD

func WrapAD(f Field, kind string, id []byte) []byte

WrapAD is the associated data of a wrapped data key (see ValueAD).

Types

type Ciphertext

type Ciphertext []byte

Ciphertext is an encrypted value as a document holds it: the stored form of BSON binary subtype 6 (version, data key id, nonce, AES-256-GCM ciphertext and tag).

func Seal

func Seal(dataKey, id, plaintext, associated []byte) (Ciphertext, error)

Seal encrypts plaintext under the data key with the given id.

type Field

type Field struct {
	Realm, Database, Collection, Path string
}

Field names one encrypted field: where its data keys live.

type Material

type Material struct {
	Current         []byte
	Version         int
	Previous        []byte
	PreviousVersion int
}

Material is what the secrets store gives of a field key: its value and version, and, while a rotation is unfinished, the previous value and version.

type MemStore

type MemStore struct {
	Keys map[string]Record
	// contains filtered or unexported fields
}

MemStore is a Store in memory, for tests.

func NewMemStore

func NewMemStore() *MemStore

NewMemStore returns an empty MemStore.

func (*MemStore) ActiveDataKey

func (m *MemStore) ActiveDataKey(_ context.Context, database, collection, path, kind string) (Record, bool, error)

func (*MemStore) CreateDataKey

func (m *MemStore) CreateDataKey(_ context.Context, r Record) (bool, error)

func (*MemStore) DataKeyByID

func (m *MemStore) DataKeyByID(_ context.Context, id string) (Record, bool, error)

func (*MemStore) DataKeyPaths

func (m *MemStore) DataKeyPaths(_ context.Context, database, collection string) ([]string, error)

func (*MemStore) DataKeysByKey

func (m *MemStore) DataKeysByKey(_ context.Context, key string) (int64, error)

func (*MemStore) DataKeysOf

func (m *MemStore) DataKeysOf(_ context.Context, database, collection, path string) ([]Record, error)

func (*MemStore) DataKeysToRewrap

func (m *MemStore) DataKeysToRewrap(_ context.Context, key string, belowVersion int, afterID string, limit int) ([]Record, error)

func (*MemStore) RewrapDataKey

func (m *MemStore) RewrapDataKey(_ context.Context, id string, wrapped []byte, from, to int) (bool, error)

func (*MemStore) SetDataKeyStatus

func (m *MemStore) SetDataKeyStatus(_ context.Context, id, status string) error

type Record

type Record struct {
	ID          string // 32 hex characters
	Database    string
	Collection  string
	Path        string
	Kind        string
	Generation  int
	Key         string // the field key's name
	Wrapped     []byte
	WrapVersion int // the version of the field key that wrapped it
	Status      string
	CreatedAt   time.Time
}

Record is a data key as stored in <realm>___system.data_keys: one per field and generation.

func DecodeKeyLine

func DecodeKeyLine(line []byte) (Record, error)

DecodeKeyLine reads a line EncodeKeyLine wrote.

func (Record) Field

func (r Record) Field(realm string) Field

Field returns where the record's key is used, in a realm.

type Ring

type Ring struct {
	Realm string
	Store Store
	// Keys returns a field key by name; ErrUnavailable when it can't.
	Keys func(ctx context.Context, name string) (Material, error)
	Now  func() time.Time
	// contains filtered or unexported fields
}

Ring encrypts and decrypts the documents of one realm. It caches unwrapped data keys, which never change (rotating a field key only changes how they are wrapped), and the key chosen for writes, for a minute so a new generation applies without a restart.

func (*Ring) ActiveID

func (r *Ring) ActiveID(ctx context.Context, c *registry.Collection, path string) (string, error)

ActiveID is the id (32 hex characters) of the data key new values of a field are sealed with.

func (*Ring) Blind

func (r *Ring) Blind(ctx context.Context, c *registry.Collection, path string, v any) ([]byte, error)

Blind returns the blind index to look a value of a searchable field up by.

func (*Ring) Decrypt

func (r *Ring) Decrypt(ctx context.Context, c *registry.Collection, doc map[string]any) error

Decrypt opens the encrypted fields of a document read from storage, in place: the ones the collection configures and the ones it once did (data keys remain for them, and their values stay encrypted until a migration opens them). A value that isn't encrypted (data from before the field was encrypted) is left as it is.

func (*Ring) Encrypt

func (r *Ring) Encrypt(ctx context.Context, c *registry.Collection, doc map[string]any) (map[string]any, error)

Encrypt returns doc with its encrypted fields sealed. doc is not modified: the maps along each encrypted path are copied, because the caller still answers with the plaintext. A field that is absent stays absent; one already sealed is left as it is.

func (*Ring) Ensure

func (r *Ring) Ensure(ctx context.Context, c *registry.Collection) error

Ensure makes sure every encrypted field of c has a data key to write with, creating the first generation under the field's key when none exists. Several instances may race: the unique (field, generation) makes one win, and the others use its key.

func (*Ring) HistoricPaths

func (r *Ring) HistoricPaths(ctx context.Context, c *registry.Collection) ([]string, error)

HistoricPaths lists the paths of a collection with data keys that its configuration no longer encrypts: values may still be stored encrypted there until a migration opens them.

func (*Ring) OpenAt

func (r *Ring) OpenAt(ctx context.Context, c *registry.Collection, path, docID string, ct Ciphertext) (any, error)

OpenAt opens one encrypted value of the field at path in the document with that id.

func (*Ring) Rekey

func (r *Ring) Rekey(ctx context.Context, c *registry.Collection, path string) (Record, error)

Rekey starts a new generation of the data key of an encrypted field, so writes use a fresh key; values under the old one stay readable until a migration re-encrypts them. For data keys that may have leaked; replacing the field key alone never needs it.

func (*Ring) Reset

func (r *Ring) Reset()

Reset forgets every cached key, so the next use reads and unwraps them again.

func (*Ring) Retire

func (r *Ring) Retire(ctx context.Context, c *registry.Collection, path string, used func(id string) (int64, error)) ([]string, error)

Retire marks as retired the keys of a field no value uses any more: used(id) says how many values are still sealed with a key. The active data key of a field that is no longer encrypted is retired too, once none is left. It returns the ids it retired.

func (*Ring) SealAt

func (r *Ring) SealAt(ctx context.Context, c *registry.Collection, path, docID string, v any) (Ciphertext, string, error)

SealAt encrypts a plaintext value of the field at path for the document with that id, with the field's active data key, and returns the id (32 hex characters) of the key it used.

type Store

type Store interface {
	// ActiveDataKey returns the key used for writes of a field, if there is one.
	ActiveDataKey(ctx context.Context, database, collection, path, kind string) (Record, bool, error)
	// DataKeyByID returns a key by its id (32 hex characters).
	DataKeyByID(ctx context.Context, id string) (Record, bool, error)
	// CreateDataKey stores a key; false when that field already has the generation.
	CreateDataKey(ctx context.Context, r Record) (bool, error)
	// DataKeysToRewrap returns, ordered by id after afterID, up to limit keys wrapped by the
	// named field key at a version below belowVersion.
	DataKeysToRewrap(ctx context.Context, key string, belowVersion int, afterID string, limit int) ([]Record, error)
	// RewrapDataKey replaces a key's wrapping if it still has wrap version from; false when it
	// no longer does (another process did it).
	RewrapDataKey(ctx context.Context, id string, wrapped []byte, from, to int) (bool, error)
	// DataKeysByKey counts the keys wrapped by a field key that are not retired.
	DataKeysByKey(ctx context.Context, key string) (int64, error)
	// DataKeysOf lists every key of a field (all kinds, generations and statuses), oldest first.
	DataKeysOf(ctx context.Context, database, collection, path string) ([]Record, error)
	// DataKeyPaths lists the paths of a collection that have data keys: the fields that are, or
	// once were, encrypted.
	DataKeyPaths(ctx context.Context, database, collection string) ([]string, error)
	// SetDataKeyStatus changes a key's status (active, decrypt_only, retired).
	SetDataKeyStatus(ctx context.Context, id, status string) error
}

Store keeps data keys. Implemented by the system database of a realm.

Jump to

Keyboard shortcuts

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