secrets

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

README

secrets

github.com/docker/secrets-engine/secrets holds the core types of the Secrets Engine: secret IDs and patterns, resolved envelopes, and the Secret and Store interfaces.

It depends only on the standard library, so clients, plugins and store backends can import it without pulling in the engine runtime or the keychain bindings. Its API is stable and follows semantic versioning from v1.0.0.

go get github.com/docker/secrets-engine/secrets

Identifiers and patterns

An ID contains a secret identifier. Valid secret identifiers must match the format ^[A-Za-z0-9._:-]+(?:/[A-Za-z0-9._:-]+)*$:

  • Components separated by /
  • Each component is non-empty
  • Only characters A-Z, a-z, 0-9, ., _, - or :
  • No leading, trailing, or double slashes

For storage, we don't really differentiate much about the ID format but by convention we do simple, slash-separated management, providing a groupable access control system for management across plugins.

A Pattern matches secret IDs. It follows the ID validation rules, except that * matches one component and ** matches zero or more.

id := secrets.MustParseID("docker/auth/hub/joe")
pattern := secrets.MustParsePattern("docker/auth/**")
pattern.Match(id) // true

if _, err := secrets.ParsePattern(userInput); errors.Is(err, secrets.ErrInvalidPattern) {
	// reject the input
}

Implementing a secret

Store backends such as store/keychain and store/posixage persist any type that implements secrets.Secret, and take a secrets.Factory that creates an empty one per ID:

type token struct {
	value    []byte
	metadata map[string]string
}

func (t *token) Marshal() ([]byte, error) { return t.value, nil }

// Copy the data: backends zero the buffer after Unmarshal returns.
func (t *token) Unmarshal(data []byte) error {
	t.value = bytes.Clone(data)
	return nil
}

func (t *token) Metadata() map[string]string { return t.metadata }

func (t *token) SetMetadata(m map[string]string) error {
	t.metadata = m
	return nil
}

var factory secrets.Factory[*token] = func(context.Context, secrets.ID) *token {
	return &token{}
}

Migrating from x/secrets and store

github.com/docker/secrets-engine/x/secrets and the type aliases in the root github.com/docker/secrets-engine/store package are deprecated aliases of this module. They carry //go:fix inline directives, so go fix ./... rewrites callers to import secrets directly. x/secrets will be removed in a future release of x.

x/secrets.Resolver, x/secrets.Authorizer and x/secrets.AuthorizeResponse are the exception: go fix leaves them alone, and their replacements live in github.com/docker/secrets-engine/client/api/resolver.

Deprecated Replacement
x/secrets.* secrets.*
x/secrets.Resolver, x/secrets.Authorizer, x/secrets.AuthorizeResponse client/api/resolver.Resolver, client/api/resolver.Authorizer, client/api/resolver.AuthorizeResponse
store.ID, store.Pattern, store.Secret, store.Store secrets.ID, secrets.Pattern, secrets.Secret, secrets.Store
store.Factory[T] secrets.Factory[T]
store.ParseID, store.MustParseID secrets.ParseID, secrets.MustParseID
store.ParsePattern, store.MustParsePattern secrets.ParsePattern, secrets.MustParsePattern
store.ErrCredentialNotFound secrets.ErrNotFound
store.ErrEmptySecret secrets.ErrEmptySecret

Documentation

Overview

Package secrets defines the core types shared across the Secrets Engine: secret identifiers and patterns, resolved secret envelopes, and the interfaces implemented by secret stores.

Identifiers and patterns

An ID contains a secret identifier. Valid secret identifiers must match the format ^[A-Za-z0-9._:-]+(?:/[A-Za-z0-9._:-]+)*$:

  • Components separated by '/'
  • Each component is non-empty
  • Only characters A-Z, a-z, 0-9, '.', '_', '-' or ':'
  • No leading, trailing, or double slashes

For storage, we don't really differentiate much about the ID format but by convention we do simple, slash-separated management, providing a groupable access control system for management across plugins.

A Pattern matches secret IDs. It follows the ID validation rules, except that '*' matches one component and '**' matches zero or more.

id := secrets.MustParseID("docker/auth/hub/joe")
pattern := secrets.MustParsePattern("docker/auth/**")
pattern.Match(id) // true

Resolving secrets

A github.com/docker/secrets-engine/client/api/resolver.Resolver returns the Envelope of every secret that matches a pattern. A github.com/docker/secrets-engine/client/api/resolver.Authorizer decides whether access to a set of patterns is allowed.

Storing secrets

A Store persists values implementing Secret, keyed by ID. Store backends take a Factory that creates an empty Secret for each ID they read, so callers decide how their secret values are encoded.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when no secret exists for the requested ID or
	// pattern.
	ErrNotFound = errors.New("secret not found")
	// ErrAccessDenied is returned when the caller is not allowed to access
	// the requested secrets.
	ErrAccessDenied = errors.New("access denied") // nuh, uh, uh!
	// ErrEmptySecret is returned when a secret with an empty value is saved.
	ErrEmptySecret = errors.New("secret value must not be empty")
)
View Source
var ErrInvalidPattern = errors.New("invalid pattern")

ErrInvalidPattern is returned by ParsePattern when a string is not a valid Pattern.

Functions

This section is empty.

Types

type Envelope

type Envelope struct {
	// ID identifies the secret.
	ID ID `json:"-"`
	// Value is the plaintext secret value.
	Value []byte `json:"-"`
	// Metadata holds non-sensitive key-value data about the secret.
	Metadata map[string]string `json:"-"`
	// Provider names the provider that resolved the secret.
	Provider string `json:"-"`
	// Version is the version of the payload format in Value, set by the
	// provider. It is independent of the provider's own release version.
	Version string `json:"-"`
	// CreatedAt is when the secret was created.
	CreatedAt time.Time `json:"-"`
	// ResolvedAt is when the secret was resolved.
	ResolvedAt time.Time `json:"-"`
	// ExpiresAt is when the secret stops being valid.
	ExpiresAt time.Time `json:"-"`
}

Envelope is a resolved secret together with information about where it came from and how long it is valid.

An Envelope carries plaintext secret material and cannot be encoded with encoding/json; see Envelope.MarshalJSON.

func (Envelope) MarshalJSON

func (e Envelope) MarshalJSON() ([]byte, error)

MarshalJSON always panics, so that an Envelope and its plaintext value are never written out by encoding/json by accident.

type ErrInvalidID

type ErrInvalidID struct {
	// ID is the rejected input.
	ID string
}

ErrInvalidID is returned by ParseID when a string is not a valid ID.

func (ErrInvalidID) Error

func (e ErrInvalidID) Error() string

Error describes the rejected input and the format an ID must match.

type Factory

type Factory[T Secret] func(context.Context, ID) T

Factory returns a new, empty Secret for the given ID. Store backends call it for every secret they read, then fill it in with Secret.SetMetadata and, when the value is read too, Secret.Unmarshal.

type ID

type ID interface {
	// String formats the [ID] as a string
	String() string
	// Match the [ID] against a [Pattern]
	// It checks if a given identifier matches the pattern.
	// - "*" matches a single component
	// - "**" matches zero or more components
	// - "/" is the separator
	Match(pattern Pattern) bool
}

ID contains a secret identifier. Valid secret identifiers must match the format ^[A-Za-z0-9._:-]+(?:/[A-Za-z0-9._:-]+)*$.

For storage, we don't really differentiate much about the ID format but by convention we do simple, slash-separated management, providing a groupable access control system for management across plugins.

func MustParseID

func MustParseID(s string) ID

MustParseID parses a string into a ID and behaves similar to ParseID, however, it panics when the id is invalid

func ParseID

func ParseID(s string) (ID, error)

ParseID creates a new ID from a string If a validation error occurs, it returns nil and the error. Rules: - Components separated by '/' - Each component is non-empty - Only characters A-Z, a-z, 0-9, '.', '_', '-' or ':' - No leading, trailing, or double slashes

type Pattern

type Pattern interface {
	// Match reports whether the pattern matches id.
	// Complexity: O(n*m^k), where id has n components and the pattern has
	// m components and k occurrences of '**'.
	Match(id ID) bool
	// Contains reports whether every ID that [other] matches can also be
	// matched by the pattern: the set of IDs [other] matches is contained
	// in the set the pattern matches, i.e., matches(other) ⊆ matches(p).
	//
	// Examples:
	//   - docker/** contains docker/*/mcp/*: '**' is more general than
	//     '*/mcp/*'.
	//   - docker/proj1/** does not contain docker/*/mcp/*: docker/*/mcp/*
	//     matches docker/proj2/mcp/x, but docker/proj1/** does not.
	//
	// Complexity: O(n*m)
	Contains(other Pattern) bool
	// Overlaps reports whether the pattern and [other] match at least one
	// ID in common, i.e., matches(p) ∩ matches(other) ≠ ∅.
	//
	// Examples:
	//   - docker/*/mcp/* and docker/proj1/** overlap: both match e.g. docker/proj1/mcp/x.
	//   - bar/** and foo/** do not overlap: an ID cannot begin with both bar and foo.
	//
	// Complexity: O(n*m)
	Overlaps(other Pattern) bool
	// String returns the pattern text.
	String() string

	ExpandID(other ID) (ID, error)
	ExpandPattern(other Pattern) (Pattern, error)
}

Pattern matches secret IDs. It follows the ID validation rules, except that '*' matches one component and '**' matches zero or more. Below, matches(p) denotes the set of IDs a pattern p matches.

func Minimize

func Minimize(patterns []Pattern) []Pattern

Minimize removes each pattern that another contains (see Pattern.Contains); when patterns match the same IDs, only the first stays. The result preserves input order.

Examples:

[** a/*]        ->  [**]
[**/* */** **]  ->  [**/*]
[a/** **/a]     ->  [a/** **/a]

Complexity: O(n²·L²) for n patterns of at most L components each.

func MustParsePattern

func MustParsePattern(s string) Pattern

MustParsePattern is like ParsePattern but panics on an invalid pattern.

func ParsePattern

func ParsePattern(s string) (Pattern, error)

ParsePattern parses s into a Pattern: non-empty '/'-separated components of A-Z, a-z, 0-9, '.', '-', '_', ':', where a component may instead be '*' or '**'. It returns ErrInvalidPattern for anything else.

type Secret

type Secret interface {
	// Marshal the secret into a slice of bytes
	Marshal() ([]byte, error)
	// Unmarshal the secret from a slice of bytes into its structured format.
	// Implementations must copy any bytes they retain: store backends zero
	// the source buffer after Unmarshal returns to avoid leaking plaintext.
	Unmarshal(data []byte) error
	// Metadata returns a key-value pair of non-sensitive data about the secret
	Metadata() map[string]string
	// SetMetadata allows the caller to set the secrets non-sensitive data
	// A secret may expects certain keys or values from the map and may return
	// an error.
	SetMetadata(map[string]string) error
}

Secret is a generic type that represents the actual secret values

The implementer is responsible for defining the data structure of their secrets.

Example:

type secret struct {
	AccessToken string
	RefreshToken string
}

func (s *secret) Marshal() ([]byte, error) {
	return []byte(s.AccessToken+":"+s.RefreshToken), nil
}

func (s *secret) Unmarshal(data []byte) error {
	tokens := bytes.Split(data, []byte(":"))
	if len(tokens) != 2 {
		return errors.New("invalid secret format")
	}

	s.AccessToken, s.RefreshToken = string(tokens[0]), string(tokens[1])
	return nil
}

type Store

type Store interface {
	// Delete removes credentials from the store for a given ID.
	Delete(ctx context.Context, id ID) error
	// Get retrieves credentials from the store for a given ID.
	Get(ctx context.Context, id ID) (Secret, error)
	// GetAllMetadata retrieves all the credentials from the store.
	// Credentials retrieved will only call [Secret.SetMetadata] so that the
	// underlying store does not get queried for each secret's sensitive data.
	// This could be very taxing on the underlying store and cause a poor User
	// Experience.
	GetAllMetadata(ctx context.Context) (map[ID]Secret, error)
	// Save persists credentials from the store.
	//
	// An empty secret value is rejected with [ErrEmptySecret].
	Save(ctx context.Context, id ID, secret Secret) error
	// Upsert atomically replaces an existing credential or inserts a new one.
	//
	// An empty secret value is rejected with [ErrEmptySecret].
	//
	// On the macOS Keychain an existing item is updated in place, keeping the
	// applications the user allowed to access it. Another store instance or
	// process can still write the same item concurrently, in which case Upsert
	// returns a backend-specific duplicate item error.
	Upsert(ctx context.Context, id ID, secret Secret) error
	// Filter returns a map of secrets based on a [Pattern].
	//
	// A pattern matching nothing is a valid empty result: implementations
	// return an empty (non-nil) map with a nil error, not ErrNotFound.
	//
	// Secrets returned will have both [Secret.SetMetadata] and [Secret.Unmarshal]
	// called; in that order. Any error produced by any of them would result in
	// an early return with a nil secrets map.
	Filter(ctx context.Context, pattern Pattern) (map[ID]Secret, error)
}

Store defines a strict format for secrets to conform to when interacting with the secrets engine

Jump to

Keyboard shortcuts

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