secrets

package
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

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"
)

Provider name constants for SB_SECRET_PROVIDER.

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.

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")
)

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

Functions

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 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 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 KeyAADBound added in v0.6.1

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

KeyAADBound authenticates the wrapped data-key for v4 envelopes.

func NewProvider added in v0.6.1

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

NewProvider builds the configured Provider. Vault is a known value that returns a clear not-implemented error (no silent fallback to local). For awskms, also returns the DataKeyWrapper so callers can run CanaryWrapUnwrap.

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 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 RetiredRecipientsFromContext added in v0.6.1

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

RetiredRecipientsFromContext returns the optional reseal-retirement journal.

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 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.

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 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).

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 (*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) 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)

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.

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 accepted for the Provider contract (audit) but is not checked against the envelope recipient set — KMS IAM 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 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 (default local).
	Name string
	// AWSKMSKeyID is required when Name=awskms.
	AWSKMSKeyID string
	// Cipher is required for local.
	Cipher *Cipher
	// Store persists sealed blobs for every provider.
	Store BlobStore
	// Wrapper overrides the awskms backend (tests inject FakeKMS).
	Wrapper DataKeyWrapper
}

ProviderOptions selects and constructs a secrets.Provider.

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.

Jump to

Keyboard shortcuts

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