secrets

package
v0.6.12 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CustodyFile    = "file"
	CustodyWrapped = "wrapped"
)

Server-key custody (plans/customer-key-custody.md §3). With custody "wrapped" the 32-byte server key that seals env, registry, mounts, the egress CA and toolbox tokens exists on disk only wrapped by the customer's key store, and is unwrapped into memory at boot.

View Source
const (
	RefVersion = 1
	// EnvelopeVersion 4 binds sandbox identity into AEAD AAD (and KMS
	// EncryptionContext on the KMS path) so ciphertext cannot be relabeled
	// across sandboxes when recipient sets match.
	EnvelopeVersion = 4
)

Envelope / handle version constants. RefVersion is the provider handle version stored alongside the row; EnvelopeVersion is the identity-bound on-wire AEAD envelope format.

View Source
const (
	ProviderLocal  = "local"
	ProviderAWSKMS = "awskms"
	ProviderVault  = "vault"
	ProviderPKCS11 = "pkcs11"
)

Provider name constants for SB_SECRET_PROVIDER.

View Source
const (
	BudgetForeground = "foreground"
	BudgetCreate     = "create"
	BudgetBackground = "background"
)

Limiter budget names, used by LimiterObserver.

View Source
const (
	RingStateCurrent = "current"
	RingStateDecrypt = "decrypt"
	RingStateRetired = "retired"
)

Ring key states.

View Source
const (

	// CorrelationHeader carries the sandboxd secret-audit correlation id to
	// the key store, so a Vault audit entry joins to the exact sandboxd event
	// (CEO-E3). Vault records it once listed under audited request headers.
	CorrelationHeader = "X-Aerol-Correlation-ID"
)
View Source
const DefaultMaxInFlight = 8

DefaultMaxInFlight is the default foreground cap on key-store calls per node (SB_SECRET_PROVIDER_MAX_INFLIGHT).

View Source
const IdentityTokenPrefix = "aocrwrap:"

IdentityTokenPrefix is the sentinel AOCR's auth service uses to route `aocrwrap:<blob>` strings through the wrap-validation path rather than the static-PAT or cluster-PAT paths. Anything starting with this prefix is treated as a wrapped upstream credential.

View Source
const KeyRingFileFormat = 1

KeyRingFileFormat is the version of custody=file's plaintext ring file.

View Source
const WrappedKeyFormat = 1

WrappedKeyFormat is the version of the wrapped server-key file.

View Source
const WrappedKeyRingFormat = 2

WrappedKeyRingFormat is the wrapped server-key file once it holds a ring. A ring of the one legacy key is still written as format 1, so a node that never rotates keeps a file older builds read.

Variables

View Source
var (
	ErrNotFound        = errors.New("secret not found")
	ErrRecipientDenied = errors.New("recipient denied")
	ErrVersionMismatch = errors.New("secret version mismatch")
	ErrDecryptFailed   = errors.New("secret decrypt failed")

	// Provider-agnostic (used by external backends in T10+).
	ErrProviderUnavailable = errors.New("secret provider unavailable")
	ErrProviderThrottled   = errors.New("secret provider throttled")
	ErrProviderDenied      = errors.New("secret provider denied")

	// ErrKeyRevoked means the key store deliberately refused the key: it was
	// disabled, deleted or scheduled for deletion. Only these signals may trip a
	// revoke (plans/customer-key-custody.md §10); a permission error or an outage
	// never does.
	ErrKeyRevoked = errors.New("key revoked by the key store")
	// ErrKeyVersionRetired means the row was wrapped under a key version the
	// key store no longer decrypts. It marks a stale row, never a revoke.
	ErrKeyVersionRetired = errors.New("key version retired by the key store")
)

Typed sentinel errors for secret provider operations. Callers and metrics should prefer errors.Is on these before string-matching.

View Source
var ErrKeyFileChanged = errors.New("the server-key file changed while it was being edited; run again")

ErrKeyFileChanged means the server-key file changed between the read an edit started from and its write: the daemon's rewrap and `sandboxd key rotate` both edit it, and neither may undo the other.

View Source
var ErrNotLocalRow = errors.New("not a row wrapped by the server key")

ErrNotLocalRow is a cluster-secret row whose data key the server key does not wrap (a key-store row): a server-key rotation leaves it alone.

View Source
var ErrRotationInProgress = errors.New("a rotation is already in progress")

ErrRotationInProgress refuses a stage while another key is decrypt-only: one rotation at a time, so "zero rows on the old key" means one key.

View Source
var ErrServerKeyCheck = errors.New("unwrapped server key does not match the file's check")

ErrServerKeyCheck means the key store unwrapped the file to a key whose check does not match: the wrong file, or a file edited by hand.

Functions

func BackgroundSlots added in v0.6.9

func BackgroundSlots() int

BackgroundSlots is the size of the background budget, which the PKCS#11 session pool adds to the foreground cap.

func CallClass added in v0.6.9

func CallClass(err error) string

CallClass is the outcome class of one key-store call, for metrics.

func CanaryWrapUnwrap added in v0.6.1

func CanaryWrapUnwrap(ctx context.Context, w DataKeyWrapper) error

CanaryWrapUnwrap exercises Wrap+Unwrap with a random 32-byte DEK. Used at daemon boot for awskms (E4 lite). Does not touch BlobStore or create rows.

func ContextForBackground added in v0.6.9

func ContextForBackground(ctx context.Context) context.Context

ContextForBackground marks ctx as background work (re-check, sweep), which uses its own budget and never retries an unavailable key store.

func ContextForCreate added in v0.6.9

func ContextForCreate(ctx context.Context) context.Context

ContextForCreate marks ctx as a create-path call, which may use the reserved create slot.

func ContextWithBackgroundPurpose added in v0.6.9

func ContextWithBackgroundPurpose(ctx context.Context, purpose string) context.Context

ContextWithBackgroundPurpose names a call with no request behind it (boot, recheck, sweep). The key store then sees the correlation id "aerolvm-background:<purpose>:<node-id>", recognisable in its audit log though it joins to no sandboxd event.

func ContextWithIncarnationID added in v0.6.1

func ContextWithIncarnationID(ctx context.Context, incarnationID string) context.Context

ContextWithIncarnationID attaches a placement incarnation to ctx for Put.

func ContextWithPutOutbox added in v0.6.1

func ContextWithPutOutbox(ctx context.Context, incarnationID string, recipients []string) context.Context

ContextWithPutOutbox attaches remaining peer PUT targets to journal atomically with the sealed row (crash-vacuum fix). Recipients should exclude the originator; empty clears any prior outbox for the sandbox on Put.

func ContextWithRetiredRecipients added in v0.6.1

func ContextWithRetiredRecipients(ctx context.Context, recipients []string) context.Context

ContextWithRetiredRecipients attaches the peers removed by a reseal. The blob store journals them atomically with the new sealed generation, but the delete reconciler must wait until Raft publishes that generation.

func CurrentKeyVersion added in v0.6.9

func CurrentKeyVersion(ctx context.Context, w DataKeyWrapper) (version string, ok bool, err error)

CurrentKeyVersion asks w (through the limiter and the router) for the sealing provider's current key. ok is false when the provider has no versions to move between (AWS KMS).

func EncryptionContextAAD added in v0.6.9

func EncryptionContextAAD(encCtx map[string]string) []byte

EncryptionContextAAD encodes encCtx as additional authenticated data for backends that take raw AAD (FakeKMS, Vault Transit's associated_data, the PKCS#11 helper's GCM AAD): sorted keys, each key and value NUL-terminated, so two different contexts never encode the same.

func EncryptionContextForBinding added in v0.6.1

func EncryptionContextForBinding(b SealBinding) map[string]string

EncryptionContextForBinding is the AWS KMS EncryptionContext for v4 wraps.

func EnvAAD added in v0.6.1

func EnvAAD(sandboxID, incarnationID string) []byte

EnvAAD binds an environment to both its sandbox and lifecycle. JSON string framing prevents ambiguous boundaries even if an ID contains a delimiter.

func EnvelopeRecipients added in v0.6.1

func EnvelopeRecipients(sealed []byte) ([]string, error)

EnvelopeRecipients returns the recipient list declared in a sealed envelope without decrypting the payload. Used by peer-receive validation so a node can reject blobs that do not name it before storing ciphertext.

func FormatRef added in v0.6.1

func FormatRef(sandboxID, incarnationID string, version int) string

FormatRef builds the sole current handle shape. Callers must supply the lifecycle incarnation; ParseRef rejects incarnation-less references.

func IncarnationIDFromContext added in v0.6.1

func IncarnationIDFromContext(ctx context.Context) string

IncarnationIDFromContext returns the Put-time incarnation, or "".

func IsExternalProvider added in v0.6.9

func IsExternalProvider(name string) bool

IsExternalProvider reports whether name keeps key material in an external key store (anything but local).

func IsKeyStoreError added in v0.6.9

func IsKeyStoreError(err error) bool

IsKeyStoreError reports whether err carries one of the five key-store classes, which callers must pass on unchanged: folding a revoke into ErrDecryptFailed would hide it from the API's 503 key_revoked answer.

func IsVaultPolicyError added in v0.6.9

func IsVaultPolicyError(err error) bool

IsVaultPolicyError reports whether err is the boot refusal for a token with more than update on the Transit paths.

func KeyAADBound added in v0.6.1

func KeyAADBound(recipients []string, b SealBinding) []byte

KeyAADBound authenticates the wrapped data-key for v4 envelopes.

func LoadPlaintextKey added in v0.6.9

func LoadPlaintextKey(keyB64, path string) (key []byte, ok bool, err error)

LoadPlaintextKey reads the plaintext server key from the env value or the key file, never generating one. ok is false when neither exists.

func NewProvider added in v0.6.1

func NewProvider(ctx context.Context, opts ProviderOptions) (Provider, DataKeyWrapper, error)

NewProvider builds the configured Provider. For an external provider it also returns the DataKeyWrapper so callers can run CanaryWrapUnwrap.

func NewServerKey added in v0.6.9

func NewServerKey() ([]byte, error)

NewServerKey returns 32 fresh random bytes.

func NextRingID added in v0.6.9

func NextRingID(entries []RingEntry) uint32

NextRingID is the id a staged key takes: one past every id the ring has ever had, retired ones included, so an id is never reused.

func NormalizeProviderName added in v0.6.1

func NormalizeProviderName(name string) string

NormalizeProviderName lowercases and defaults empty to local.

func NormalizeRecipients added in v0.6.1

func NormalizeRecipients(in []string) []string

NormalizeRecipients trims, dedupes, and sorts recipient node IDs.

func OpenEnvelopePayloadBound added in v0.6.1

func OpenEnvelopePayloadBound(dek []byte, sealed []byte, recipients []string, binding SealBinding) ([]byte, error)

OpenEnvelopePayloadBound decrypts a v4 payload with a raw data key.

func OpenRawEnvelopeBound added in v0.6.1

func OpenRawEnvelopeBound(c *Cipher, sealed []byte, nodeID string, expect SealBinding) ([]byte, error)

OpenRawEnvelopeBound opens a v4 envelope and enforces its identity and recipient binding.

func OpenRawEnvelopeExternalBound added in v0.6.1

func OpenRawEnvelopeExternalBound(sealed []byte, expect SealBinding, unwrap func(wrapped []byte) ([]byte, error)) ([]byte, error)

OpenRawEnvelopeExternalBound opens with an expected sandbox binding for v4 AAD.

func ParseRingSummary added in v0.6.9

func ParseRingSummary(s string) map[uint32]string

ParseRingSummary reads a RingSummary back; malformed parts are skipped.

func PayloadAADBound added in v0.6.1

func PayloadAADBound(recipients []string, b SealBinding) []byte

PayloadAADBound authenticates the ciphertext for v4 envelopes.

func PutOutboxFromContext added in v0.6.1

func PutOutboxFromContext(ctx context.Context) (incarnationID string, recipients []string, ok bool)

PutOutboxFromContext returns optional put-outbox recipients for an originator Put.

func RecipientAllowed added in v0.6.1

func RecipientAllowed(recipients []string, nodeID string) bool

RecipientAllowed reports whether nodeID may open an envelope sealed for recipients.

func RefuseGroupOtherBits added in v0.6.9

func RefuseGroupOtherBits(path string) error

RefuseGroupOtherBits refuses a secret file that anyone but its owner can read, write or run. One rule, one message, for every secret file sandboxd loads: the upstream wrap key, the PKCS#11 PIN file and the wrapped server key (eng D14). A caller with a stricter rule adds it after this check. A missing file returns the os.Stat error unchanged, so callers can still test it with errors.Is(err, os.ErrNotExist).

func ReplaceKeyRingFile added in v0.6.9

func ReplaceKeyRingFile(path string, prev *KeyRingFile, next KeyRingFile) error

ReplaceKeyRingFile is WriteKeyRingFile as a compare-and-swap under the key-file lock: it writes next only if the file still holds prev (nil: the file must not exist yet), else ErrKeyFileChanged.

func ReplaceWrappedKeyFile added in v0.6.9

func ReplaceWrappedKeyFile(path string, prev, next WrappedKeyFile) error

ReplaceWrappedKeyFile writes next only if the file still holds prev: a compare-and-swap on the file's content, re-read just before the write.

func ResealLocalEnvelope added in v0.6.9

func ResealLocalEnvelope(sealed []byte, local *Cipher) (out []byte, from uint32, changed bool, err error)

ResealLocalEnvelope moves a local row's data key onto the server key's current ring key (§13 step 3). Only WrappedKey changes, so the result is the same secret by SameEnvelopeContent. from is the key that opened it; changed is false when it was already current.

func RetiredKeyStillPresent added in v0.6.9

func RetiredKeyStillPresent(in CustodyInputs, plaintextB64 string) bool

RetiredKeyStillPresent reports a plaintext legacy key left behind after ring key 0 was retired: the rotation's claim needs it destroyed.

func RetiredRecipientsFromContext added in v0.6.1

func RetiredRecipientsFromContext(ctx context.Context) (recipients []string, ok bool)

RetiredRecipientsFromContext returns the optional reseal-retirement journal.

func RewrapEnvelope added in v0.6.9

func RewrapEnvelope(ctx context.Context, sealed []byte, local *Cipher, w DataKeyWrapper) ([]byte, error)

RewrapEnvelope moves sealed's data key onto w's current key: the key is opened with the server key (a local row) or w, checked against the payload, and wrapped again. Everything else in the envelope is kept, so the result is the same secret by SameEnvelopeContent.

func RingSummary added in v0.6.9

func RingSummary(entries []RingEntry) string

RingSummary is a ring's ids and states, "0:retired,1:current": what the daemon remembers between re-reads to record rotation steps.

func SameEnvelopeContent added in v0.6.9

func SameEnvelopeContent(a, b []byte) bool

SameEnvelopeContent reports whether a and b are the same sealed secret apart from WrappedKey (eng D3): after a rewrap two holders of one generation hold different bytes for the same content.

func SealEnvelopeBound added in v0.6.1

func SealEnvelopeBound(c *Cipher, s Secrets, recipients []string, binding SealBinding) ([]byte, error)

SealEnvelopeBound marshals s and seals it bound to sandbox identity.

func SealRawEnvelopeBound added in v0.6.1

func SealRawEnvelopeBound(c *Cipher, plain []byte, recipients []string, binding SealBinding) ([]byte, error)

SealRawEnvelopeBound seals plaintext into a v4 identity-bound envelope.

func SealRawEnvelopeWrappedBound added in v0.6.1

func SealRawEnvelopeWrappedBound(plain []byte, recipients []string, binding SealBinding, wrap func(dek []byte) ([]byte, error)) ([]byte, error)

SealRawEnvelopeWrappedBound seals plaintext with a fresh DEK and stores wrap(dek) in WrappedKey. Recipients are still recorded for fan-out targeting even when the wrap backend (KMS) does not enforce recipient binding on Open.

func UnwrapServerKey added in v0.6.9

func UnwrapServerKey(ctx context.Context, w DataKeyWrapper, f WrappedKeyFile) ([]byte, error)

UnwrapServerKey unwraps f with w and verifies its check.

func WrapUpstreamCreds added in v0.2.3

func WrapUpstreamCreds(ring *UpstreamWrapKeyRing, creds UpstreamCredentials) (string, error)

WrapUpstreamCreds seals `creds` with the current key in `ring` and returns a Docker `identitytoken` value of the form `aocrwrap:<base64url>`. AOCR's auth service unwraps and probes the upstream registry with the embedded credentials.

The blob layout is AES-256-GCM `nonce(12) || ciphertext || tag(16)`, then base64url. AOCR's `unwrap` reads exactly this format.

func WrappedKeyBackend added in v0.6.9

func WrappedKeyBackend(w []byte) string

WrappedKeyBackend names the backend that wrapped w by its tag: ProviderVault, ProviderPKCS11, or "" for an untagged key (local or AWS KMS).

func WrappedKeyVersion added in v0.6.9

func WrappedKeyVersion(w []byte) string

WrappedKeyVersion names the key a wrapped key is under: "vault:v3" for Vault Transit, "p11:<label>" for PKCS#11, "" for an untagged key (local or AWS KMS, which rotates in place and has no version to retire).

func WriteKeyRingFile added in v0.6.9

func WriteKeyRingFile(path string, f KeyRingFile) error

WriteKeyRingFile writes the ring file atomically at mode 0600.

func WriteWrappedKeyFile added in v0.6.9

func WriteWrappedKeyFile(path string, f WrappedKeyFile) error

WriteWrappedKeyFile writes f to path atomically at mode 0600.

Types

type AWSKMS added in v0.6.1

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

AWSKMS wraps DEKs with AWS KMS Encrypt/Decrypt. Ciphertext still lives in BlobStore; this only custodians the data key.

func NewAWSKMS added in v0.6.1

func NewAWSKMS(ctx context.Context, keyID string) (*AWSKMS, error)

NewAWSKMS builds an AWSKMS from the default AWS config chain (env, shared config, IAM role). keyID is the CMK id/arn/alias (SB_SECRET_AWS_KMS_KEY_ID).

func NewAWSKMSWithClient added in v0.6.1

func NewAWSKMSWithClient(client kmsAPI, keyID string) *AWSKMS

NewAWSKMSWithClient is for tests that inject a fake kmsAPI.

func (*AWSKMS) Unwrap added in v0.6.1

func (a *AWSKMS) Unwrap(ctx context.Context, wrapped []byte, encCtx map[string]string) ([]byte, error)

Unwrap implements DataKeyWrapper via KMS Decrypt.

func (*AWSKMS) Wrap added in v0.6.1

func (a *AWSKMS) Wrap(ctx context.Context, dek []byte, encCtx map[string]string) ([]byte, error)

Wrap implements DataKeyWrapper via KMS Encrypt.

type BlobStore added in v0.6.1

type BlobStore interface {
	Put(ctx context.Context, rec SecretBlob) error
	Get(ctx context.Context, ref string) (*SecretBlob, error)
	DeleteForSandbox(ctx context.Context, sandboxID string) error
	NextSealGeneration(ctx context.Context, sandboxID string) (int64, error)
}

BlobStore persists sealed secret rows. Defined here so pkg/secrets never imports internal/store — the service layer adapts Store ↔ BlobStore.

type CallObserver added in v0.6.9

type CallObserver func(backend, op, class string, took time.Duration)

CallObserver is told about every call the router makes to a key-store backend: the backend, "wrap" or "unwrap", the outcome class (CallClass) and how long it took. Retries above the router count as separate calls.

type Cipher

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

Cipher seals and opens user-supplied secrets (cloud credentials for sandbox mounts) using AES-256-GCM. The seal format is `nonce(12) || ciphertext+tag`. The key never leaves this package; sealed bytes are what crosses other trust boundaries (DB, logs, error messages).

The AEAD sits behind an atomic pointer so a key-store revoke can drop it for every holder at once: the store and the service share one Cipher, and after Revoke every seal and open returns ErrKeyRevoked (plans/customer-key-custody.md §10).

func NewCipher

func NewCipher(keyB64, fallbackPath string) (*Cipher, error)

NewCipher constructs a Cipher from either an explicit key (base64-encoded, must decode to 32 bytes) or a fallback file path. If the explicit key is empty and the fallback path does not exist, a fresh 32-byte key is generated and persisted at the path with mode 0600.

func NewCipherFromKey added in v0.6.9

func NewCipherFromKey(key []byte) (*Cipher, error)

NewCipherFromKey builds a Cipher from a 32-byte key.

func NewCipherRing added in v0.6.9

func NewCipherRing(keys []RingKey) (*Cipher, error)

NewCipherRing builds a Cipher from a key ring; exactly one key is current.

func OpenServerKey added in v0.6.9

func OpenServerKey(ctx context.Context, in CustodyInputs, plaintextB64 string, w DataKeyWrapper, provider, keyRef string) (*Cipher, error)

OpenServerKey runs the boot decision and returns the Cipher. w is the external key store (nil for local). A key-store call gets at most unwrapTimeout; sandboxd.service restarts the daemon, so there is no retry loop here (§3 failure rule).

func (*Cipher) CurrentKeyID added in v0.6.9

func (c *Cipher) CurrentKeyID() uint32

CurrentKeyID is the id new seals use; 0 is the legacy key.

func (*Cipher) Decrypt

func (c *Cipher) Decrypt(sealed []byte) ([]byte, error)

Decrypt opens a sealed blob produced by Encrypt. Tampering, truncation, or using a different key all return an error.

func (*Cipher) DecryptWithAAD added in v0.2.1

func (c *Cipher) DecryptWithAAD(sealed []byte, aad []byte) ([]byte, error)

func (*Cipher) Digests added in v0.6.9

func (c *Cipher) Digests(purpose string, data []byte) ([]KeyedDigest, error)

Digests returns HMAC-SHA256 digests of data under a key derived from each server key the Cipher holds, the current key's first.

A keyed digest is what a stored or logged value derived from secrets needs (an idempotency fingerprint over a create's env, say): it is stable for as long as the server key is, the same on every node that shares the key, and useless for checking a guessed value offline without the key. The keys after the first are those of a rotation in progress, so a caller can still match what it stored under the previous key. purpose separates uses: the same data under two purposes gives unrelated digests.

func (*Cipher) Encrypt

func (c *Cipher) Encrypt(plain []byte) ([]byte, error)

Encrypt seals plaintext. Empty input is allowed and produces a non-empty sealed blob (the nonce alone authenticates that no plaintext was sealed).

func (*Cipher) EncryptWithAAD added in v0.2.1

func (c *Cipher) EncryptWithAAD(plain []byte, aad []byte) ([]byte, error)

func (*Cipher) HoldsKey added in v0.6.9

func (c *Cipher) HoldsKey(id uint32, check []byte) bool

HoldsKey reports whether the Cipher holds key id with this check, so a ring re-read can skip unwrapping it again.

func (*Cipher) KeyIDs added in v0.6.9

func (c *Cipher) KeyIDs() []uint32

KeyIDs lists the ids the Cipher can open.

func (*Cipher) OpenWithKeyID added in v0.6.9

func (c *Cipher) OpenWithKeyID(sealed []byte, aad []byte) ([]byte, uint32, error)

OpenWithKeyID opens sealed and says which key opened it. The key-id form is tried first; GCM authenticates the attempt, so a legacy blob that happens to start with the marker fails it cleanly and is then opened as legacy, under key id 0 (authenticated dual read, §13).

func (*Cipher) Reseal added in v0.6.9

func (c *Cipher) Reseal(sealed, aad []byte) (out []byte, from uint32, changed bool, err error)

Reseal returns sealed under the current key. A blob already on it comes back unchanged with changed false; any other is opened and sealed again with the same AAD. from is the key that opened it.

func (*Cipher) RestoreRing added in v0.6.9

func (c *Cipher) RestoreRing(keys []RingKey) error

RestoreRing takes the keys back after a revoke ends (eng D12). A key under an id this Cipher already knew must be the same key.

func (*Cipher) Revoke added in v0.6.9

func (c *Cipher) Revoke()

Revoke drops every key from memory: every later seal and open returns ErrKeyRevoked until Restore. Go cannot promise the bytes are zeroed, so the docs say "dropped", not "wiped".

func (*Cipher) Revoked added in v0.6.9

func (c *Cipher) Revoked() bool

Revoked reports whether Revoke dropped the keys.

func (*Cipher) Rotating added in v0.6.9

func (c *Cipher) Rotating() bool

Rotating reports whether the ring holds more than one key: a rotation is staged or a retired-to-be key is still readable, so rows may be on a key other than the current one.

func (*Cipher) SandboxTokenSigner added in v0.6.12

func (c *Cipher) SandboxTokenSigner() (uint32, ed25519.PrivateKey, error)

SandboxTokenSigner returns the key new sandbox tokens are signed with: the one derived from the current server key, with that key's id. A staged key (decrypt-only, not yet promoted) never signs, because a node that has not yet read the staged ring could not check what it signed.

func (*Cipher) SandboxTokenVerifyKey added in v0.6.12

func (c *Cipher) SandboxTokenVerifyKey(id uint32) (ed25519.PublicKey, bool)

SandboxTokenVerifyKey returns the public key for key id, from any key the ring still holds: the current one, a staged one, or the previous current key during a rotation. That is the rotation rule for tokens: a new key signs as soon as it is current, and the old key keeps verifying until the operator retires it. ok is false for an id the ring does not hold (never seen, or retired), and for a revoked Cipher.

func (*Cipher) SetRing added in v0.6.9

func (c *Cipher) SetRing(keys []RingKey) error

SetRing replaces the keys the Cipher holds: a staged key added, a key promoted to current, a retired key dropped. It never revives a revoked Cipher (RestoreRing does that).

type CustodyAction added in v0.6.9

type CustodyAction int

CustodyAction is what boot does to get the server key.

const (
	// ActionPlaintext is today's behavior: the env value, else the key file,
	// generated on first boot.
	ActionPlaintext CustodyAction = iota
	// ActionUnwrap reads and unwraps the wrapped file.
	ActionUnwrap
	// ActionGenerateWrapped makes a fresh key and writes only the wrapped
	// file: single node, first boot.
	ActionGenerateWrapped
	// ActionRefuse stops the boot; the reason says why and what to do.
	ActionRefuse
)

func DecideCustody added in v0.6.9

func DecideCustody(in CustodyInputs) (CustodyAction, string)

DecideCustody is the boot decision of §3 as a pure function.

type CustodyInputs added in v0.6.9

type CustodyInputs struct {
	Custody             string
	PlaintextEnvSet     bool
	PlaintextFileExists bool
	WrappedFileExists   bool
	ClusterMode         bool
	StateDBExists       bool
	PlaintextPath       string
	WrappedPath         string
	// RingFileExists: custody=file's ring file exists at RingPath (§13).
	RingFileExists bool
	RingPath       string
}

CustodyInputs is everything the boot decision reads.

type DataKeyWrapper added in v0.6.1

type DataKeyWrapper interface {
	Wrap(ctx context.Context, dek []byte, encCtx map[string]string) (wrapped []byte, err error)
	Unwrap(ctx context.Context, wrapped []byte, encCtx map[string]string) (dek []byte, err error)
}

DataKeyWrapper wraps and unwraps per-secret data encryption keys (DEKs). Local Cipher uses AES-GCM with AAD; AWS KMS / FakeKMS implement the same seam so KMSProvider never talks to a concrete backend.

encCtx is optional additional authenticated context (AWS KMS EncryptionContext / FakeKMS AAD). Boot canaries pass nil; production envelope wraps bind it.

func NewLimitedWrapper added in v0.6.9

func NewLimitedWrapper(inner DataKeyWrapper, maxInFlight int, observe LimiterObserver) DataKeyWrapper

NewLimitedWrapper wraps inner with a foreground cap of maxInFlight (one of which is kept for creates when maxInFlight > 1) and a separate background budget. observe may be nil.

func NewOpenWrapper added in v0.6.9

func NewOpenWrapper(ctx context.Context, opts ProviderOptions) (DataKeyWrapper, error)

NewOpenWrapper builds the key-store client of a node that still seals with the server key but already holds a key store's settings: step 1 of the two-step switch (§12, eng D8). It opens the rows that switched nodes seal and never seals; it is nil when the node holds no key-store settings.

func NewWrapper added in v0.6.9

func NewWrapper(ctx context.Context, opts ProviderOptions) (DataKeyWrapper, error)

NewWrapper builds the key-store client for an external provider from config alone, with no store, so the daemon can build it before the server key is unwrapped. It returns nil for local. The result seals with the configured provider, opens each row with whichever backend its tag names among those the node has settings for (so a provider switch is two steps, §12), and limits in-flight calls.

type EnvelopeBindingFields added in v0.6.1

type EnvelopeBindingFields struct {
	Version       int // wire envelope version
	SandboxID     string
	IncarnationID string
	Ref           string
	VersionField  int // handle version (RefVersion)
	Generation    int64
}

EnvelopeBindingFields is the authenticated identity carried on a sealed envelope.

func EnvelopeBinding added in v0.6.1

func EnvelopeBinding(sealed []byte) (EnvelopeBindingFields, error)

EnvelopeBinding returns full wire binding metadata without decrypting.

type FakeKMS added in v0.6.1

type FakeKMS struct {

	// Injected failure modes (checked under mu on each call).
	Throttle    bool
	Deny        bool
	Unavailable bool
	// contains filtered or unexported fields
}

FakeKMS is an offline DataKeyWrapper for contract tests and local development. It AES-GCM-wraps DEKs with an in-memory test key and can inject throttle / deny / unavailable failures.

func NewFakeKMS added in v0.6.1

func NewFakeKMS() (*FakeKMS, error)

NewFakeKMS returns a FakeKMS with a random 32-byte wrapping key.

func (*FakeKMS) Unwrap added in v0.6.1

func (f *FakeKMS) Unwrap(ctx context.Context, wrapped []byte, encCtx map[string]string) ([]byte, error)

Unwrap implements DataKeyWrapper.

func (*FakeKMS) Wrap added in v0.6.1

func (f *FakeKMS) Wrap(ctx context.Context, dek []byte, encCtx map[string]string) ([]byte, error)

Wrap implements DataKeyWrapper.

type Handle added in v0.6.1

type Handle struct {
	Ref            string
	Version        int
	SealGeneration int64 // set by Put so callers can journal put-outbox without a reload
}

Handle is a log-safe reference to sealed secrets. Safe to replicate through Raft; it never carries ciphertext or plaintext.

type KMSProvider added in v0.6.1

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

KMSProvider seals secrets with a per-row DEK whose wrap material lives in KMS (or FakeKMS). Ciphertext still lands in BlobStore — KMS never stores the payload. Open skips recipient binding: any node that holds the row and can Unwrap via IAM may decrypt (removes WALL 2). Fan-out is still required for WALL 1 (bytes must reach the failover node).

v4 envelopes bind sandbox identity into payload AAD and KMS EncryptionContext so ciphertext cannot be relabeled across sandboxes.

func NewKMSProvider added in v0.6.1

func NewKMSProvider(wrapper DataKeyWrapper, store BlobStore) *KMSProvider

NewKMSProvider returns a Provider backed by wrapper + store.

func (*KMSProvider) Delete added in v0.6.1

func (p *KMSProvider) Delete(ctx context.Context, sandboxID string) error

Delete removes all sealed rows for sandboxID.

func (*KMSProvider) Open added in v0.6.1

func (p *KMSProvider) Open(ctx context.Context, sandboxID string, h Handle, nodeID string) (Secrets, error)

Open resolves h to plaintext. sandboxID is verified against the v4 binding. nodeID is checked against the recipient set only for a local row left from before a switch to the key store; for key-store rows KMS IAM (or the Vault policy, or the HSM login) is the authorization boundary.

func (*KMSProvider) Put added in v0.6.1

func (p *KMSProvider) Put(ctx context.Context, sandboxID string, s Secrets, recipients []string) (Handle, error)

Put seals s for recipients (recorded for fan-out targeting) and stores the envelope. Empty secrets return a zero Handle without writing a row.

type KeyRingFile added in v0.6.9

type KeyRingFile struct {
	Format int         `json:"format"`
	Ring   []RingEntry `json:"ring"`
}

KeyRingFile is custody=file's ring (SB_CREDENTIAL_KEY_RING_PATH, mode 0600). Once it exists it is the whole server key: the legacy key file and SB_CREDENTIAL_ENCRYPTION_KEY are only checked against it.

func ReadKeyRingFile added in v0.6.9

func ReadKeyRingFile(path string) (KeyRingFile, error)

ReadKeyRingFile reads and validates custody=file's ring file.

func UnwrapRingToFile added in v0.6.9

func UnwrapRingToFile(ctx context.Context, w DataKeyWrapper, f WrappedKeyFile) (KeyRingFile, error)

UnwrapRingToFile is the rollback of a rotated wrapped key to custody=file: the plaintext ring file.

func (KeyRingFile) Entry added in v0.6.9

func (f KeyRingFile) Entry(id uint32) (RingEntry, bool)

Entry returns the ring's entry for id.

func (KeyRingFile) RingKeys added in v0.6.9

func (f KeyRingFile) RingKeys() []RingKey

RingKeys is the ring file's keys that are not retired.

type KeyVersioner added in v0.6.9

type KeyVersioner interface {
	CurrentKeyVersion(ctx context.Context) (string, error)
}

KeyVersioner is a key store that names its current key in the form WrappedKeyVersion uses. AWS KMS does not implement it.

type KeyedDigest added in v0.6.9

type KeyedDigest struct {
	KeyID uint32
	Sum   []byte
}

KeyedDigest is a keyed digest of some data under one ring key.

func (KeyedDigest) String added in v0.6.10

func (d KeyedDigest) String() string

String is the digest as it is stored or recorded: "hmac:<key id>:<hex>". The key id says which server key made it, so a reader can tell digests of two key epochs apart rather than take them for two different inputs.

type LimiterObserver added in v0.6.9

type LimiterObserver func(budget string, wait time.Duration)

LimiterObserver is told how long each call waited for a key-store slot.

type LocalProvider added in v0.6.1

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

LocalProvider seals secrets with a node-local Cipher and persists the recipient-bound envelope via BlobStore. This preserves today's cluster_secrets SQLite behavior behind the Provider interface.

func NewLocalProvider added in v0.6.1

func NewLocalProvider(cipher *Cipher, store BlobStore) *LocalProvider

NewLocalProvider returns a Provider backed by cipher + store.

func (*LocalProvider) Delete added in v0.6.1

func (p *LocalProvider) Delete(ctx context.Context, sandboxID string) error

Delete removes all sealed rows for sandboxID.

func (*LocalProvider) Open added in v0.6.1

func (p *LocalProvider) Open(ctx context.Context, sandboxID string, h Handle, nodeID string) (Secrets, error)

Open resolves h to plaintext for nodeID. sandboxID is verified against the v4 envelope binding so ciphertext cannot be relabeled across sandboxes.

func (*LocalProvider) Put added in v0.6.1

func (p *LocalProvider) Put(ctx context.Context, sandboxID string, s Secrets, recipients []string) (Handle, error)

Put seals s for recipients and stores the envelope. Empty secrets return a zero Handle without writing a row (matches today's PutClusterSecrets).

type ParsedRef added in v0.6.1

type ParsedRef struct {
	SandboxID     string
	IncarnationID string
	Version       int
}

ParsedRef is the decomposed cluster-secret handle.

func ParseRef added in v0.6.1

func ParseRef(ref string) (ParsedRef, error)

ParseRef accepts only cluster-secret://sandbox/{id}/i/{inc}/v{N} handles.

type Provider added in v0.6.1

type Provider interface {
	Put(ctx context.Context, sandboxID string, s Secrets, recipients []string) (Handle, error)
	Open(ctx context.Context, sandboxID string, h Handle, nodeID string) (Secrets, error)
	Delete(ctx context.Context, sandboxID string) error
}

Provider resolves ref → plaintext. Backends differ in how a node reaches plaintext (local row, peer fetch, KMS), not in the wire handle shape.

type ProviderOptions added in v0.6.1

type ProviderOptions struct {
	// Name is local | awskms | vault | pkcs11 (default local).
	Name string
	// AWSKMSKeyID is required when Name=awskms. Set with another provider, it
	// lets the node still open AWS KMS rows during a switch.
	AWSKMSKeyID string
	// Vault is required when Name=vault. Set with another provider, it lets
	// the node already open vault rows during a switch.
	Vault VaultOptions
	// PKCS11 is the running PKCS#11 helper client, required when
	// Name=pkcs11. pkg/daemon starts it (the vendor library lives in its own
	// process, eng D5), so this package never imports pkg/secrets/pkcs11.
	// Set with another provider, it lets the node open p11 rows.
	PKCS11 DataKeyWrapper
	// Cipher is required for local.
	Cipher *Cipher
	// Store persists sealed blobs for every provider.
	Store BlobStore
	// Wrapper overrides the sealing backend (tests inject FakeKMS). NewWrapper
	// still routes and limits it.
	Wrapper DataKeyWrapper
	// Prebuilt is a wrapper NewWrapper already built (routed and limited),
	// reused as-is so one key-store client serves boot, the provider and the
	// background loop.
	Prebuilt DataKeyWrapper
	// MaxInFlight is the foreground cap (SB_SECRET_PROVIDER_MAX_INFLIGHT);
	// 0 means DefaultMaxInFlight.
	MaxInFlight int
	// Observer is told how long calls waited for a key-store slot; may be nil.
	Observer LimiterObserver
	// Calls is told about every key-store call (backend, op, class,
	// latency); may be nil.
	Calls CallObserver
}

ProviderOptions selects and constructs a secrets.Provider.

type RingEntry added in v0.6.9

type RingEntry struct {
	ID      uint32 `json:"id"`
	State   string `json:"state"`
	Wrapped []byte `json:"wrapped,omitempty"`
	Key     []byte `json:"key,omitempty"`
	Check   []byte `json:"check"`
}

RingEntry is one key of the ring on disk. With custody=wrapped Wrapped holds the key wrapped by the key store; with custody=file Key holds it in plaintext. A retired entry keeps only its id, state and check: the record of what was retired outlives the key.

func LegacyRingEntry added in v0.6.9

func LegacyRingEntry(key []byte) RingEntry

LegacyRingEntry is a plaintext key as ring key 0, the current key: the ring custody=file starts from when it first rotates.

func NewRingEntry added in v0.6.9

func NewRingEntry(ctx context.Context, id uint32, w DataKeyWrapper) (RingEntry, error)

NewRingEntry makes a fresh key for StageRingKey. wrap seals it for custody=wrapped; nil keeps it in plaintext for custody=file.

func PromoteRingKey added in v0.6.9

func PromoteRingKey(entries []RingEntry) (out []RingEntry, from, to uint32, err error)

PromoteRingKey makes the staged key (the decrypt-only key newer than the current one) current; the old current key becomes decrypt-only until it is retired. It returns the old and new current ids.

func RetireRingKey added in v0.6.9

func RetireRingKey(entries []RingEntry, id uint32) ([]RingEntry, error)

RetireRingKey retires a decrypt-only key and drops its bytes. Retiring a staged key that was never promoted cancels the rotation.

func StageRingKey added in v0.6.9

func StageRingKey(entries []RingEntry, staged RingEntry) ([]RingEntry, error)

StageRingKey adds staged (state decrypt) to the ring.

type RingKey added in v0.6.9

type RingKey struct {
	ID      uint32
	Key     []byte
	Current bool
}

RingKey is one key of a server-key ring, in memory. A nil Key on SetRing keeps the key the Cipher already holds under ID, so a re-read of the ring unwraps only the keys that are new to this node.

func UnwrapRing added in v0.6.9

func UnwrapRing(ctx context.Context, w DataKeyWrapper, f WrappedKeyFile, held func(id uint32, check []byte) bool) ([]RingKey, error)

UnwrapRing unwraps every key of f that is not retired. held reports a key the Cipher already holds (same id and check): it comes back with a nil Key, which SetRing keeps, so a re-read makes no key-store call for it.

type Router added in v0.6.9

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

Router seals with the configured provider and opens each wrapped key with whichever configured backend its tag names, even when that is not the sealing provider. That is what makes a provider switch two-step with no failover window: every node gets the new backend's settings first, then the sealing provider flips (plans/customer-key-custody.md §12, eng D8). An untagged key opens with AWS KMS whenever AWS KMS is configured, whatever the sealing provider (eng D22); local rows never reach the router, because the server key opens them first.

func NewRouter added in v0.6.9

func NewRouter(sealName string, seal DataKeyWrapper, openers map[string]DataKeyWrapper) *Router

NewRouter seals with seal (named sealName) and opens with openers, keyed by provider name. The sealing wrapper is added to openers under sealName.

func (*Router) CurrentKeyVersion added in v0.6.9

func (r *Router) CurrentKeyVersion(ctx context.Context) (string, error)

CurrentKeyVersion implements KeyVersioner for the router: the sealing provider's current key.

func (*Router) Unwrap added in v0.6.9

func (r *Router) Unwrap(ctx context.Context, wrapped []byte, encCtx map[string]string) ([]byte, error)

Unwrap implements DataKeyWrapper with the backend the wrapped key's tag names.

func (*Router) Wrap added in v0.6.9

func (r *Router) Wrap(ctx context.Context, dek []byte, encCtx map[string]string) ([]byte, error)

Wrap implements DataKeyWrapper with the sealing provider.

type RowState added in v0.6.9

type RowState int

RowState is a sealed row's place relative to the sealing provider.

const (
	// RowCurrent needs nothing.
	RowCurrent RowState = iota
	// RowStale is wrapped under an older version or label of the sealing
	// provider, or is a local row on a node that seals with a key store
	// (§12): the sweep rewraps it.
	RowStale
	// RowForeign is wrapped by a backend the node does not seal with (an
	// external to external switch, which v1 does not support). Left alone.
	RowForeign
)

func ClassifyRow added in v0.6.9

func ClassifyRow(sealed []byte, local *Cipher, provider, current string) (RowState, error)

ClassifyRow places sealed relative to the sealing provider's current key version (current is "" for AWS KMS). local is the server key: an untagged row it opens is a local row.

type SealBinding added in v0.6.1

type SealBinding struct {
	SandboxID     string
	IncarnationID string
	Ref           string
	Version       int
	Generation    int64
}

SealBinding authenticates ciphertext to a specific sandbox handle.

type SecretBlob added in v0.6.1

type SecretBlob struct {
	Ref            string
	SandboxID      string
	IncarnationID  string
	Version        int
	Recipients     []string
	SealedPayload  []byte
	SealGeneration int64
	// OutboxRecipients, when non-nil (including empty), is journaled in the
	// same SQLite transaction as the sealed row. Nil means "do not touch
	// put-outbox beyond the default clear-on-put". Empty slice clears pending
	// peers after a fully-local seal.
	OutboxRecipients *[]string
	// RetiredRecipients, when non-nil, is staged in the delete outbox in the
	// same transaction as the sealed generation. The staged row is not eligible
	// for peer deletion until the service confirms Raft promotion.
	RetiredRecipients *[]string
}

SecretBlob is one sealed cluster-secret row addressed by ref.

type Secrets added in v0.6.1

type Secrets struct {
	Registry   *models.RegistryAuth         `json:"registry,omitempty"`
	MountCreds map[string]map[string]string `json:"mount_creds,omitempty"`
	// Env carries the sealed sandbox environment.
	Env map[string]string `json:"env,omitempty"`
}

Secrets is the cleartext credential bag (NOT the CreateSandboxRequest). MountCreds is keyed by MountSpec.Target.

func OpenEnvelopeBound added in v0.6.1

func OpenEnvelopeBound(c *Cipher, sealed []byte, nodeID string, expect SealBinding) (Secrets, error)

OpenEnvelopeBound opens a sealed envelope and verifies its sandbox binding.

func (Secrets) IsEmpty added in v0.6.1

func (s Secrets) IsEmpty() bool

IsEmpty reports whether Secrets carries nothing that LocalProvider should persist. Registry password, mount credentials, or Env count as content.

type UpstreamCredentials added in v0.2.3

type UpstreamCredentials struct {
	UpstreamHost string `json:"upstreamHost"`
	Username     string `json:"username"`
	Password     string `json:"password"`
	Scope        string `json:"scope"`
}

UpstreamCredentials is the plaintext shape AOCR's auth service expects inside a wrapped blob. Field names are JSON-serialized as-is; they must match `auth/src/upstreamAuth/wrap.ts` exactly or the round-trip breaks.

`Scope` pins the wrap to a specific Distribution token-server scope string (e.g. `repository:aocr/ghcr/org/repo:pull`). AOCR cross-checks the scope inside the blob against the scope on the `/v2/token` request, so a leaked blob cannot be reused for a different repo.

type UpstreamWrapKey added in v0.2.3

type UpstreamWrapKey struct {
	ID    string
	Bytes []byte
}

UpstreamWrapKey is one key in the rotation ring. `ID` is a short, human- readable identifier surfaced in metrics and logs; the cryptographic material is `Bytes`. The wire format on AOCR's side and ours must agree exactly: 32-byte AES-256 keys, base64 (standard alphabet), optionally prefixed with `<id>:`.

type UpstreamWrapKeyRing added in v0.2.3

type UpstreamWrapKeyRing struct {
	Keys []UpstreamWrapKey
}

UpstreamWrapKeyRing holds the ordered list of wrap keys. The first entry is the *current* key used for wrapping new tokens; all entries are kept available for unwrap (here only as a future-proofing detail — sandboxd only wraps, never unwraps — but matching AOCR's structure keeps the two sides interchangeable).

Rotation policy: prepend a new key (`new:<b64>,old:<b64>`) on every node, wait one full token lifetime so any in-flight wrapped credentials have expired on the AOCR side, then drop the old entry. See the `rotate-upstream-wrap-key.yml` playbook for the operator flow.

func LoadUpstreamWrapKeyRing added in v0.2.3

func LoadUpstreamWrapKeyRing(path string) (*UpstreamWrapKeyRing, error)

LoadUpstreamWrapKeyRing reads the wrap key file at `path` and parses it into a key ring. The file must be mode 0400 (owner-readable only); any looser mode is refused at load time to prevent operator-mistake leaks via world-readable home directories or `cp -p` from a wide-mode source.

The file body is a comma-separated list of `<b64>` or `<id>:<b64>` entries — same format as the AOCR side's `UPSTREAM_AUTH_WRAP_KEYS` env var. Whitespace around commas is tolerated. Malformed entries are silently dropped (matching AOCR behavior) so a partial-bad rotation does not break the node entirely, but the final ring must have at least one valid key or LoadUpstreamWrapKeyRing returns an error.

If the file does not exist, LoadUpstreamWrapKeyRing returns `os.ErrNotExist` wrapped so callers can fall through to "wrap keys not configured" without treating it as fatal — the daemon may still run for public images.

func ParseUpstreamWrapKeyRing added in v0.2.3

func ParseUpstreamWrapKeyRing(raw string) *UpstreamWrapKeyRing

ParseUpstreamWrapKeyRing parses the comma-separated wrap-key format. Public so callers (tests, config validators) can validate a string without writing it to disk.

func (*UpstreamWrapKeyRing) Current added in v0.2.3

func (r *UpstreamWrapKeyRing) Current() (UpstreamWrapKey, bool)

Current returns the active wrap key. Callers should not cache the returned key across reloads.

type Vault added in v0.6.9

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

Vault wraps DEKs with Vault Transit or OpenBao encrypt/decrypt. Its ciphertext starts with "vault:v<N>:", which is also the provider tag the Router reads.

func NewVault added in v0.6.9

func NewVault(opts VaultOptions) (*Vault, error)

NewVault validates opts and builds the client. It makes no call; the token policy check runs at boot (NewWrapper) and again before the first encrypt.

func (*Vault) CurrentKeyVersion added in v0.6.9

func (v *Vault) CurrentKeyVersion(ctx context.Context) (string, error)

CurrentKeyVersion implements KeyVersioner: the Transit key's latest version, which new wraps use and the rewrap sweep moves rows to (§11). Needs read on <mount>/keys/<key>.

func (*Vault) Unwrap added in v0.6.9

func (v *Vault) Unwrap(ctx context.Context, wrapped []byte, encCtx map[string]string) ([]byte, error)

Unwrap implements DataKeyWrapper with Transit decrypt.

func (*Vault) Wrap added in v0.6.9

func (v *Vault) Wrap(ctx context.Context, dek []byte, encCtx map[string]string) ([]byte, error)

Wrap implements DataKeyWrapper with Transit encrypt. The encryption context is bound as associated_data; Phase 0 confirmed decrypt rejects a wrong one on Vault and OpenBao.

type VaultOptions added in v0.6.9

type VaultOptions struct {
	Addr      string // SB_SECRET_VAULT_ADDR
	Mount     string // SB_SECRET_VAULT_TRANSIT_MOUNT; "" means "transit"
	KeyName   string // SB_SECRET_VAULT_KEY_NAME
	TokenFile string // SB_SECRET_VAULT_TOKEN_FILE
	Namespace string // SB_SECRET_VAULT_NAMESPACE (X-Vault-Namespace)
	CACert    string // SB_SECRET_VAULT_CACERT, a PEM bundle path
	// NodeID names this node in the correlation id of background calls.
	NodeID string
}

VaultOptions configures the vault provider: Vault Transit or OpenBao (plans/customer-key-custody.md §1). sandboxd has no Vault login code (eng D10): Vault Agent either writes a token to TokenFile, or, with no token file, Addr points at Agent's local API proxy, which adds the token itself so sandboxd holds no Vault credential at all.

func (VaultOptions) Configured added in v0.6.9

func (o VaultOptions) Configured() bool

Configured reports whether any Vault setting is present, which makes the node able to open vault-tagged rows even when it seals with another provider.

type WrappedKeyFile added in v0.6.9

type WrappedKeyFile struct {
	Format   int    `json:"format"`
	Provider string `json:"provider"`
	KeyRef   string `json:"key_ref,omitempty"`
	Wrapped  []byte `json:"wrapped"`
	// Check is HMAC-SHA256(serverKey, serverKeyCheckLabel)[:16]: a wrong key
	// is caught before the store opens instead of failing every decrypt.
	Check []byte `json:"check"`
	// MigratedFromPlaintext marks a key that existed in plaintext before it
	// was wrapped. Old backups and bundles still hold that plaintext, so
	// `sandboxd key status` says so until `sandboxd key ack-migration`
	// (eng D24).
	MigratedFromPlaintext bool `json:"migrated_from_plaintext,omitempty"`
	// Ring is the server-key ring of a format 2 file (§13); Wrapped and
	// Check above are then the current key's.
	Ring []RingEntry `json:"ring,omitempty"`
}

WrappedKeyFile is the wrapped server-key file, mode 0600.

func ReadWrappedKeyFile added in v0.6.9

func ReadWrappedKeyFile(path string) (WrappedKeyFile, error)

ReadWrappedKeyFile reads and validates the wrapped server-key file. A file others can read is refused like every secret file (eng D14), though it is ciphertext: the rule stays one rule.

func RewrapRing added in v0.6.9

RewrapRing wraps every live key of f again under w's newest key: the same keys, ids, states and checks, new wrapped bytes.

func WrapRing added in v0.6.9

func WrapRing(ctx context.Context, w DataKeyWrapper, ring KeyRingFile, provider, keyRef string) (WrappedKeyFile, error)

WrapRing wraps custody=file's ring with w: the wrapped file a migration to custody=wrapped writes when the plaintext key was already rotated.

func WrapServerKey added in v0.6.9

func WrapServerKey(ctx context.Context, w DataKeyWrapper, key []byte, provider, keyRef string) (WrappedKeyFile, error)

WrapServerKey wraps key with w under the server-key wrap context.

func (WrappedKeyFile) Entries added in v0.6.9

func (f WrappedKeyFile) Entries() []RingEntry

Entries is the file's ring; a format 1 file is the legacy key alone.

func (WrappedKeyFile) KeyVersion added in v0.6.9

func (f WrappedKeyFile) KeyVersion() string

KeyVersion names what the file is wrapped under, for the custody report: "vault:v3", "p11:<label>", or "" when the backend does not say.

func (*WrappedKeyFile) SetEntries added in v0.6.9

func (f *WrappedKeyFile) SetEntries(entries []RingEntry) error

SetEntries replaces the file's ring. The top-level wrapped key and check stay the current key's, so the re-check and every single-key reader keep working on a ring file.

func (WrappedKeyFile) StaleRingKeys added in v0.6.9

func (f WrappedKeyFile) StaleRingKeys(current string) int

StaleRingKeys counts f's live keys wrapped under a key-store version other than current (the rewrap sweep's view of the server-key file).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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