storage

package
v1.0.0-alpha1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: GPL-2.0 Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KeyCACert        = "ca_cert"
	KeyCAPubKey      = "ca_pubkey"
	KeyCAKey         = "ca_key"
	KeyCRL           = "crl"
	KeySerial        = "serial"
	KeyInventory     = "inventory"
	KeyInventoryHMAC = "inventory_hmac"
	KeyHMACKey       = "hmac_key"
	// KeySuperseded holds the cross-subject list of certificates that have
	// been replaced by a renewal and are awaiting delayed revocation. See
	// ca.CA.ReconcileSuperseded. It is operational state rather than CA
	// material, but it is written BlobPrivate like the inventory: it names
	// every subject that has renewed recently, which is not something a
	// world-readable cadir should volunteer.
	KeySuperseded = "superseded"
)

Logical key names used by StorageService to address backend blobs. Backends translate these into physical locations (paths, etcd keys, redis keys). Keys of the form "csr/<subject>" and "cert/<subject>" address per-subject CSRs and signed certificates.

View Source
const (
	CertStateSigned  = "signed"
	CertStateRevoked = "revoked"
	CertStateUnknown = "unknown"
)

Certificate index states recorded in CertRecord.State. Pending CSRs are not issued certificates and never appear in the index; the API layer derives the "requested" state from the csr/ namespace instead.

CertStateUnknown is reported (never stored as a target state) by a backend that cannot maintain per-serial state for a record — the etcd and redis backends, for serials that appeared more than once in a converted legacy blob, which their one-to-one by-serial index cannot address. Readers must derive such a record's real state from the signed CRL (the authoritative artefact) rather than trust the index.

View Source
const (
	FilePermPrivate = 0600
	FilePermPublic  = 0644
	DirPerm         = 0750
)

File permissions used by the filesystem backend. Exposed because callers that still reach directly into the filesystem (tests, migration helpers) need to match them.

View Source
const AllowUnverifiedSourceFlag = "allow-unverified-source"

AllowUnverifiedSourceFlag is the openvox-ca-ctl migrate flag that sets MigrateOptions.AllowUnverifiedSource. Defined here because the refusal names it, and consumed by the command rather than spelled twice, for the same reason as RebuildConfirmFlag.

View Source
const InventoryTimeFormat = "2006-01-02T15:04:05UTC"

InventoryTimeFormat is the layout for the NotBefore/NotAfter timestamps in an inventory.txt line. It is part of the on-disk wire format. The trailing "UTC" is a literal in the layout (Go's zone token is "MST"), so formatting a UTC time records its wall-clock digits and parsing yields them back as UTC.

View Source
const RebuildConfirmFlag = "yes-re-bless"

RebuildConfirmFlag is the flag name the offline rebuild requires before it will act. Exported and consumed by cmd/openvox-ca rather than spelled twice: this package names it in the hint an operator reads out of a log line, and the command defines the flag itself, so a rename in one place would otherwise leave the other pointing at a flag that does not exist.

Variables

View Source
var ErrCAKeyConflict = errors.New("two different CA keys in the cadir")

ErrCAKeyConflict is returned for every CA key operation on a cadir holding both ca_key.pem and private/ca_key.pem with different contents. Either could be the key this CA signs with, and picking one would sign with a key the operator may not have meant, or hand OpenVox Server one this CA never used.

View Source
var ErrCAKeyLinkBroken = errors.New("the CA key file is a link that leads nowhere")

ErrCAKeyLinkBroken is returned for a CA key file that is a symlink leading nowhere. It deliberately does not wrap fs.ErrNotExist: callers read that as "no key here" (migrate skips the key, Init takes the no-key branches), and a link where the key belongs is a key that is meant to be there.

View Source
var ErrDestinationNotEmpty = errors.New("destination backend already contains a CA certificate (use --force to overwrite)")

ErrDestinationNotEmpty is returned by Migrate when the destination backend already holds a CA certificate and MigrateOptions.Force is false.

View Source
var ErrDistributedLockingUnsupported = errors.New("distributed locking unsupported by this backend")

ErrDistributedLockingUnsupported signals that a backend advertising the Locker interface cannot actually provide a distributed lock in the current configuration (SQLite, which is single-node; an OverlayBackend wrapping a base with no locking support). StorageService.WithLock treats this as a hint to try the next tier down — SameHostLocker, and only then a process-local mutex.

View Source
var ErrDuplicateSerial = errors.New("serial number already exists in inventory")

ErrDuplicateSerial is returned by AppendInventory when the entry's serial number already exists in the inventory. SQL backends detect this via their unique index (translated from the dialect-specific driver error); the etcd backend via a by-serial marker key whose absence is a condition of the append transaction; the redis backend via a by-serial hash field the append script refuses to overwrite. All three are true cluster-wide guarantees. The filesystem backend — the only remaining blob one — detects it via an explicit scan performed under the same inventoryMu that already serialises every append within a process. That is a narrower guarantee rather than a bare gap: filesystem is single-node by construction, so no cross-replica case arises, and SameHostLocker gives its WithLock names cross-process reach on the host. What that reach does not extend to is the AppendInventory call itself, which no lock wraps (see the blob-fallback HMAC-update comment below, which documents a similar limitation for that path).

View Source
var ErrInventoryTampered = fmt.Errorf("inventory file integrity check failed: HMAC mismatch (possible tampering)")

ErrInventoryTampered is returned when the inventory HMAC verification fails.

View Source
var ErrMalformedSerial = errors.New("malformed serial")

ErrMalformedSerial marks input that is not a hexadecimal serial number, so callers taking a serial from an operator can answer "you typed it wrong" rather than reporting a server fault.

View Source
var ErrSameHostLockingUnsupported = errors.New("same-host locking unsupported by this backend")

ErrSameHostLockingUnsupported signals that a backend advertising the SameHostLocker interface cannot actually provide a same-host lock in the current configuration: an in-memory SQLite database (no file to lock beside, and no second process that could open it), a platform without flock(2), or an overlay over a base that offers neither. StorageService.WithLock treats this the same way it treats ErrDistributedLockingUnsupported — as a hint to fall back to a process-local mutex.

View Source
var ErrSourceUnverified = errors.New("refusing to migrate a source inventory that does not verify")

ErrSourceUnverified is returned by MigrateService when the source inventory does not verify against its stored integrity value and MigrateOptions.AllowUnverifiedSource is false.

Functions

func AtomicWriteFile

func AtomicWriteFile(target string, data []byte, perm os.FileMode) error

AtomicWriteFile writes data to a temporary file in the same directory as target, sets perm on it, then renames it into place. This prevents partial writes from leaving a corrupt file on disk (e.g. during a crash or power loss).

Exported because the offline subcommands write public PEM material to operator-supplied paths and must do it the same way: docs/storage-backends.md advertises the property for CA material, and a bundle an automation step is about to deploy fleet-wide should not be weaker than the copy in storage. One implementation rather than two so the two cannot drift.

The mode is applied to the descriptor before the rename, so the file never exists at the target path under the caller's umask.

func CSRKey

func CSRKey(subject string) string

CSRKey returns the logical key addressing subject's pending CSR.

func CertKey

func CertKey(subject string) string

CertKey returns the logical key addressing subject's signed certificate.

func DSNHasPassword

func DSNHasPassword(dsn string) bool

DSNHasPassword reports whether dsn carries a non-empty database password. It exists so the server can warn when a password has been put somewhere every local user can read, such as the command line, which is exposed whichever backend the DSN is for -- so the backend is not an input.

A postgres://, postgresql:// or unix:// URL with userinfo is read the way pgdriver reads it, taking the password from the userinfo alone; anything else is read as a go-sql-driver/mysql DSN. Both are needed: MySQL's parser rejects a PostgreSQL URL outright, and url.Parse finds no userinfo in a MySQL DSN. Userinfo is what decides, not the scheme alone, because url.Parse also accepts "postgres:secret@tcp(db)/ca" -- a MySQL DSN for a user called postgres -- as an opaque URL with that scheme. A DSN neither parser accepts, which includes every SQLite path, is reported as having none.

func FormatInventoryLine

func FormatInventoryLine(serial string, notBefore, notAfter time.Time, subject string) string

FormatInventoryLine builds the canonical inventory line (without the trailing newline) from the semantic fields, formatting the timestamps in UTC via InventoryTimeFormat. Issuance paths (signing, import) must construct inventory lines through this single constructor so they cannot drift from canonicalInventoryLine, which the structured backends store and chain over. The filesystem's inventory.txt is written from it by openVoxInventoryLine.

func LockIsEnforced

func LockIsEnforced(u Unlocker) bool

LockIsEnforced reports whether u is a lock that actually excludes another instance, as opposed to one of the no-ops AcquireInstanceLock returns when it has nothing to enforce.

It exists because those two are indistinguishable to a caller: both arrive as a nil error and a usable Unlocker, and the only notice of the difference is an slog warning, which an offline subcommand has usually just repointed at the server's logfile. A caller whose correctness depends on being alone — the inventory rebuild, whose head is computed from a snapshot — needs to be able to ask.

func NormaliseSerial

func NormaliseSerial(serial string) (string, error)

NormaliseSerial parses a hexadecimal serial number and re-renders it in the canonical form this CA stores and logs: uppercase hex, no leading zeros, and no separators. It rejects anything that is not a non-negative hexadecimal integer, so it doubles as the input validator for operator-supplied serials. One leading "0x" or "0X" is accepted: OpenVox Server writes its inventory serials that way, and the filesystem backend now does too, so it is the form an operator copying a serial from inventory.txt will have.

It is the storage-layer twin of the ca package's serialHexStr, which canonicalises a *big.Int that has already been parsed; this one starts from text.

func SQLiteFilePath

func SQLiteFilePath(dsn string) (string, bool)

SQLiteFilePath extracts the database file path from a SQLite DSN, which the driver accepts either as a bare path ("/var/lib/openvox-ca/ca.db") or as a "file:" URI, both optionally carrying query parameters. Reports false when the DSN names no file on disk.

Exported because the managed-certificate path check needs the same answer: that database holds the inventory, the signed certificates and the CRL, so a file store pointed at it would overwrite the CA's own state. Two implementations of "which file does this DSN name" would be two answers, and the one that drifted would be the one guarding against that.

Types

type Backend

type Backend interface {
	// EnsureReady prepares the backend for use (creates directories,
	// verifies connectivity, etc). Safe to call multiple times.
	EnsureReady(ctx context.Context) error

	// Get returns the blob at key. Wraps os.ErrNotExist when absent.
	Get(ctx context.Context, key string) ([]byte, error)

	// Put stores data at key atomically with respect to concurrent readers.
	// kind hints at visibility for backends that care.
	Put(ctx context.Context, key string, data []byte, kind BlobKind) error

	// Delete removes key. Wraps os.ErrNotExist when absent.
	Delete(ctx context.Context, key string) error

	// Exists reports whether key is present.
	Exists(ctx context.Context, key string) (bool, error)

	// List returns all keys with the given prefix. Only the csrPrefix and
	// certPrefix namespaces are listable.
	List(ctx context.Context, prefix string) ([]string, error)

	// AppendLine appends data to key, creating it if absent. The append is
	// atomic with respect to concurrent AppendLine calls on the same key
	// within a single process. Callers include any trailing newline in data.
	AppendLine(ctx context.Context, key string, data []byte, kind BlobKind) error

	// ModTime returns the last-modified time of key. Backends that do not
	// track modification time may return the zero time with a nil error.
	// Wraps os.ErrNotExist when absent.
	ModTime(ctx context.Context, key string) (time.Time, error)

	// Close releases any resources held by the backend. Close is intended
	// for shutdown and intentionally does not take a context: cleanup must
	// always run.
	Close() error
}

Backend is the pluggable storage abstraction that StorageService delegates to. Implementations translate the logical key namespace into physical storage (filesystem paths, etcd/redis keys, ...).

Get and Delete must return an error that wraps os.ErrNotExist (fs.ErrNotExist) when the key does not exist so callers can distinguish absence from failure.

All operations except Close take a context for caller cancellation and deadline propagation. Implementations may further bound a single network round-trip with their own per-call timeout (context.WithTimeout on top of the caller's ctx); cancellation of the caller's ctx must always propagate. The filesystem backend honours ctx only at the start of each call — individual syscalls cannot be interrupted mid-flight.

type BackendKind

type BackendKind string

BackendKind identifies which backend implementation to construct.

const (
	BackendFilesystem BackendKind = "filesystem"
	BackendEtcd       BackendKind = "etcd"
	BackendRedis      BackendKind = "redis"
	BackendSQLite     BackendKind = "sqlite"
	BackendPostgres   BackendKind = "postgres"
	BackendMySQL      BackendKind = "mysql"
)

func ParseBackendKind

func ParseBackendKind(s string) (BackendKind, error)

ParseBackendKind parses a kind string from configuration, accepting common aliases and rejecting unknown values.

type BackendSpec

type BackendSpec struct {
	// Kind selects the backend implementation. Empty means BackendFilesystem.
	Kind BackendKind

	// LocalDir is the operational directory on the local filesystem. For the
	// filesystem backend it is the backend root; for remote backends it is
	// still used for per-subject generated private keys (always local) and
	// for ancillary local state such as the inventory-integrity HMAC key.
	LocalDir string

	// Etcd configures the etcd backend. Only consulted when Kind == BackendEtcd.
	Etcd EtcdSpec

	// Redis configures the Redis/Valkey backend. Only consulted when
	// Kind == BackendRedis.
	Redis RedisSpec

	// SQL configures a SQL backend (SQLite, and in later changes PostgreSQL and
	// MySQL/MariaDB). Only consulted when Kind is one of the SQL backends.
	SQL SQLSpec

	// CACertFile, when non-empty, keeps the CA certificate on local disk at
	// this path regardless of the selected backend. Useful when operators
	// want to supply the cert as a file or mount it from a secret volume.
	CACertFile string

	// CAKeyFile, when non-empty, keeps the CA private key on local disk at
	// this path regardless of the selected backend. Combine with a remote
	// backend to keep the key out of shared storage.
	CAKeyFile string
}

BackendSpec describes how to construct a StorageService from configuration. It lets the main application defer backend selection to a single place.

type BlobKind

type BlobKind int

BlobKind signals the desired visibility of a stored blob. The filesystem backend maps these to file permissions (0600 vs 0644); remote backends may ignore it or use the hint to pick a storage namespace.

const (
	// BlobPublic marks blobs that may be world-readable (CA cert, CRL, CSRs,
	// signed certs). Filesystem backend writes 0644.
	BlobPublic BlobKind = iota
	// BlobPrivate marks blobs that must stay owner-only (CA key, HMAC key,
	// inventory). Filesystem backend writes 0600.
	BlobPrivate
)

type CertIndex

type CertIndex interface {
	// Statuses returns one record per subject that currently holds a stored
	// signed certificate — the latest issuance for that subject — in subject
	// order. stateFilter narrows the result to CertStateSigned or
	// CertStateRevoked; "" returns all records. Records whose projection has
	// never been populated are returned with an empty Fingerprint so the
	// caller can fall back to the stored PEM for display fields.
	//
	// Note today's in-tree callers always pass "": the statuses handler must
	// see every certified subject to keep its CSR-dedup set complete (it
	// filters per record in Go), and the index repair pass reconciles all
	// records. The filter is nevertheless part of the capability contract —
	// it is the indexed query shape issue #137 fixes the schema for, it is
	// dialect-tested, and direct consumers (CLI/report tooling) can use it
	// without a schema change.
	Statuses(ctx context.Context, stateFilter string) ([]CertRecord, error)

	// SetRevoked marks every index row bearing serial as revoked at the given
	// time. Idempotent: re-marking an already-revoked serial keeps the
	// original revocation time. A serial with no matching row is a no-op, not
	// an error (the CRL may legitimately reference certs the index no longer
	// tracks).
	//
	// SetRevoked, ClearRevoked, and SetProjection may also decline a write —
	// as a logged no-op, not an error — when the implementation cannot
	// unambiguously identify the bearing rows (the etcd and redis backends'
	// one-to-one by-serial index cannot address a serial duplicated in a
	// converted legacy blob). Statuses reports such records with
	// CertStateUnknown so callers know to derive their state from the CRL
	// instead.
	SetRevoked(ctx context.Context, serial string, at time.Time) error

	// ClearRevoked returns every index row bearing serial to the signed
	// state. Used by index repair when a row claims a revocation the signed
	// CRL does not corroborate.
	ClearRevoked(ctx context.Context, serial string) error

	// SetProjection fills the denormalised display fields for every index row
	// bearing serial. Used to backfill rows created from projection-less
	// sources (legacy inventory blobs, direct AppendLine writes).
	SetProjection(ctx context.Context, serial string, proj CertProjection) error
}

CertIndex is an optional capability of InventoryStore backends: the backend that owns the structured inventory rows can answer certificate-status queries from indexed columns instead of forcing the caller into a list-certs → read-PEM → parse → CRL-check scan per subject.

The certificate blobs stay authoritative. Statuses reflects the index rows joined against blob existence, so a certificate removed by clean/cleanup stops being reported even though its historical inventory rows remain.

type CertProjection

type CertProjection struct {
	// Fingerprint is the SHA-256 digest of the certificate's DER encoding,
	// rendered as colon-separated hex pairs exactly as the status API emits it.
	// An empty Fingerprint marks a record whose projection has not been
	// populated (e.g. rows imported from a legacy inventory blob); readers must
	// fall back to parsing the stored PEM for such records.
	Fingerprint string
	// DNSAltNames holds the certificate's DNS subject alternative names.
	DNSAltNames []string
	// IPAltNames holds the certificate's IP address subject alternative names,
	// in the text form ca.IPAddressStrings renders.
	//
	// Every backend stores this field so that a projection written before it
	// existed can be told apart from one with no IP SANs: an empty list is
	// stored as an empty list, never as an absent value. A projection that
	// lacks the field decodes as no projection at all (empty Fingerprint), so
	// readers fall back to the PEM and the startup repair pass rewrites it.
	IPAltNames []string
	// AuthExtensions holds Puppet auth-arc extension values keyed by short
	// name (e.g. "pp_auth_role") or dotted OID when no short name is known.
	AuthExtensions map[string]string
}

CertProjection carries the display fields denormalised from a signed certificate into the certificate index. Every field is immutable for the life of the certificate (they are fixed at signing), so the projection can never drift from the stored PEM — the PEM remains the authoritative artefact and the projection is rebuildable from it at any time.

type CertRecord

type CertRecord struct {
	InventoryEntry
	CertProjection
	State     string     // CertStateSigned or CertStateRevoked
	RevokedAt *time.Time // nil unless revoked
}

CertRecord is one issued certificate as the certificate index sees it: the canonical inventory fields, the denormalised display projection, and the one mutable fact — revocation. State/RevokedAt are a projection of the signed CRL (the source of truth), written alongside CRL updates and rebuildable from it, exactly as the projection fields relate to the PEM. The rebuildability guarantee is conditional on the backend being able to address the record's serial one-to-one; when it cannot, State is reported as CertStateUnknown and the reader consults the CRL directly.

Note the integrity hash chain covers only the canonical InventoryEntry fields (via canonicalInventoryLine); the projection columns are not chained. That is deliberate: each projection field is independently verifiable against a signed artefact (the certificate PEM or the CRL), so chaining them would add nothing the artefacts do not already guarantee.

type EtcdBackend

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

EtcdBackend is a Backend implementation backed by an etcd v3 cluster.

Blob contents are wrapped with an 8-byte big-endian nanosecond mtime prefix so ModTime can be answered without a second key. The certificate inventory is not stored as a blob: it is decomposed into per-entry keys (see etcd_inventory.go), and the backend implements InventoryStore and CertIndex. Mutations use etcd Txns with ModRevision guards to remain atomic across concurrent writers, including those in different processes. Distributed locks are provided via AcquireLock using etcd's concurrency.Mutex on a lazily-created lease session.

func NewEtcdBackend

func NewEtcdBackend(cfg EtcdConfig) (*EtcdBackend, error)

NewEtcdBackend connects to the configured etcd cluster and returns a ready backend. The caller must call Close to release the underlying client.

func NewEtcdBackendFromClient

func NewEtcdBackendFromClient(cli *clientv3.Client, keyPrefix string, requestTimeout time.Duration) *EtcdBackend

NewEtcdBackendFromClient wraps an existing etcd client. The backend does not take ownership and Close leaves the client open. Primarily used by tests that need to share a single embedded etcd across backends.

func (*EtcdBackend) AcquireLock

func (b *EtcdBackend) AcquireLock(ctx context.Context, name string) (Unlocker, error)

AcquireLock obtains a distributed mutex under <prefix>/locks/<name> using etcd's concurrency.Mutex. Local goroutines racing on the same name are serialised by a per-name process-local mutex first (concurrency.Mutex is not safe for re-entry on the same session), then the distributed mutex is taken so only one process in the cluster holds the lock at a time.

func (*EtcdBackend) AppendEntry

func (b *EtcdBackend) AppendEntry(ctx context.Context, rec CertRecord, newHead func(prev []byte) []byte) error

AppendEntry inserts rec and advances the integrity head atomically. The commit transaction is guarded on the fence being unchanged since the read (so the head cannot fork under concurrent appenders, including other replicas) and on rec's by-serial key not existing (the cluster-wide duplicate-serial guarantee). newHead runs in Go between the read and the commit; a conflicting writer invalidates the guard and the loop re-reads.

func (*EtcdBackend) AppendLine

func (b *EtcdBackend) AppendLine(ctx context.Context, key string, data []byte, _ BlobKind) error

AppendLine atomically appends data to key. Concurrent appends from this process are serialised on appendMu; concurrent appends from other processes are resolved by an etcd Txn guarded on the key's ModRevision with bounded retry on conflict.

func (*EtcdBackend) ClearRevoked

func (b *EtcdBackend) ClearRevoked(ctx context.Context, serial string) error

ClearRevoked returns the entry bearing serial to the signed state.

func (*EtcdBackend) Close

func (b *EtcdBackend) Close() error

Close releases the underlying etcd client when owned by this backend, and always closes the lock session if one was created. Later lock acquisitions fail with errEtcdBackendClosed.

func (*EtcdBackend) Delete

func (b *EtcdBackend) Delete(ctx context.Context, key string) error

Delete removes key, wrapping fs.ErrNotExist when the key is absent. Deleting KeyInventory removes the marker and the decomposed structure.

func (*EtcdBackend) EnsureReady

func (b *EtcdBackend) EnsureReady(ctx context.Context) error

EnsureReady verifies connectivity by listing the cluster status (etcd has no directory concept so there is nothing to create), then decomposes a legacy inventory blob left by a pre-decomposition version of this backend into the per-entry structure. Decomposition must run before the inventory is used: the structured paths assume the blob key is only a presence marker.

func (*EtcdBackend) Entries

func (b *EtcdBackend) Entries(ctx context.Context) ([]InventoryEntry, error)

Entries returns every inventory entry in issuance order.

func (*EtcdBackend) Exists

func (b *EtcdBackend) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present.

func (*EtcdBackend) Get

func (b *EtcdBackend) Get(ctx context.Context, key string) ([]byte, error)

Get returns the (unwrapped) blob at key, wrapping fs.ErrNotExist when absent. The KeyInventory key is served from the decomposed entry keys (rendered to inventory.txt text) rather than a stored blob.

func (*EtcdBackend) LatestSerialForSubject

func (b *EtcdBackend) LatestSerialForSubject(ctx context.Context, subject string) (string, error)

LatestSerialForSubject returns the most recently issued serial for subject, wrapping fs.ErrNotExist when the subject has no entry. This is a single point read of the by-subject index key.

func (*EtcdBackend) List

func (b *EtcdBackend) List(ctx context.Context, prefix string) ([]string, error)

List returns the logical keys sharing prefix. Only csrPrefix and certPrefix are supported; other prefixes yield an error.

func (*EtcdBackend) ModTime

func (b *EtcdBackend) ModTime(ctx context.Context, key string) (time.Time, error)

ModTime returns the wall-clock timestamp recorded when the blob was last written. Returns fs.ErrNotExist-wrapped when the key is absent.

func (*EtcdBackend) PruneEntries

func (b *EtcdBackend) PruneEntries(ctx context.Context, keep func(InventoryEntry) bool, advanceHead func(prev []byte, e InventoryEntry) []byte) ([]InventoryEntry, error)

PruneEntries removes the entries for which keep returns false and rewrites the integrity head over the survivors. A prune larger than one transaction's op budget is split into batches; every intermediate transaction writes a head that exactly covers the entries remaining after it, so each committed revision is internally consistent (entries and head always match — a concurrent verifier on another replica never observes a spurious mismatch, and a crash mid-prune leaves a valid, partially-pruned inventory that the caller's next prune completes). Interleaved appends invalidate the fence and restart the prune from a fresh read.

Per the interface contract, the returned slice contains every entry that was durably removed — accumulated across batches and retries, and returned even alongside a non-nil error — so the caller's CRL/blob cleanup never misses an entry that a partially-completed prune already deleted. One call removes at most etcdPruneMaxBatchesPerCall batches' worth of entries; matches beyond that stay in the inventory for later calls (the interface contract permits bounding, and the periodic cleanup job converges).

func (*EtcdBackend) Put

func (b *EtcdBackend) Put(ctx context.Context, key string, data []byte, _ BlobKind) error

Put writes the blob at key. The BlobKind hint is recorded but has no effect on the stored form: etcd access control is managed by the cluster. Putting KeyInventory parses the text and replaces the decomposed entries.

func (*EtcdBackend) SetProjection

func (b *EtcdBackend) SetProjection(ctx context.Context, serial string, proj CertProjection) error

SetProjection fills the denormalised display fields for the entry bearing serial. Used to backfill records created from projection-less sources (legacy blob imports, direct AppendLine writes).

func (*EtcdBackend) SetRevoked

func (b *EtcdBackend) SetRevoked(ctx context.Context, serial string, at time.Time) error

SetRevoked marks the entry bearing serial as revoked at the given time. Idempotent: an already-revoked entry keeps its original revocation time. A serial with no entry is a no-op, not an error.

func (*EtcdBackend) Statuses

func (b *EtcdBackend) Statuses(ctx context.Context, stateFilter string) ([]CertRecord, error)

Statuses returns one record per subject that currently holds a stored signed certificate (the subject's latest issuance), in subject order, optionally narrowed to stateFilter. Unlike SQL there is no indexed query to push the latest-per-subject fold into, so the whole entry range is read and folded in Go — still a single round-trip against the entries, compared with the per-subject PEM read-and-parse the fallback path costs.

type EtcdConfig

type EtcdConfig struct {
	// Endpoints is the list of etcd cluster endpoints (host:port).
	Endpoints []string
	// DialTimeout bounds the initial connection attempt. Zero uses 5s.
	DialTimeout time.Duration
	// RequestTimeout bounds per-request operations. Zero uses 5s.
	RequestTimeout time.Duration
	// Username / Password enable etcd authentication when both are set.
	Username string
	Password string
	// TLS, if non-nil, configures TLS for the etcd connection.
	TLS *tls.Config
	// KeyPrefix namespaces all keys stored by this backend so multiple CAs
	// (or other applications) can share a single etcd cluster. Defaults to
	// "/puppet-ca" when empty.
	KeyPrefix string
}

EtcdConfig configures the etcd-backed storage backend.

type EtcdSpec

type EtcdSpec struct {
	Endpoints         []string
	KeyPrefix         string
	Username          string
	Password          string
	DialTimeoutSec    int
	RequestTimeoutSec int
	TLSCAFile         string
	TLSCertFile       string
	TLSKeyFile        string
}

EtcdSpec is the config-friendly form of EtcdConfig with TLS expressed as file paths rather than a preloaded tls.Config.

type FilesystemBackend

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

FilesystemBackend stores blobs as files under a single base directory. It is the default Backend implementation. It keeps OpenVox Server's own CA directory layout and inventory line format, and reads a cadir an earlier version of openvox-ca wrote (the key in private/, canonical inventory lines) in place, without rearranging it.

func NewFilesystemBackend

func NewFilesystemBackend(baseDir string) *FilesystemBackend

NewFilesystemBackend constructs a FilesystemBackend rooted at baseDir.

func (*FilesystemBackend) AcquireInstanceLock

func (b *FilesystemBackend) AcquireInstanceLock() (Unlocker, error)

AcquireInstanceLock takes the store-wide lock permitting one running instance, as an exclusive flock(2) under <baseDir>/locks alongside the per-name locks.

The cadir is the store, so locking within it is locking the store. It shares the lock directory rather than taking a lock of its own beside it so that a single chown fixes every lock a store has, which is the recovery the permission error in inaccessibleLockFile sends operators to.

func (*FilesystemBackend) AcquireSameHostLock

func (b *FilesystemBackend) AcquireSameHostLock(ctx context.Context, name string) (Unlocker, error)

AcquireSameHostLock takes the named lock as an exclusive flock(2) on a file under <baseDir>/locks, excluding another process on this host — an `openvox-ca-ctl` command, or a second server — from the same name.

It deliberately promises nothing across hosts, and this backend still implements no Locker, so anything asking whether the store coordinates across *replicas* continues to be told no. That is the honest answer: docs/storage-backends.md scopes the filesystem backend to single-node installs, and flock(2) over NFS is not a basis for widening it.

func (*FilesystemBackend) AppendLine

func (b *FilesystemBackend) AppendLine(ctx context.Context, key string, data []byte, kind BlobKind) error

func (*FilesystemBackend) BaseDir

func (b *FilesystemBackend) BaseDir() string

BaseDir returns the filesystem root.

func (*FilesystemBackend) CAKeyFile

func (b *FilesystemBackend) CAKeyFile() string

CAKeyFile returns the path of the CA key file this backend would read, or "" when there is none or it cannot be resolved. It never reads the key: see caKeyLocation.

func (*FilesystemBackend) Close

func (b *FilesystemBackend) Close() error

func (*FilesystemBackend) Delete

func (b *FilesystemBackend) Delete(ctx context.Context, key string) error

func (*FilesystemBackend) EnsureReady

func (b *FilesystemBackend) EnsureReady(ctx context.Context) error

func (*FilesystemBackend) Exists

func (b *FilesystemBackend) Exists(ctx context.Context, key string) (bool, error)

func (*FilesystemBackend) Get

func (b *FilesystemBackend) Get(ctx context.Context, key string) ([]byte, error)

func (*FilesystemBackend) List

func (b *FilesystemBackend) List(ctx context.Context, prefix string) ([]string, error)

func (*FilesystemBackend) ModTime

func (b *FilesystemBackend) ModTime(ctx context.Context, key string) (time.Time, error)

func (*FilesystemBackend) Path

func (b *FilesystemBackend) Path(key string) string

Path returns the filesystem path for key, or empty if key is unknown. Used for diagnostic messages and by StorageService's legacy *Path methods.

func (*FilesystemBackend) Put

func (b *FilesystemBackend) Put(ctx context.Context, key string, data []byte, kind BlobKind) error

type HMACKeyState

type HMACKeyState int

HMACKeyState describes the stored inventory HMAC key as found, without changing it. EnsureHMACKey regenerates a present-but-wrong-length key, which is itself one of the ways an inventory stops verifying; a report that called it would perform the very act it exists to describe.

const (
	// HMACKeyUnknown is the zero value: nothing has been read yet. It exists so
	// that a zero-valued report does not assert the most reassuring answer --
	// InventoryIntegrityReport returns a partly-filled report alongside every
	// error, and on the arms that fail before the key is read, a zero value
	// meaning "usable" would be a lie a caller could act on.
	HMACKeyUnknown HMACKeyState = iota
	// HMACKeyUsable means the stored key is present and the expected length.
	HMACKeyUsable
	// HMACKeyAbsent means no key is stored: integrity was never initialised.
	HMACKeyAbsent
	// HMACKeyWrongLength means a key is stored but is not hmacKeyLen bytes.
	// Every existing MAC was computed under a key that no longer exists, so no
	// rebuild can reproduce them and one would mint a new key as a side effect.
	HMACKeyWrongLength
)

func (HMACKeyState) String

func (s HMACKeyState) String() string

String names the state for operator-facing output.

type InstanceLockOption

type InstanceLockOption func(*instanceLockConfig)

InstanceLockOption adjusts one AcquireInstanceLock call.

func WithKnownDistributedLocking

func WithKnownDistributedLocking(distributed bool) InstanceLockOption

WithKnownDistributedLocking supplies an answer the caller has already had from SupportsDistributedLocking, so this call does not buy it twice.

Optional by design. The probe acquires and releases a real lock, so on a cluster backend it is a round trip, and `openvox-ca generate` was paying for two: one for the capability report it prints, one for the lock. But a caller that knows nothing must stay able to call AcquireInstanceLock and get a correct answer -- csr and import-ca-cert do exactly that -- so this is a hint rather than a parameter. Making it required would push the probe out to the call sites that currently do the right thing by not thinking about it.

Pass only a definite answer. SupportsDistributedLocking has three outcomes, and its error is not a "false": a caller whose own probe failed should omit this and let AcquireInstanceLock re-probe, so the documented warn-and-permit policy for an undetermined capability applies in one place rather than being reimplemented by each caller.

type InstanceLocker

type InstanceLocker interface {
	AcquireInstanceLock() (Unlocker, error)
}

InstanceLocker is implemented by backends that can hold a store-wide exclusive lock excluding another process on the same host.

Deliberately not part of Backend: a backend that cannot provide one is not broken, it is simply one where this rule has to rest on the operator instead.

No context parameter, unlike Locker and SameHostLocker, and that is the contract rather than an oversight: this acquisition never waits. A caller starting a server wants to be told that another instance is running, not to queue behind it until a timeout it would then have to explain.

type InventoryEntry

type InventoryEntry struct {
	Serial    string
	NotBefore string
	NotAfter  string
	Subject   string
}

InventoryEntry is one issued-certificate record in the inventory. NotBefore and NotAfter are stored verbatim as the formatted strings the signing path produces, so that rendering entries back to the inventory.txt line is byte-identical to the legacy append-only blob.

type InventoryIntegrityReport

type InventoryIntegrityReport struct {
	// Scheme is the integrity scheme this backend computes under:
	// "hash-chain" on InventoryStore backends, "whole-blob-hmac" otherwise.
	Scheme string
	// Entries is the number of inventory entries the value covers.
	Entries int
	// KeyState is the stored HMAC key as found.
	KeyState HMACKeyState
	// StoredHead is the persisted integrity value, nil when none is stored.
	StoredHead []byte
	// ComputedHead is the value recomputed from the inventory as it now
	// stands, nil when KeyState is not HMACKeyUsable.
	ComputedHead []byte
	// LegacyUndecomposed reports a structured backend still holding an
	// undecomposed legacy inventory blob. Entries() reads only the decomposed
	// rows, so such a store answers "no entries" while its real inventory sits
	// in the blob and its stored head is a whole-blob MAC. Rebuilding there
	// would write an empty hash-chain head over the only baseline that can
	// validate the blob, which is destruction rather than repair.
	//
	// It can be true only because this report is reached without EnsureReady:
	// the server decomposes on start (CA.Init -> EnsureDirs -> EnsureReady),
	// and an offline command that reports rather than starts does not.
	LegacyUndecomposed bool
	// UnparseableLines counts lines the inventory blob holds that are not
	// entry-shaped. Always zero on a structured backend, whose entries are
	// rows. It is not a curiosity: the blob scheme MACs the whole blob, so
	// those lines are covered by the value a rebuild re-asserts while being
	// invisible in Entries — which is the operator's only quantitative view of
	// what they are about to sign over.
	UnparseableLines int
	// Verifies reports whether StoredHead and ComputedHead agree. False
	// whenever either is missing.
	Verifies bool
}

InventoryIntegrityReport is the inventory's integrity state as it currently stands. Every field is what was found, never what was repaired.

type InventoryStore

type InventoryStore interface {
	// AppendEntry inserts rec and advances the integrity head atomically.
	// newHead computes the chained head MAC from the previous head (nil when
	// the inventory is empty); the backend MUST invoke it inside the same
	// transaction or lock that serialises appends so the chain cannot fork
	// under concurrent appenders. A nil newHead means integrity is disabled
	// (no HMAC key configured): the backend appends the entry and leaves the
	// stored head untouched. Only rec's canonical InventoryEntry fields feed
	// the chain; the projection/state columns are stored uncovered (see
	// CertRecord).
	AppendEntry(ctx context.Context, rec CertRecord, newHead func(prev []byte) []byte) error

	// Entries returns every entry in issuance order, for the OCSP index build
	// and for chain verification.
	Entries(ctx context.Context) ([]InventoryEntry, error)

	// LatestSerialForSubject returns the most recently issued serial for
	// subject. Wraps os.ErrNotExist when the subject has no entry.
	LatestSerialForSubject(ctx context.Context, subject string) (string, error)

	// PruneEntries removes every entry for which keep returns false and
	// rewrites the integrity head over the survivors. advanceHead advances the
	// hash chain by one entry from the previous head (nil for the first
	// entry); a nil advanceHead means integrity is disabled and the stored
	// head is left untouched.
	//
	// Consistency contract: the stored entries and the stored head must never
	// be observable out of sync by another replica. Implementations need not
	// perform the whole prune in one transaction — the etcd backend commits
	// it in batches, each of which writes a head covering exactly the entries
	// that remain after it — so a prune may partially complete on conflict or
	// error, and an implementation may deliberately bound how much one call
	// removes (etcd caps a call's batches, and redis — which commits the
	// whole removal in one atomic script, so it never partially completes —
	// caps a call's entries, both so a huge backlog cannot blow the caller's
	// time budget; deferred matches stay present and consistent for later
	// calls). Whatever happens, the returned slice must contain every
	// entry actually removed (in issuance order), including alongside a
	// non-nil error: callers drive CRL entry removal and blob cleanup from
	// it, and an entry that was durably removed but not returned can never be
	// rediscovered. An empty slice with a nil error means nothing matched.
	PruneEntries(ctx context.Context, keep func(InventoryEntry) bool, advanceHead func(prev []byte, e InventoryEntry) []byte) ([]InventoryEntry, error)
}

InventoryStore is an optional Backend capability for storing the certificate inventory as structured records (a SQL table, etcd keys, redis hash fields) rather than the single append-only KeyInventory blob. Backends that implement it let StorageService skip the render → scan → reparse round-trip for appends and subject lookups, and verify integrity with a hash chain instead of re-hashing the whole blob.

Backends that do not implement it keep using the KeyInventory blob via AppendLine/Get; StorageService selects the path with a type assertion, the same way it probes Locker.

A backend that implements InventoryStore must still serve the KeyInventory logical key through Get/Put/Exists (rendering rows to inventory.txt text and parsing text back to rows) so that Migrate and the OCSP index build remain backend-agnostic.

type KeyFileLister

type KeyFileLister interface {
	// KeyFilePaths returns the files that may contain key material. Paths that
	// do not exist are permitted and ignored by the caller.
	KeyFilePaths() []string
}

KeyFileLister is an optional capability for backends that keep key material in files of their own, outside the local private-key directory StorageService already scans. The SQLite backend implements it: its database holds the CA key as a blob, and the sidecars beside it hold page images of the same rows. A wrapper backend is reached through asKeyFileLister rather than a bare type assertion, for the reason the other capability probes are: a bare assertion on a wrapper that does not forward the method reports "no key files" rather than failing, and a permission check that silently has nothing to judge is the one failure mode this check cannot afford. OverlayBackend does forward it today, so nothing is broken; this is about the next wrapper.

type KeyPermWarning

type KeyPermWarning struct {
	Path string
	Mode os.FileMode

	// Unreadable marks a path whose permissions could not be established at all
	// -- an unreadable parent directory, an I/O error, a symlink whose target
	// cannot be resolved. Mode is meaningless when this is set.
	//
	// It is a distinct state rather than a pessimistic Mode because the two need
	// different things said about them: "world-accessible, chmod o-rwx" is a
	// remedy, and printing it for a path that is actually 0000 sends the
	// operator to run a command that changes nothing and leaves the next start
	// refusing identically.
	Unreadable bool

	// Err is why the path could not be judged, for the operator to act on. Set
	// only when Unreadable is.
	Err error
}

KeyPermWarning describes a file holding key material whose on-disk permissions are looser than expected.

func (KeyPermWarning) WorldAccessible

func (w KeyPermWarning) WorldAccessible() bool

WorldAccessible reports whether this finding should be refused: either the mode grants access to users outside the owner and the group, or the path could not be judged at all.

The second half is as much the contract as the first, and is stated here rather than only in the body because a caller reading the rendered godoc has to know it: a permission this process cannot read is not one it may assume is safe, so an unjudgeable path counts as world-accessible and callers refuse by default. Mode is meaningless when Unreadable is set. Callers that can say something better about that case -- naming the path as unreadable rather than as world-readable -- test Unreadable first, and all of them do.

World access means every local account can read the CA private key, and is refused. Group access is tolerated: a Kubernetes fsGroup reapplies it at every mount whatever a file was created as, so refusing on it would make the most common containerised deployment unserveable through no act of the operator's.

type Locker

type Locker interface {
	AcquireLock(ctx context.Context, name string) (Unlocker, error)
}

Locker is an optional Backend capability that provides a cross-node distributed mutex. Backends implement it when they have a natural way to coordinate a lock across replicas (etcd's concurrency.Mutex, Redis SET NX, etc.).

A backend without this capability is not left unlocked: StorageService.WithLock falls through to SameHostLocker, which the single-node backends implement, and only to a process-local named mutex when neither is available. Implement this one *only* if the coordination genuinely spans hosts — a single-node backend that implements it claims a guarantee it cannot keep, and callers deciding whether a second replica is safe probe exactly this.

The returned Unlocker must be called exactly once, typically via defer. Implementations are free to use leases, so a long-delayed Unlock may no-op if the lease has already expired.

type MigrateOptions

type MigrateOptions struct {
	// Force permits writing into a destination that already holds CA material.
	// When false, Migrate aborts with ErrDestinationNotEmpty if the destination
	// already has a CA certificate, to avoid clobbering a live CA.
	Force bool

	// Logf, when non-nil, receives one human-readable line per copied blob.
	Logf func(format string, args ...any)

	// AllowUnverifiedSource lets MigrateService copy a source whose inventory
	// does not verify against its stored integrity value, rather than refusing
	// with ErrSourceUnverified. Migrate itself never verifies, so it ignores
	// this.
	AllowUnverifiedSource bool

	// CAKey, when non-nil, turns the source's stored CA key into the one the
	// destination stores; openvox-ca-ctl migrate uses it to encrypt or
	// re-encrypt the key for the destination's configuration. It is a hook
	// because this package cannot import internal/ca, which holds the encoder.
	// Migrate calls it before it touches the destination at all, so a refusal
	// leaves the destination as it was. It is not called when the source holds
	// no CA key.
	CAKey func(sourceKey []byte) ([]byte, error)
}

MigrateOptions tunes a Migrate run.

type MigrateReport

type MigrateReport struct {
	Singletons int // fixed CA/operational blobs copied
	CSRs       int // pending certificate requests copied
	Certs      int // signed certificates copied

	// UnverifiedSource is set by MigrateService when it copied a source
	// inventory it could not verify, and says why: either the source never
	// recorded an integrity value, or AllowUnverifiedSource let a failure
	// through. Empty when the source verified. Whichever it is, the
	// destination's integrity value will vouch for the copy: MigrateService
	// rebuilds it when the destination holds an HMAC key (copied from the
	// source, or already there, as under Force), and otherwise the server's
	// first start writes it, at Warn. A caller should show this to the operator: it
	// is the only record that the value vouches for an inventory nothing
	// checked.
	UnverifiedSource string
}

MigrateReport summarises what a Migrate run copied.

func Migrate

func Migrate(ctx context.Context, src, dst Backend, opts MigrateOptions) (MigrateReport, error)

Migrate copies every blob held by src into dst, preserving each blob's visibility (public/private). It is backend-agnostic: any pair of Backend implementations may be combined, enabling filesystem→database, database→database and database→filesystem migrations.

Per-subject generated private keys are not copied: they always live on the local filesystem outside any backend. The CA key is copied as it is unless opts.CAKey rewrites it.

Migrate is not transactional. On error it returns the blobs copied so far in the report. Re-running is safe: copies overwrite matching keys idempotently.

func MigrateService

func MigrateService(ctx context.Context, src, dst *StorageService, opts MigrateOptions) (MigrateReport, error)

MigrateService copies src to dst exactly like Migrate, but holds each backend's strongest lock for the whole copy, guarding against a concurrent migration or a CA bootstrap racing on either backend. Locks are acquired source-first, then destination, and released in reverse on return.

Note: pointing both src and dst at the same store would have the two lock acquisitions deadlock. On a distributed backend they are separate sessions; on a single-node one they are two separate backend values, each with its own per-name mutex, so the second blocks on the *flock* and spins in its backoff loop rather than parking on a mutex — a live poll, not a blocked goroutine, which is what a maintainer reading a stack dump needs to know. Since MigrateService applies no timeout, that wait never ends; it announces itself on the first refusal ("Waiting for the CA lock"), so interrupt it. Migrating a store onto itself is not a supported operation, and this is now the same failure on every backend rather than only the distributed ones.

A source this process cannot write to is fine: the same-host lock reports itself unsupported rather than failing there, since a store nothing can write to has no writer to exclude, and a migration only reads its source.

The source inventory is verified first, under the source's lock and before the destination is touched, because the destination's integrity value is rebuilt over whatever was copied: without the check, a migration would turn a tampered inventory into one that verifies. See verifyMigrationSource for what refuses and what does not.

func (MigrateReport) Total

func (r MigrateReport) Total() int

Total returns the total number of blobs copied.

type OverlayBackend

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

OverlayBackend wraps a Backend, redirecting reads and writes for a fixed set of logical keys to explicit local filesystem paths. The typical use is to keep the CA certificate and/or private key on local disk (or a mounted secret volume) even when the rest of the CA state lives in a remote backend such as etcd.

Only single-blob keys (KeyCACert, KeyCAKey, KeyCAPubKey, etc.) are safe to override. Operations on list-style keys (csrPrefix, certPrefix) and append-style keys (KeyInventory) are always delegated to the underlying backend; AppendLine on an overridden key returns an error.

func NewOverlayBackend

func NewOverlayBackend(base Backend, overrides map[string]string) (*OverlayBackend, error)

NewOverlayBackend returns a backend that serves overrides from local files and delegates everything else to base. Empty override values are ignored; the backend requires at least one non-empty override. All paths are resolved to absolutes.

func (*OverlayBackend) AcquireInstanceLock

func (o *OverlayBackend) AcquireInstanceLock() (Unlocker, error)

AcquireInstanceLock delegates to the base backend's InstanceLocker when present, for the same reason the two lock methods above delegate: the override files are local copies of CA material, but the store an instance must be alone in is the base backend's.

Forwarding is what makes the rule hold for an overlay at all. An overlay over a filesystem base reports no distributed locking, so the single-instance rule applies to it — and without this method a type assertion would find no InstanceLocker and silently permit the second instance the rule exists to refuse.

func (*OverlayBackend) AcquireLock

func (o *OverlayBackend) AcquireLock(ctx context.Context, name string) (Unlocker, error)

AcquireLock delegates to the base backend's Locker implementation when present. Locks must span the whole cluster (e.g. "bootstrap" must serialise across replicas even when the CA key sits on a local file), so it is the base backend's job to provide cross-node coordination. When the base does not implement Locker, this returns ErrDistributedLockingUnsupported so StorageService.WithLock drops to the next tier — AcquireSameHostLock below, and only then a process-local mutex.

func (*OverlayBackend) AcquireSameHostLock

func (o *OverlayBackend) AcquireSameHostLock(ctx context.Context, name string) (Unlocker, error)

AcquireSameHostLock delegates to the base backend's SameHostLocker when present, for the same reason AcquireLock delegates to its Locker: the override files are local copies of CA material, but the store the lock protects is the base backend's, so it is the base that must decide how processes exclude each other on it. When the base offers no same-host lock either, this returns ErrSameHostLockingUnsupported and StorageService.WithLock falls back to a process-local mutex.

func (*OverlayBackend) AppendLine

func (o *OverlayBackend) AppendLine(ctx context.Context, key string, data []byte, kind BlobKind) error

AppendLine rejects overridden keys — the override targets single blobs — and otherwise delegates.

func (*OverlayBackend) BaseDir

func (o *OverlayBackend) BaseDir() string

BaseDir implements PathProvider by delegating; overlay has no single root.

func (*OverlayBackend) CAKeyFile

func (o *OverlayBackend) CAKeyFile() string

CAKeyFile forwards to the base backend's, so that CheckKeyPermissions still finds a filesystem CA key when only other keys (ca_cert_file, say) are overridden. An overridden CA key is not reported: it is the configured file, not one the cadir holds.

func (*OverlayBackend) Close

func (o *OverlayBackend) Close() error

Close closes the base backend.

func (*OverlayBackend) Delete

func (o *OverlayBackend) Delete(ctx context.Context, key string) error

Delete removes the local file for an overridden key, wrapping fs.ErrNotExist when absent; otherwise delegates.

func (*OverlayBackend) EnsureReady

func (o *OverlayBackend) EnsureReady(ctx context.Context) error

EnsureReady prepares the base backend and ensures each override's parent directory exists. Operators supplying a pre-existing file still need to ensure the directory mode is acceptable; EnsureReady only creates the directory when missing.

func (*OverlayBackend) Exists

func (o *OverlayBackend) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether the overridden file exists, or delegates.

func (*OverlayBackend) Get

func (o *OverlayBackend) Get(ctx context.Context, key string) ([]byte, error)

Get reads an overridden key from its local file (returning fs.ErrNotExist when absent) or delegates to the base backend.

func (*OverlayBackend) KeyFilePaths

func (o *OverlayBackend) KeyFilePaths() []string

KeyFilePaths implements KeyFileLister by delegating, plus the CA key override if there is one. collectOverrides populates only KeyCACert and KeyCAKey, and of those only the key is material worth checking — ca_key_file is a local file the operator pointed the CA key at, which is exactly what this check is for. The base's own files still hold whatever was not overridden.

func (*OverlayBackend) List

func (o *OverlayBackend) List(ctx context.Context, prefix string) ([]string, error)

List always delegates: override keys are single-blob, not list-style.

func (*OverlayBackend) ModTime

func (o *OverlayBackend) ModTime(ctx context.Context, key string) (time.Time, error)

ModTime reports the local file mtime for overridden keys, or delegates.

func (*OverlayBackend) Path

func (o *OverlayBackend) Path(key string) string

Path implements PathProvider: returns the override path for overridden keys, or delegates to the base if it implements PathProvider.

func (*OverlayBackend) Put

func (o *OverlayBackend) Put(ctx context.Context, key string, data []byte, kind BlobKind) error

Put writes to the overridden file atomically (temp + rename) honouring kind for permissions, or delegates to the base backend.

func (*OverlayBackend) Unwrap

func (o *OverlayBackend) Unwrap() Backend

Unwrap returns the wrapped base backend, letting capability checks that don't have their own OverlayBackend forwarding method (e.g. InventoryStore) see through the wrapper to the concrete backend beneath it. Overriding only KeyCACert/KeyCAKey never touches the inventory, so it is always correct for such a check to consult base directly.

type PathProvider

type PathProvider interface {
	// Path returns the filesystem path for key, or empty if the key is
	// unknown to this backend.
	Path(key string) string
	// BaseDir returns the root directory under which keys are stored.
	BaseDir() string
}

PathProvider is an optional capability for backends that map keys onto a filesystem. Callers use this to obtain a physical path for diagnostic messages or legacy APIs that still deal in paths.

type RedisBackend

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

RedisBackend is a Backend implementation backed by a Redis- (or Valkey-) compatible server. Optionally uses Redis Sentinel for automatic failover.

Blob contents are wrapped with an 8-byte big-endian nanosecond mtime prefix (same encoding as the etcd backend) so ModTime answers from the same round-trip as Get. The certificate inventory is not stored as a blob: it is decomposed into per-entry hash fields (see redis_inventory.go), and the backend implements InventoryStore and CertIndex. AppendLine on any other key is performed server-side via a Lua script so concurrent appenders on different replicas do not lose lines. Distributed locks use SET NX PX with a per-acquisition token, a background heartbeat while the lock is held, and a token-matching Lua script on Unlock; this is sufficient for a single logical Redis/Sentinel-primary, which is the deployment this backend targets.

func NewRedisBackend

func NewRedisBackend(cfg RedisConfig) (*RedisBackend, error)

NewRedisBackend connects to a Redis/Valkey instance (or the primary behind a set of Sentinels) and returns a ready backend. The caller must call Close to release the underlying client.

func NewRedisBackendFromClient

func NewRedisBackendFromClient(client redis.UniversalClient, keyPrefix string, requestTimeout, lockTTL time.Duration) *RedisBackend

NewRedisBackendFromClient wraps an existing redis.UniversalClient. The backend does not take ownership and Close leaves the client open. Used by tests that need to share a single miniredis across backends.

func (*RedisBackend) AcquireLock

func (b *RedisBackend) AcquireLock(ctx context.Context, name string) (Unlocker, error)

AcquireLock obtains a distributed mutex under <prefix>:locks:<name> using SET NX PX with a per-acquisition token. Local goroutines racing on the same name are serialised by a per-name process-local mutex first, then the distributed lock is taken so only one process in the cluster holds the lock at a time. A heartbeat goroutine extends the TTL while the lock is held; Unlock stops it and deletes the lock if we still own it.

NB: Redis replication under Sentinel is asynchronous, so an in-flight failover can theoretically release a lock we still believe we hold. For `openvox-ca`'s workloads (CRL rotation, bootstrap, per-subject CSR serialisation) this narrow window is acceptable; operators needing stricter guarantees should prefer the etcd backend.

func (*RedisBackend) AppendEntry

func (b *RedisBackend) AppendEntry(ctx context.Context, rec CertRecord, newHead func(prev []byte) []byte) error

AppendEntry inserts rec and advances the integrity head atomically. The script rejects the append outright if rec's serial is already indexed (the cluster-wide duplicate-serial guarantee) and aborts it if the stored head is no longer the one newHead was computed from, which is the only way a concurrent appender — in this process or on another replica — can interfere. A nil newHead means integrity is disabled: there is then nothing to compute in Go, the script is the entire operation, and it cannot conflict.

func (*RedisBackend) AppendLine

func (b *RedisBackend) AppendLine(ctx context.Context, key string, data []byte, _ BlobKind) error

AppendLine atomically appends data to key. Concurrent appends from this process are serialised on appendMu; concurrent appends from other processes are resolved by a server-side Lua script that reads the current blob, appends, and writes back in a single atomic step. KeyInventory does not take this path: it is decomposed, and appending to it means adding entry fields (see redis_inventory.go).

func (*RedisBackend) ClearRevoked

func (b *RedisBackend) ClearRevoked(ctx context.Context, serial string) error

ClearRevoked returns the entry bearing serial to the signed state.

func (*RedisBackend) Close

func (b *RedisBackend) Close() error

Close releases the underlying Redis client when owned by this backend.

func (*RedisBackend) Delete

func (b *RedisBackend) Delete(ctx context.Context, key string) error

Delete removes key, wrapping fs.ErrNotExist when the key is absent. Deleting KeyInventory removes the marker and the decomposed structure.

func (*RedisBackend) EnsureReady

func (b *RedisBackend) EnsureReady(ctx context.Context) error

EnsureReady verifies connectivity with a PING (Redis has no directory concept so there is nothing to create), then decomposes a legacy inventory blob left by a pre-decomposition version of this backend into the per-entry structure. Decomposition must run before the inventory is used: the structured paths assume the blob key is only a presence marker.

func (*RedisBackend) Entries

func (b *RedisBackend) Entries(ctx context.Context) ([]InventoryEntry, error)

Entries returns every inventory entry in issuance order.

func (*RedisBackend) Exists

func (b *RedisBackend) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present.

func (*RedisBackend) Get

func (b *RedisBackend) Get(ctx context.Context, key string) ([]byte, error)

Get returns the (unwrapped) blob at key, wrapping fs.ErrNotExist when absent. The KeyInventory key is served from the decomposed entry fields (rendered to inventory.txt text) rather than a stored blob.

func (*RedisBackend) LatestSerialForSubject

func (b *RedisBackend) LatestSerialForSubject(ctx context.Context, subject string) (string, error)

LatestSerialForSubject returns the most recently issued serial for subject, wrapping fs.ErrNotExist when the subject has no entry. This is a single hash-field read of the by-subject index.

func (*RedisBackend) List

func (b *RedisBackend) List(ctx context.Context, prefix string) ([]string, error)

List returns the logical keys sharing prefix. Only csrPrefix and certPrefix are supported. Uses SCAN under the hood to avoid blocking the server.

func (*RedisBackend) ModTime

func (b *RedisBackend) ModTime(ctx context.Context, key string) (time.Time, error)

ModTime returns the wall-clock timestamp recorded when the blob was last written. Returns fs.ErrNotExist-wrapped when the key is absent.

func (*RedisBackend) PruneEntries

func (b *RedisBackend) PruneEntries(ctx context.Context, keep func(InventoryEntry) bool, advanceHead func(prev []byte, e InventoryEntry) []byte) ([]InventoryEntry, error)

PruneEntries removes the entries for which keep returns false, repoints the indices, and rewrites the integrity head — all in one script, so the entries and the head are never observably out of sync and a prune either happens or does not. The returned slice therefore only ever describes a completed removal, which is the strongest form of the PruneEntries contract (etcd, which cannot commit an arbitrary number of deletions atomically, takes the weaker batched form the same contract permits).

One call removes at most redisPruneMaxPerCall entries, oldest first; matches beyond that stay in the inventory, consistent and intact, for later calls.

func (*RedisBackend) Put

func (b *RedisBackend) Put(ctx context.Context, key string, data []byte, _ BlobKind) error

Put writes the blob at key. The BlobKind hint is recorded but has no effect on the stored form: Redis access control is managed server-side. Putting KeyInventory parses the text and replaces the decomposed entries.

func (*RedisBackend) SetProjection

func (b *RedisBackend) SetProjection(ctx context.Context, serial string, proj CertProjection) error

SetProjection fills the denormalised display fields for the entry bearing serial. Used to backfill records created from projection-less sources (legacy blob imports, direct AppendLine writes).

func (*RedisBackend) SetRevoked

func (b *RedisBackend) SetRevoked(ctx context.Context, serial string, at time.Time) error

SetRevoked marks the entry bearing serial as revoked at the given time. Idempotent: an already-revoked entry keeps its original revocation time. A serial with no entry is a no-op, not an error.

func (*RedisBackend) Statuses

func (b *RedisBackend) Statuses(ctx context.Context, stateFilter string) ([]CertRecord, error)

Statuses returns one record per subject that currently holds a stored signed certificate (the subject's latest issuance), in subject order, optionally narrowed to stateFilter. Like etcd — and unlike SQL — there is no indexed query to push the latest-per-subject fold into, so the whole entry hash is read and folded in Go; that is still a single round-trip, compared with the per-subject PEM read-and-parse the fallback path costs.

type RedisConfig

type RedisConfig struct {
	// Addrs is the list of Redis/Valkey instance addresses (host:port). In
	// direct mode the first address is used. Ignored when SentinelMasterName
	// is non-empty.
	Addrs []string

	// SentinelMasterName, if non-empty, switches the backend to Sentinel
	// mode: the client asks SentinelAddrs for the current primary and
	// follows failovers automatically.
	SentinelMasterName string
	// SentinelAddrs is the list of Sentinel addresses (host:port). Only
	// consulted when SentinelMasterName is set.
	SentinelAddrs []string
	// SentinelUsername / SentinelPassword authenticate to the Sentinels
	// themselves (distinct from the primary's auth, which uses Username /
	// Password).
	SentinelUsername string
	SentinelPassword string

	// DB selects the numeric logical database. Zero is fine for most
	// deployments and required for Redis Cluster-like routing.
	DB int
	// Username / Password authenticate to the Redis primary.
	Username string
	Password string
	// TLS, if non-nil, configures TLS for the connection.
	TLS *tls.Config

	// DialTimeout bounds the initial connection attempt. Zero uses 5s.
	DialTimeout time.Duration
	// RequestTimeout bounds per-request operations. Zero uses 5s.
	RequestTimeout time.Duration

	// KeyPrefix namespaces all keys. Defaults to "puppet-ca" when empty.
	// Redis convention uses ":" as a separator.
	KeyPrefix string

	// LockTTL is the time-to-live on acquired distributed locks. If the
	// holder process dies without Unlock, the lock releases automatically
	// after this interval. Zero uses 30s.
	LockTTL time.Duration
}

RedisConfig configures the Redis/Valkey-backed storage backend. Either Addrs or SentinelMasterName+SentinelAddrs must be set.

type RedisSpec

type RedisSpec struct {
	Addrs []string

	SentinelMasterName string
	SentinelAddrs      []string
	SentinelUsername   string
	SentinelPassword   string

	DB       int
	Username string
	Password string

	DialTimeoutSec    int
	RequestTimeoutSec int
	LockTTLSec        int

	KeyPrefix string

	TLSCAFile   string
	TLSCertFile string
	TLSKeyFile  string
}

RedisSpec is the config-friendly form of RedisConfig with TLS expressed as file paths rather than a preloaded tls.Config.

type SQLBackend

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

SQLBackend is a Backend implementation backed by a SQL database (SQLite, PostgreSQL, or MySQL/MariaDB). It stores every logical key as one row in a single key-value table and runs bun migrations on EnsureReady to create and version the schema.

AppendLine is made atomic with a per-process mutex plus a row-locking transaction (SELECT ... FOR UPDATE on engines that support it), so concurrent appenders — including separate replicas sharing one database — never lose lines. Distributed locking is provided per dialect via AcquireLock (PostgreSQL advisory locks, MySQL GET_LOCK); SQLite, being single-node, reports ErrDistributedLockingUnsupported. That is not the end of its locking: StorageService.WithLock then reaches AcquireSameHostLock, an flock(2) beside the database file that excludes another process on the same host.

func NewSQLBackend

func NewSQLBackend(cfg SQLConfig) (*SQLBackend, error)

NewSQLBackend opens a database connection according to cfg and returns a ready backend. The caller must call Close to release the connection pool.

func (*SQLBackend) AcquireInstanceLock

func (b *SQLBackend) AcquireInstanceLock() (Unlocker, error)

AcquireInstanceLock takes the store-wide lock permitting one running instance, in the same hidden directory beside the database file as the per-name same-host locks, and for the same reasons: the database file itself must not be flocked, and a locks table cannot be held open for a process lifetime on a single-connection pool.

A nil lock set is every dialect but SQLite — whose real distributed lock makes this rule inapplicable — and an in-memory database, which no second process can open in the first place.

func (*SQLBackend) AcquireLock

func (b *SQLBackend) AcquireLock(ctx context.Context, name string) (Unlocker, error)

AcquireLock obtains a cross-node distributed mutex named name. The mechanism is dialect-specific; SQLite is single-node and reports ErrDistributedLockingUnsupported, which sends StorageService.WithLock down to AcquireSameHostLock rather than straight to a process-local mutex.

func (*SQLBackend) AcquireSameHostLock

func (b *SQLBackend) AcquireSameHostLock(ctx context.Context, name string) (Unlocker, error)

AcquireSameHostLock takes the named lock as an exclusive flock(2) on a file in a hidden directory beside the SQLite database, so a `ctl` command and a running server on one host exclude each other. It reports ErrSameHostLockingUnsupported for every other dialect, whose real distributed lock WithLock takes first, and for an in-memory database.

A sidecar rather than a lock table, which the two obvious alternatives make unworkable:

  • The database file itself must not be flocked. SQLite locks it, and adding a second, independent locking scheme over the same file would leave two answers to "is this database busy" that nothing reconciles.
  • A locks table entered under BEGIN IMMEDIATE self-deadlocks. The SQLite pool is pinned to one connection (see NewSQLBackend), so a transaction held open for the duration of fn owns the only connection fn's own reads and writes need. Committing it immediately instead would leave nothing held for the duration that matters, which is the whole requirement.

The sidecar also keeps per-name granularity, which SQLite's single-writer model cannot express, and shares one implementation with the filesystem backend so the two cannot drift.

func (*SQLBackend) AppendEntry

func (b *SQLBackend) AppendEntry(ctx context.Context, rec CertRecord, newHead func(prev []byte) []byte) error

AppendEntry inserts rec and advances the integrity head atomically. The whole operation runs in one transaction that locks the presence-marker row, so concurrent appenders — including separate replicas — serialise and the hash chain cannot fork. newHead is invoked inside that transaction with the current head (nil when none); a nil newHead means integrity is disabled and the stored head is left untouched.

func (*SQLBackend) AppendLine

func (b *SQLBackend) AppendLine(ctx context.Context, key string, data []byte, kind BlobKind) error

AppendLine atomically appends data to key, creating it if absent. Appends from this process are serialised on appendMu; cross-replica concurrency is resolved by a row-locking transaction that reads, appends, and writes back the blob in one atomic step.

On MySQL/MariaDB the FOR UPDATE-then-insert pattern can raise an InnoDB deadlock (1213) when two connections race to create the same not-yet-existing row; InnoDB rolls one back as the victim. That is the expected, transient outcome, so the transaction is retried a bounded number of times.

func (*SQLBackend) ClearRevoked

func (b *SQLBackend) ClearRevoked(ctx context.Context, serial string) error

ClearRevoked returns every row bearing serial to the signed state.

func (*SQLBackend) Close

func (b *SQLBackend) Close() error

Close releases the underlying connection pool when owned by this backend.

func (*SQLBackend) Delete

func (b *SQLBackend) Delete(ctx context.Context, key string) error

Delete removes key, wrapping fs.ErrNotExist when the key is absent.

func (*SQLBackend) EnsureReady

func (b *SQLBackend) EnsureReady(ctx context.Context) error

EnsureReady verifies connectivity and brings the schema up to date by running the bun migrations. Safe to call multiple times, and safe to call from several processes at once: the run is serialised by the backend's distributed lock and the migrator records applied versions.

func (*SQLBackend) Entries

func (b *SQLBackend) Entries(ctx context.Context) ([]InventoryEntry, error)

Entries returns every inventory entry in issuance order.

func (*SQLBackend) Exists

func (b *SQLBackend) Exists(ctx context.Context, key string) (bool, error)

Exists reports whether key is present.

func (*SQLBackend) Get

func (b *SQLBackend) Get(ctx context.Context, key string) ([]byte, error)

Get returns the blob at key, wrapping fs.ErrNotExist when absent. The KeyInventory key is served from the structured inventory table (rendered to inventory.txt text) rather than the blob table.

func (*SQLBackend) KeyFilePaths

func (b *SQLBackend) KeyFilePaths() []string

KeyFilePaths implements KeyFileLister. Only SQLite has files of its own: the networked dialects keep the key in a database this process does not own and cannot stat, and their protection is the server's own, not a file mode.

func (*SQLBackend) LatestSerialForSubject

func (b *SQLBackend) LatestSerialForSubject(ctx context.Context, subject string) (string, error)

LatestSerialForSubject returns the most recently issued serial for subject, wrapping fs.ErrNotExist when the subject has no entry.

func (*SQLBackend) List

func (b *SQLBackend) List(ctx context.Context, prefix string) ([]string, error)

List returns the logical keys sharing prefix. Only csrPrefix and certPrefix are supported, matching the other backends.

func (*SQLBackend) ModTime

func (b *SQLBackend) ModTime(ctx context.Context, key string) (time.Time, error)

ModTime returns the timestamp recorded when the blob was last written, wrapping fs.ErrNotExist when the key is absent.

func (*SQLBackend) PruneEntries

func (b *SQLBackend) PruneEntries(ctx context.Context, keep func(InventoryEntry) bool, advanceHead func(prev []byte, e InventoryEntry) []byte) ([]InventoryEntry, error)

PruneEntries removes the rows for which keep returns false and rewrites the integrity head over the survivors in a single transaction, so a concurrent reader on another replica never observes the rows and the chained head out of sync, and a returned error always means nothing was removed. Survivors keep their original ids (and thus issuance order); only the dropped rows are deleted. The presence-marker row is locked first so this serialises with AppendEntry across replicas, exactly as appends do.

func (*SQLBackend) Put

func (b *SQLBackend) Put(ctx context.Context, key string, data []byte, kind BlobKind) error

Put stores data at key, inserting or replacing the row. The BlobKind hint is recorded in the kind column but does not affect access control, which is managed by the database server.

func (*SQLBackend) SetProjection

func (b *SQLBackend) SetProjection(ctx context.Context, serial string, proj CertProjection) error

SetProjection fills the denormalised display columns for every row bearing serial. Empty DNS names / auth extensions are stored as NULL, and IP SANs as ipAltNamesColumn encodes them, matching what AppendEntry writes for a fresh issuance.

func (*SQLBackend) SetRevoked

func (b *SQLBackend) SetRevoked(ctx context.Context, serial string, at time.Time) error

SetRevoked marks every row bearing serial as revoked at the given time. The state guard keeps the first recorded revocation time on repeat calls, and a serial with no rows is a no-op.

func (*SQLBackend) Statuses

func (b *SQLBackend) Statuses(ctx context.Context, stateFilter string) ([]CertRecord, error)

Statuses returns one record per subject that currently holds a stored signed certificate (the subject's latest issuance), in subject order, optionally narrowed to stateFilter. Blob existence is resolved with a single indexed key listing rather than a cross-table SQL join so the query stays dialect-free; historical rows for cleaned or superseded certificates are never returned.

type SQLConfig

type SQLConfig struct {
	// Dialect selects the SQL engine. Required.
	Dialect SQLDialect

	// DSN is the driver-specific data source name. For SQLite it is a file
	// path or "file:" URI; for PostgreSQL/MySQL it is the connection string
	// understood by the respective driver.
	DSN string

	// TLS, if non-nil, configures TLS for the networked dialects (PostgreSQL,
	// MySQL). Ignored by SQLite.
	TLS *tls.Config

	// RequestTimeout bounds each individual operation. Zero uses 10s.
	RequestTimeout time.Duration

	// MigrationTimeout bounds a whole migration run, replacing RequestTimeout for
	// the duration of EnsureReady. Zero uses 10 minutes.
	//
	// Configurable because the default is a guess about someone else's hardware:
	// the slowest legitimate run is an index build over an inventory whose size
	// this code cannot know, plus any wait for a peer replica holding the
	// migration lock. A run cut short is exactly what leaves a schema
	// half-migrated, so an operator who needs longer must be able to say so
	// without a code change.
	MigrationTimeout time.Duration

	// MaxOpenConns / MaxIdleConns tune the underlying database/sql pool. Zero
	// leaves the database/sql defaults in place, except SQLite which is pinned
	// to a single open connection (see NewSQLBackend).
	MaxOpenConns int
	MaxIdleConns int
}

SQLConfig configures an SQLBackend.

type SQLDialect

type SQLDialect string

SQLDialect selects which SQL engine an SQLBackend talks to. The same backend implementation drives every dialect; only DSN/driver selection, a few dialect-specific SQL clauses (upsert, row locking), and the distributed-lock mechanism differ.

const (
	// SQLitePure targets a single SQLite database file via the pure-Go
	// modernc.org/sqlite driver (no CGO). SQLite is single-node, so it does
	// not provide a distributed lock.
	SQLitePure SQLDialect = "sqlite"
	// SQLPostgres targets PostgreSQL.
	SQLPostgres SQLDialect = "postgres"
	// SQLMySQL targets MySQL or MariaDB.
	SQLMySQL SQLDialect = "mysql"
)

type SQLSpec

type SQLSpec struct {
	// DSN is the driver-specific data source name (a file path/URI for SQLite,
	// a connection string for PostgreSQL/MySQL).
	DSN string
	// DSNFile is the path to a file whose first line is the DSN, so a
	// password-bearing DSN need not appear in the process's arguments or
	// environment. Mutually exclusive with DSN; it is read when the backend
	// is opened, not for each connection.
	DSNFile string

	RequestTimeoutSec int
	// MigrationTimeoutSec bounds a whole schema-migration run rather than one
	// statement. Zero uses ten minutes.
	MigrationTimeoutSec int
	MaxOpenConns        int
	MaxIdleConns        int

	// TLS file paths apply to the networked dialects (PostgreSQL, MySQL); they
	// are ignored by SQLite.
	TLSCAFile   string
	TLSCertFile string
	TLSKeyFile  string
}

SQLSpec is the config-friendly form of SQLConfig with TLS expressed as file paths rather than a preloaded tls.Config. The same spec serves every SQL dialect; the dialect is chosen by BackendSpec.Kind.

type SameHostLocker

type SameHostLocker interface {
	AcquireSameHostLock(ctx context.Context, name string) (Unlocker, error)
}

SameHostLocker is an optional Backend capability that provides a mutex excluding other *processes on this host* — an `openvox-ca-ctl` command, or a second server — from the same named lock. It is a strictly weaker promise than Locker and a deliberately separate capability, not a second way to spell it.

The distinction is load-bearing. The single-node backends (filesystem, SQLite) can coordinate two processes sharing one host cheaply and soundly, but nothing about that extends across hosts: flock(2) over NFS is not a basis for clustering, and a caller deciding whether it is safe to run a second *replica* must not be told "yes" because a second *process* is handled. Backends therefore advertise the two capabilities independently, and a backend implementing this one must not be taken to implement Locker.

StorageService.WithLock prefers Locker and falls back to this, so a backend may implement both: the distributed lock already excludes same-host peers, and this capability is consulted only when the distributed one reports itself unsupported (SQLite's answer, and an overlay's over a base without one).

The returned Unlocker must be called exactly once, typically via defer.

type StorageService

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

StorageService provides the higher-level storage API used by the CA and API layers. It delegates all blob I/O to a pluggable Backend and handles inventory HMAC sequencing, append/read locks, and the per-subject private key directory (always local).

func New

func New(baseDir string) *StorageService

New constructs a StorageService backed by a filesystem rooted at baseDir. Per-subject generated private keys are stored in baseDir/private alongside the filesystem backend's other private files.

func NewServiceFromSpec

func NewServiceFromSpec(spec BackendSpec) (*StorageService, error)

NewServiceFromSpec constructs a StorageService according to spec. Returns an error when the backend cannot be initialised (e.g. etcd unreachable). The caller is responsible for calling s.Backend().Close() at shutdown.

func NewWithBackend

func NewWithBackend(backend Backend, localPrivateKeyDir string) *StorageService

NewWithBackend constructs a StorageService with an explicit backend and a local directory for per-subject private keys. The private key directory is always on the local filesystem regardless of the chosen backend.

func (*StorageService) AcquireInstanceLock

func (s *StorageService) AcquireInstanceLock(ctx context.Context, opts ...InstanceLockOption) (Unlocker, error)

AcquireInstanceLock takes the store-wide lock permitting exactly one running instance, and returns an Unlocker the caller must hold for as long as it is running.

It reports StoreLockedError when another process already holds the store, and a nil error in every case where the rule does not apply or cannot be enforced. Those two are not the same answer and the caller must not conflate them: only the error means "do not run".

The three no-op cases:

  • The backend has distributed locking. Multiple instances are a supported, designed-for configuration there, so there is nothing to enforce and this must not interfere with it.
  • The capability could not be determined. See below.
  • The backend has no instance lock to take: an in-memory SQLite database private to this process, a platform without flock(2), a store on a read-only mount. Warned about, then allowed, because refusing to start over a lock that is unavailable rather than held would take down a CA that worked before this check existed.

A caller that has already asked SupportsDistributedLocking may pass the answer with WithKnownDistributedLocking and skip the probe here; without it this method probes for itself, so it is always safe to call knowing nothing.

Releasing it

Release the lock AFTER closing the backend it protects, never before. Between the two, a second process that took the store would find this one still holding an open handle to it -- on SQLite a pooled connection to the very database file the lock exists to keep to one writer.

The mechanism differs by caller because their lifetimes do, and neither can borrow the other's: `openvox-ca` hangs the release off a runtime whose store-lifetime closer group runs in reverse, so it inserts the release at the front of that group (cmd/openvox-ca/runtime.go, holdInstanceLock). The runtime keeps a second, key-lifetime group that this rule has nothing to say about — it exists so the isolated signer can release the store and go on signing, and the instance lock belongs with the store it names. `openvox-ca-ctl` has no such group and returns one cleanup that does both in order (cmd/openvox-ca-ctl/migrate.go, lockStore). What they share is this rule and the spec helper that asserts it, testutil.RecordingBackend -- so the invariant is stated once here rather than argued twice there.

On a probe error it warns and permits, which is the safe direction here even though it reads like the unsafe one. The error path is unreachable for the backends this rule governs: FilesystemBackend implements no Locker at all, so the probe answers (false, nil); SQLite implements one but reports ErrDistributedLockingUnsupported, likewise (false, nil); and an OverlayBackend over either returns the same sentinel. A non-nil error can therefore only come from a backend that does have distributed locking and is momentarily unreachable — where refusing to start would be a restriction on precisely the deployments this rule exempts, and where the process will fail loudly on its own first locked operation anyway if the backend is really down.

func (*StorageService) AppendInventory

func (s *StorageService) AppendInventory(ctx context.Context, entry string) error

AppendInventory adds entry (a single inventory.txt line, without a trailing newline) to the inventory. entry must be in the canonical form that FormatInventoryLine builds; anything else is refused, even if it parses. On backends that implement InventoryStore the entry is stored as a structured record and the integrity head is advanced by a hash chain in O(1); otherwise the line is appended to the KeyInventory blob and the whole-blob HMAC is recomputed. Returns ErrDuplicateSerial (wrapped) if the entry's serial is already present anywhere in the inventory.

func (*StorageService) AppendInventoryRecord

func (s *StorageService) AppendInventoryRecord(ctx context.Context, entry string, proj *CertProjection) error

AppendInventoryRecord is AppendInventory with an optional certificate-index projection. Issuance paths (signing, import) pass the display fields denormalised from the certificate they just stored; backends with the CertIndex capability persist them on the new row (state "signed"), all others ignore them. A nil proj records the entry without a projection, which index readers treat as "fall back to the stored PEM".

func (*StorageService) Backend

func (s *StorageService) Backend() Backend

Backend returns the underlying Backend. Exposed for advanced use cases (diagnostic output, backend-specific tuning). Most callers should prefer the higher-level methods on StorageService.

func (*StorageService) CACertPath

func (s *StorageService) CACertPath() string

func (*StorageService) CADir

func (s *StorageService) CADir() string

CADir returns the filesystem root of the backend, or "" for non-filesystem backends.

func (*StorageService) CAKeyPath

func (s *StorageService) CAKeyPath() string

func (*StorageService) CAPubKeyPath

func (s *StorageService) CAPubKeyPath() string

func (*StorageService) CRLModTime

func (s *StorageService) CRLModTime(ctx context.Context) (time.Time, error)

CRLModTime returns the last-modified time of the CRL blob, for If-Modified-Since handling. Backends that don't track mtime return zero.

func (*StorageService) CRLPath

func (s *StorageService) CRLPath() string

func (*StorageService) CSRDir

func (s *StorageService) CSRDir() string

CSRDir returns the directory where pending CSRs are stored (filesystem backend only).

func (*StorageService) CSRExists

func (s *StorageService) CSRExists(ctx context.Context, subject string) (bool, error)

CSRExists reports whether a pending CSR exists for subject, returning the backend's error rather than reading it as absence. See CertExists.

func (*StorageService) CertExists

func (s *StorageService) CertExists(ctx context.Context, subject string) (bool, error)

CertExists reports whether a signed certificate exists for subject. Unlike HasCert it returns the backend's error rather than reading it as absence, for a caller whose refusal depends on the answer.

func (*StorageService) CertStatuses

func (s *StorageService) CertStatuses(ctx context.Context, stateFilter string) (records []CertRecord, ok bool, err error)

CertStatuses answers the certificate-status listing from the certificate index. ok reports whether the backend has the capability at all; when false the caller must fall back to enumerating and parsing the stored PEMs. stateFilter narrows the records to CertStateSigned or CertStateRevoked; "" returns everything the index tracks.

func (*StorageService) CheckKeyPermissions

func (s *StorageService) CheckKeyPermissions(extra ...string) []KeyPermWarning

CheckKeyPermissions reports every file holding key material whose permissions are wider than 0600. That is the reporting threshold, not the expectation: group access is wider than 0600 and is tolerated, so what comes back is a list of findings to judge rather than a list of faults. The caller draws the line -- KeyPermWarning.WorldAccessible is refused, group access is logged, and a mode that could not be read is refused on its own terms. Four sources: every file in the local private-key directory; the filesystem backend's CA key, which sits at the top of the cadir unless the cadir predates that and keeps it in private/ (see caKeyFiler); any files the backend itself declares through KeyFileLister — the SQLite database and its sidecars, which hold the CA key as a blob; and any extra paths the caller names, for secrets it configures that the store knows nothing about.

The private-key directory is judged whole rather than by filename. It is the directory the CA keeps its secrets in, so its contents are secret by construction: as well as the per-subject "<subject>_key.pem" keys it holds the inventory-integrity HMAC key, which does not end in "_key.pem". A suffix test exempted it from a refusal whose whole subject is key material, and a world-readable HMAC key lets any local account forge inventory MACs.

Judging the directory rather than a pattern is also what makes this robust to the next secret put there, which is the property a suffix test cannot have: an earlier revision of this comment justified the sweep partly by a generated CA key passphrase, and that file stopped existing without the argument needing to change.

This reports; it does not correct. Nothing in openvox-ca changes the mode of a file it did not create, so a finding here is a condition the operator has to resolve, and the caller decides whether it is fatal. Use KeyPermWarning.WorldAccessible to tell the two severities apart: group access is expected under a Kubernetes fsGroup, world access is not expected anywhere.

func (*StorageService) ClearCertRevoked

func (s *StorageService) ClearCertRevoked(ctx context.Context, serial string) error

ClearCertRevoked removes a revocation projection from the certificate index; no-op when the backend has no index.

func (*StorageService) DeleteCSR

func (s *StorageService) DeleteCSR(ctx context.Context, subject string) error

func (*StorageService) DeleteCert

func (s *StorageService) DeleteCert(ctx context.Context, subject string) error

func (*StorageService) EnsureDirs

func (s *StorageService) EnsureDirs(ctx context.Context) error

EnsureDirs prepares the backend and the local private-key directory for use.

func (*StorageService) EnsureHMACKey

func (s *StorageService) EnsureHMACKey(ctx context.Context) ([]byte, error)

EnsureHMACKey loads or generates the HMAC key used for inventory integrity. The key is stored via the backend under KeyHMACKey.

A transient backend error (network blip, deadline exceeded, ...) is distinguished from a genuine "not present" via fs.ErrNotExist; otherwise a momentary failure on Get would silently regenerate the key and invalidate every existing inventory MAC.

Generation is a read-modify-write, so it runs under WithLock(lockNameHMACKey) and reads the key *again* after winning the lock. Without that, two replicas cold-starting against a fresh shared backend both see the key absent, both generate and both Put: last write wins, and the loser goes on to MAC its inventory under a key no other replica can reproduce. The second read is the half that matters — the lock only orders the two attempts, and it is the re-read that makes the loser adopt the winner's key rather than write over it.

The lock is taken only on the path that would write. A store whose key is already present *and of the expected length* takes no lock at all, so every restart after the first still costs one Get and no cross-replica round trip. A present-but-wrong-length blob is not that case: it regenerates, and so it locks.

How much of a cross-replica promise that lock is depends on the backend, and WithLock's tiers are the whole answer: etcd, Redis and the server SQL dialects exclude every replica; filesystem and SQLite exclude every process on the host; an in-memory SQLite database or a platform without flock(2) falls back to a process-local mutex. Read that last tier as single-*process*, not single-node: an in-memory SQLite database really is private to this process, but a filesystem store on a platform without flock(2) (Windows, AIX, Solaris, js/wasm — see filelock_other.go) is not, and two openvox-ca processes over one cadir there can still fork the key. Across hosts the question does not arise for either: shared storage is unsupported for them, as docs/storage-backends.md scopes it.

ctx bounds the wait for the lock, but only its cross-process half; see WithLock. Callers that must not hang on a peer's cold start should pass a deadline, as ca.Init does.

func (*StorageService) GetCACert

func (s *StorageService) GetCACert(ctx context.Context) ([]byte, error)

func (*StorageService) GetCAKey

func (s *StorageService) GetCAKey(ctx context.Context) ([]byte, error)

func (*StorageService) GetCRL

func (s *StorageService) GetCRL(ctx context.Context) ([]byte, error)

func (*StorageService) GetCSR

func (s *StorageService) GetCSR(ctx context.Context, subject string) ([]byte, error)

func (*StorageService) GetCert

func (s *StorageService) GetCert(ctx context.Context, subject string) ([]byte, error)

func (*StorageService) GetSerial

func (s *StorageService) GetSerial(ctx context.Context) ([]byte, error)

func (*StorageService) GetSuperseded

func (s *StorageService) GetSuperseded(ctx context.Context) ([]byte, error)

GetSuperseded returns the stored list of certificates awaiting delayed revocation, wrapping fs.ErrNotExist when no supersession has ever been recorded. The bytes are opaque here; ca.CA owns the encoding.

Callers must serialise their read-modify-write on the cluster "crl" lock — this mutex only orders goroutines inside one process, and the list is shared across replicas. See ca.CA.ReconcileSuperseded.

func (*StorageService) HMACKeyPath

func (s *StorageService) HMACKeyPath() string

func (*StorageService) HasCACert

func (s *StorageService) HasCACert(ctx context.Context) (bool, error)

func (*StorageService) HasCAKey

func (s *StorageService) HasCAKey(ctx context.Context) (bool, error)

func (*StorageService) HasCSR

func (s *StorageService) HasCSR(ctx context.Context, subject string) bool

HasCSR reports whether a pending CSR exists for subject.

func (*StorageService) HasCert

func (s *StorageService) HasCert(ctx context.Context, subject string) bool

HasCert reports whether a signed certificate exists for subject.

func (*StorageService) HasInventory

func (s *StorageService) HasInventory(ctx context.Context) (bool, error)

func (*StorageService) HasSerial

func (s *StorageService) HasSerial(ctx context.Context) (bool, error)

func (*StorageService) InitHMAC

func (s *StorageService) InitHMAC(ctx context.Context) error

InitHMAC loads or generates the inventory HMAC key and verifies the existing inventory. Call this once during CA initialisation.

func (*StorageService) InventoryEntries

func (s *StorageService) InventoryEntries(ctx context.Context) ([]InventoryEntry, error)

InventoryEntries returns every inventory entry in issuance order, verifying the stored integrity value before returning them.

The structured twin of ReadInventory, for a caller that wants the entries rather than the rendered blob — and the one to reach for on a timer. ReadInventory verifies and *then* fetches, and its verification recomputes from storage, so every call materialises the whole inventory twice: on a blob backend two full blob reads, and on an InventoryStore backend a full row fetch plus a hash chain followed by every row again through the render shim. This fetches once and folds the integrity value over what it already holds, so the cost is one materialisation plus the small stored-MAC read, on every backend family.

Verification is not skipped anywhere, which is the difference between this and SubjectForSerial: that method declines to verify on InventoryStore backends precisely because doing so "would cost a second full fetch of every row", and here it costs no fetch at all. The distinction matters for this caller, which drives removals — a deleted row silently downgrades the OCSP responder's answer for that serial from revoked to unknown and evicts the pre-signed response, so tampering must fail closed rather than be absorbed.

func (*StorageService) InventoryIntegrityReport

func (s *StorageService) InventoryIntegrityReport(ctx context.Context) (InventoryIntegrityReport, error)

InventoryIntegrityReport describes the inventory's integrity state without verifying it and without writing anything.

It exists because every ordinary read path is fail-closed: ReadInventory and InventoryEntries return ErrInventoryTampered on a mismatch, which is correct for serving and useless for diagnosis. An operator whose CA will not start needs to see what does not verify *before* deciding whether to re-assert it, and the fail-closed paths will not show them.

What it deliberately cannot answer: which entry diverged. The backends persist one head MAC (KeyInventoryHMAC) and no per-entry value — an inventory row carries the four canonical columns plus a display projection, none of them a MAC — so nothing records what any prefix should have hashed to. Localising a divergence would need a schema change, and a report that implied otherwise would be inviting an operator to trust a bisection it never performed. See docs/development/inventory-store.md for the row's shape; do not re-enumerate the columns here, which is how this comment was wrong once already (read off the initial migration rather than the current model).

func (*StorageService) InventoryPath

func (s *StorageService) InventoryPath() string

func (*StorageService) LatestSerialForSubject

func (s *StorageService) LatestSerialForSubject(ctx context.Context, subject string) (string, error)

LatestSerialForSubject returns the most recently issued serial for subject. On InventoryStore backends this is an indexed lookup; otherwise it scans the inventory blob (verifying its HMAC first, via ReadInventory). Wraps os.ErrNotExist when the subject has no entry.

func (*StorageService) ListCSRs

func (s *StorageService) ListCSRs(ctx context.Context) ([]string, error)

ListCSRs returns the subject names of all pending certificate requests.

func (*StorageService) ListCerts

func (s *StorageService) ListCerts(ctx context.Context) ([]string, error)

ListCerts returns the subject names of all signed certificates.

func (*StorageService) MarkCertRevoked

func (s *StorageService) MarkCertRevoked(ctx context.Context, serial string, at time.Time) error

MarkCertRevoked projects a revocation into the certificate index; no-op when the backend has no index.

func (*StorageService) PrivateKeyPath

func (s *StorageService) PrivateKeyPath(subject string) string

PrivateKeyPath returns the filesystem path to subject's server-generated private key. Private keys are always stored on the local filesystem.

func (*StorageService) PruneInventory

func (s *StorageService) PruneInventory(ctx context.Context, keep func(InventoryEntry) bool) ([]InventoryEntry, error)

PruneInventory removes every inventory entry for which keep returns false, rewriting the inventory and its integrity head together under the inventory write lock. It returns the removed entries (in issuance order) so the caller can act on them — drop their CRL revocations, invalidate caches, delete the stored cert. The returned slice is authoritative even when err is non-nil: any path that has durably removed entries before failing still returns them, so the caller can finish cleaning up after them. A backend may bound how much one call removes (see the PruneEntries contract); deferred matches stay in the inventory for later calls. When nothing is removed the inventory and head are left untouched and (nil, nil) is returned.

The current inventory integrity is verified before pruning, so a tampered inventory surfaces ErrInventoryTampered rather than being silently rewritten.

Concurrency: appends (AppendInventory) and reads (ReadInventory) take the same inventoryMu, so within a process a prune never interleaves with them. Structured backends prune through PruneEntries (see the contract in backend.go: SQL in one transaction, redis in one atomic script, etcd in individually-consistent batches); the blob fallback below rewrites the whole inventory with a single Backend.Put, which blob backends service as an atomic file swap. Callers needing cross-replica serialisation against revocation should hold the cluster CRL lock around this (see ca.CA.CleanupExpiredCerts).

func (*StorageService) ReadInventory

func (s *StorageService) ReadInventory(ctx context.Context) ([]byte, error)

func (*StorageService) RebuildInventoryHMAC

func (s *StorageService) RebuildInventoryHMAC(ctx context.Context) error

RebuildInventoryHMAC recomputes the inventory integrity head from the current inventory contents using the stored HMAC key, and writes it.

Two callers, with different reasons. After a migration: the destination's integrity scheme (whole-blob HMAC vs. the structured backends' hash chain) may differ from the source's, so the copied inventory_hmac value is not meaningful for the destination and must be recomputed. And from the offline "openvox-ca rebuild-inventory-hmac", as the supported repair for a CA whose stored value has stopped verifying — there it re-asserts integrity over the inventory as it stands rather than verifying anything, which is why that command gates it behind an explicit confirmation.

It is a no-op when no HMAC key is present (a CA that never initialised integrity), leaving the store untouched. That branch is contractual, not incidental: the CLI checks the same condition first and refuses, because a silent no-op here would report a repair it did not perform.

func (*StorageService) SaveCACert

func (s *StorageService) SaveCACert(ctx context.Context, data []byte) error

func (*StorageService) SaveCAKey

func (s *StorageService) SaveCAKey(ctx context.Context, data []byte) error

func (*StorageService) SaveCAPubKey

func (s *StorageService) SaveCAPubKey(ctx context.Context, data []byte) error

func (*StorageService) SaveCSR

func (s *StorageService) SaveCSR(ctx context.Context, subject string, pemData []byte) error

func (*StorageService) SaveCert

func (s *StorageService) SaveCert(ctx context.Context, subject string, pemData []byte) error

func (*StorageService) SavePrivateKey

func (s *StorageService) SavePrivateKey(ctx context.Context, subject string, pemData []byte) error

SavePrivateKey persists a server-generated private key for subject. The key is always written to the local filesystem, never the configured backend.

func (*StorageService) SaveSuperseded

func (s *StorageService) SaveSuperseded(ctx context.Context, data []byte) error

SaveSuperseded replaces the stored list of certificates awaiting delayed revocation. See GetSuperseded for the locking the caller still owes.

func (*StorageService) SerialExists

func (s *StorageService) SerialExists(ctx context.Context, serial string) (bool, error)

SerialExists reports whether any inventory entry — for any subject, current or historical — already carries the given serial number. This is a best-effort, non-authoritative check: callers needing a real guarantee must rely on AppendInventory's own atomic duplicate check (ErrDuplicateSerial), not this method, since SerialExists does not hold inventoryMu across its caller's subsequent write.

func (*StorageService) SerialPath

func (s *StorageService) SerialPath() string

func (*StorageService) SetCertProjection

func (s *StorageService) SetCertProjection(ctx context.Context, serial string, proj CertProjection) error

SetCertProjection backfills the denormalised display fields for serial in the certificate index; no-op when the backend has no index.

func (*StorageService) SignedDir

func (s *StorageService) SignedDir() string

SignedDir returns the directory where signed certificates are stored (filesystem backend only).

func (*StorageService) SubjectForSerial

func (s *StorageService) SubjectForSerial(ctx context.Context, serial string) (string, error)

SubjectForSerial returns the subject of the inventory entry carrying serial, current or historical. Wraps fs.ErrNotExist when no entry carries it, and returns an error for a serial that is not hexadecimal.

Unlike SerialExists, the comparison is on the *normalised* value (uppercase hex, no leading zeros) rather than the stored string. SerialExists can insist on an exact match because both sides are written by this CA in one format (a blob inventory's lines, OpenVox Server's included, are normalised as read); a serial reaching this method was typed by an operator, who may reasonably write it in the lowercase, zero-padded or colon-free form some other tool printed. Normalising here is also what lets a modern random serial and a zero-padded sequential one from an older inventory be looked up the same way.

Integrity matches LatestSerialForSubject, the by-subject lookup this is the twin of: on a blob backend the HMAC is verified before the scan, so an inventory whose rows were altered surfaces ErrInventoryTampered rather than answering from it. The guarantee is exactly as strong as the stored MAC's presence — verifyInventoryHMACLocked treats an absent one as first-run and re-baselines over whatever is there, so deleting the MAC blob alongside the edit still verifies clean. That is a property of the shared verifier, not of this path (LatestSerialForSubject inherits it too), and closing it would mean a read-only verify mode for every caller. It is left alone here rather than papered over: the barrier stops an edited inventory, not an edited inventory whose sibling MAC was also removed. That matters more here than for a plain read — the answer decides whether a serial may be revoked at all, and which subject's stored certificate the live certificate guard compares against, so an unverified row could both admit a serial this CA never issued (a CRL entry no expiry sweep can ever remove) and point the guard at the wrong certificate. InventoryStore backends are not verified here, exactly as LatestSerialForSubject does not verify them: their integrity head is advanced atomically per append rather than recomputed over a blob, and re-verifying would cost a second full fetch of every row.

The scan is linear in the inventory. An indexed by-serial lookup is NOT available even on backends that have the index: the schema's unique index on serial is an exact-match index over the stored text, while this lookup must match on the normalised value, because an inventory written by an older version — or migrated from Puppet Server — carries zero-padded sequential serials (see buildSerialIndex's comment in internal/ca/ocsp.go). An indexed exact match would silently miss precisely the historical certificates most likely to need retiring. A fast path that tried the canonical rendering first and fell back to this scan would be sound; it is deliberately left for later, since this answers an operator-initiated single revocation rather than a hot path, and on blob backends the verification above reads everything regardless.

func (*StorageService) SupportsAtomicInventory

func (s *StorageService) SupportsAtomicInventory() bool

SupportsAtomicInventory reports whether AppendInventory is atomic with respect to writers in other processes.

Only structured (InventoryStore) backends are: they append a row and advance the integrity chain in one transaction. Blob backends read the whole inventory, append, and rewrite an HMAC computed over their own reconstruction, so two concurrent appenders leave an HMAC covering a blob that never existed — which fails the integrity check at the next startup.

Needed as a method because asInventoryStore unwraps OverlayBackend, so a caller-side type assertion would answer "no" for a SQL backend that happens to be wrapped by ca_cert_file/ca_key_file.

func (*StorageService) SupportsDistributedLocking

func (s *StorageService) SupportsDistributedLocking(ctx context.Context) (bool, error)

SupportsDistributedLocking reports whether WithLock actually coordinates across processes for the configured backend.

This deliberately does NOT answer `_, ok := backend.(Locker)`, which is a different and misleading question. SQLBackend implements Locker but reports ErrDistributedLockingUnsupported for SQLite, and OverlayBackend implements it but delegates to a base that may not — so a type assertion says "yes" for SQLite and for any backend an overlay wraps over a filesystem base, both of which fall through to a process-local mutex. Callers that use this to decide whether it is safe to run a second process against the same storage would be told exactly the wrong thing.

Instead it reproduces WithLock's decision by making the same AcquireLock call and classifying the outcome the same way, releasing the lock immediately. The probe cannot live inside WithLock: that would add a lock round trip to every Sign. Keeping the two in step is a test's job (see the storage suite), not the type system's.

The three outcomes are distinct, and the error case matters: WithLock treats a non-sentinel AcquireLock failure as fatal, so reporting it as "false" would tell an operator their backend does not do distributed locking when the truth is that it is unreachable.

func (*StorageService) TouchInventory

func (s *StorageService) TouchInventory(ctx context.Context) error

TouchInventory creates an empty inventory blob if one does not already exist. Called during CA bootstrap and import to seed the inventory.

func (*StorageService) UpdateCRL

func (s *StorageService) UpdateCRL(ctx context.Context, pemData []byte) error

UpdateCRL stores the CRL as a public blob. It is served to anyone without authentication, and OpenVox Server writes ca_crl.pem world-readable too, so a re-sign on a cadir the two share leaves it readable to whatever else reads it there.

func (*StorageService) UpdateInventoryHMAC

func (s *StorageService) UpdateInventoryHMAC(ctx context.Context, hmacKey []byte) error

UpdateInventoryHMAC recomputes and writes the HMAC for the current inventory. It is safe to call externally (e.g. after migrating an existing inventory).

func (*StorageService) VerifyInventoryHMAC

func (s *StorageService) VerifyInventoryHMAC(ctx context.Context, hmacKey []byte) error

VerifyInventoryHMAC checks the inventory against its stored HMAC. Returns ErrInventoryTampered on mismatch, or establishes a baseline HMAC when none is stored (see baselineInventoryHMACLocked for how loudly).

func (*StorageService) WithLock

func (s *StorageService) WithLock(ctx context.Context, name string, fn func() error) error

WithLock runs fn while holding the named lock, taking the strongest lock the backend offers. Release always starts when fn returns, including on panic; if it fails, a backend may finish it in the background (etcd keeps the name held in this process until it does, see docs/development/locking.md). Three tiers, tried in order:

  1. Locker — coordinated across every replica sharing the backend (etcd, Redis, PostgreSQL, MySQL).
  2. SameHostLocker — coordinated across every process on this host, an flock(2) on the single-node backends (filesystem, SQLite). Enough to stop an `openvox-ca-ctl` command corrupting a running server's state; no promise at all across hosts, which is what those backends are scoped to.
  3. A process-local named mutex, for a backend offering neither.

Names should be stable and descriptive (e.g. "bootstrap", "crl", "subject:<name>") since all callers using the same name contend on the same lock.

ctx bounds only the *other-process* half of an acquisition. Callers inside one process serialise on a plain mutex first — the tier-3 fallback below, and inside each tier-1/tier-2 implementation's own acquisition — and sync.Mutex.Lock takes no context. A deadline therefore caps how long this waits for another replica or another process, not for another goroutine here, which is why an inverted lock order deadlocks rather than timing out. See docs/development/locking.md.

For the same reason WithLock is *not reentrant*, at any tier: re-acquiring a name this goroutine already holds blocks on a mutex only this goroutine can release, and no deadline ends that wait, so it hangs rather than failing. Work that must run under a lock the caller may already hold belongs in a ...Locked variant the caller selects — CA.finishLoadExisting takes its seeding function from its caller for exactly this reason (issue #201).

func (*StorageService) WriteSerial

func (s *StorageService) WriteSerial(ctx context.Context, val string) error

type StoreLockedError

type StoreLockedError struct {
	// Path is the lock file the refusal came from.
	Path string
	// Holder describes the process holding it, as that process recorded
	// itself. Empty when the record was missing or unreadable.
	Holder string
	// HolderUnverified is set when the lock file was group-writable, so the
	// record may have been written by any member of the store's group rather
	// than by the process holding the lock; see lockFilePerm.
	HolderUnverified bool
}

StoreLockedError reports that another process already holds the store's instance lock, and names it. Holder is what that process recorded about itself, and is empty when the record could not be read.

A distinct type rather than a formatted string so callers can tell "somebody else is running" from "the lock could not be taken", and so tests assert on the condition rather than on wording.

func (*StoreLockedError) Error

func (e *StoreLockedError) Error() string

type Unlocker

type Unlocker interface {
	Unlock() error
}

Unlocker releases a lock previously acquired via Locker.AcquireLock.

Jump to

Keyboard shortcuts

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