secrets

package
v1.0.0-rc07 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package secrets provides multi-cluster secrets management for openCenter-cli.

This package implements comprehensive secrets lifecycle management including:

  • Secrets synchronization between config files and encrypted manifests
  • Drift detection and validation between source-of-truth and deployed secrets
  • Key rotation with dual-key transition support
  • Key expiration tracking and monitoring
  • Key revocation for users and compromised keys
  • Pre-commit validation hooks for Git repositories
  • Multi-cluster operations with parallel processing
  • Audit logging for all key operations

Architecture

The package follows a layered architecture:

┌─────────────────────────────────────────────────────────────────┐
│                    CLI Commands (cmd/)                          │
│  sync, validate, rotate keys, check keys, etc.                  │
└─────────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────────┐
│                    Service Layer (this package)                 │
│  SecretsManager, KeyRegistry, KeyRotator, KeyRevoker, etc.      │
└─────────────────────────────────────────────────────────────────┘
                              │
┌─────────────────────────────▼───────────────────────────────────┐
│                    Data Layer                                   │
│  Config files, Key Registry, Encrypted Manifests, Audit Log     │
└─────────────────────────────────────────────────────────────────┘

Core Interfaces

SecretsManager handles secrets synchronization and drift detection:

manager := secrets.NewSecretsManager(sopsManager, registry, logger)
result, err := manager.SyncSecrets(ctx, secrets.SyncOptions{
    Cluster:  "my-cluster",
    Services: []string{"harbor", "keycloak"},
    DryRun:   true,
})

KeyRegistry manages key metadata and lifecycle:

registry := secrets.NewKeyRegistry(registryPath, sopsManager)
report, err := registry.CheckExpiration(ctx, 14) // Warn 14 days before expiry

KeyRotator handles key rotation with dual-key support:

rotator := secrets.NewKeyRotator(registry, sopsManager, logger)
result, err := rotator.RotateAgeKey(ctx, secrets.RotateOptions{
    Cluster: "my-cluster",
    DryRun:  false,
})

KeyRevoker handles key revocation:

revoker := secrets.NewKeyRevoker(registry, sopsManager, logger)
result, err := revoker.RevokeByUser(ctx, secrets.RevokeOptions{
    Cluster: "my-cluster",
    User:    "user@example.com",
})

Error Handling

The package defines specific error types for secrets operations:

  • ErrConfigNotFound: Config file does not exist
  • ErrKeyNotFound: Age or SSH key not found
  • ErrDecryptionFailed: Cannot decrypt manifest
  • ErrEncryptionFailed: Cannot encrypt manifest
  • ErrRegistryCorrupted: Key registry is invalid
  • ErrRotationInProgress: Dual-key rotation incomplete
  • ErrSingleKeyRevocation: Attempting to revoke only key

All errors include suggestions for resolution and support the errors.StructuredError interface for consistent error handling.

Key Registry

The key registry is stored as a SOPS-encrypted YAML file at secrets/key-registry.yaml and tracks:

  • Key fingerprints and public keys
  • Creation and expiration dates
  • Key status (active, archived, revoked)
  • Usage information (which paths use each key)

Audit Logging

All key operations are logged to the audit log with:

  • Timestamp and actor information
  • Event type (key.generated, key.rotated, key.revoked, etc.)
  • Key fingerprint and cluster
  • HMAC signatures for tamper detection

Thread Safety

All interfaces in this package are designed to be safe for concurrent use. The KeyRegistry uses file locking to prevent concurrent modifications.

Index

Constants

View Source
const (
	// DefaultAgeExpirationDays is the default expiration period for Age keys (90 days)
	DefaultAgeExpirationDays = 90

	// DefaultSSHExpirationDays is the default expiration period for SSH keys (180 days)
	DefaultSSHExpirationDays = 180

	// RegistryFileName is the name of the key registry file
	RegistryFileName = "key-registry.yaml"
)

Variables

This section is empty.

Functions

func IsKeyNotFoundError

func IsKeyNotFoundError(err error) bool

IsKeyNotFoundError checks if an error is or wraps an ErrKeyNotFound.

func IsNoReachablePrivateKeyError

func IsNoReachablePrivateKeyError(err error) bool

IsNoReachablePrivateKeyError checks if an error is or wraps ErrNoReachablePrivateKey.

func IsPrimaryKeyRevocationError

func IsPrimaryKeyRevocationError(err error) bool

IsPrimaryKeyRevocationError checks if an error is or wraps ErrPrimaryKeyRevocation.

func IsRegistryDriftError

func IsRegistryDriftError(err error) bool

IsRegistryDriftError checks if an error is or wraps ErrRegistryDriftDetected.

func NewKeyNotFoundError

func NewKeyNotFoundError(cluster string, keyType KeyType, cause error) error

NewKeyNotFoundError creates a new ErrKeyNotFound error.

func NewRegistryCorruptedError

func NewRegistryCorruptedError(path string, cause error) error

NewRegistryCorruptedError creates a new ErrRegistryCorrupted error.

Types

type AuditLogger

type AuditLogger interface {
	LogSecretsSync(ctx context.Context, actor, cluster string, filesCreated, filesUpdated, filesUnchanged int) error
	LogSecretsSyncFailed(ctx context.Context, actor, cluster, reason string) error
	LogDriftDetected(ctx context.Context, actor, cluster string, driftCount, missingCount, orphanedCount int) error
	LogSecretsValidated(ctx context.Context, actor, cluster string) error
	LogKeyRotated(ctx context.Context, actor, keyType, resource string) error
	LogKeyRevoked(ctx context.Context, actor, cluster, keyFingerprint, revokedUser string, filesReencrypted int) error
	LogKeyRevocationFailed(ctx context.Context, actor, cluster, keyFingerprint, reason string) error
}

AuditLogger defines the interface for audit logging operations. This interface is satisfied by security.AuditLogger.

type DefaultHookManager

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

DefaultHookManager implements the HookManager interface. It provides methods for installing and managing Git pre-commit hooks that validate secrets before commits.

func NewDefaultHookManager

func NewDefaultHookManager(
	secretsManager SecretsManager,
	logger *slog.Logger,
) *DefaultHookManager

NewDefaultHookManager creates a new DefaultHookManager with the given dependencies.

Parameters:

  • secretsManager: Manager for secrets validation operations
  • logger: Logger for operation tracking

Returns:

  • *DefaultHookManager: A new hook manager instance

func (*DefaultHookManager) InstallHooks

func (h *DefaultHookManager) InstallHooks(ctx context.Context, repoPath string, cluster string) error

InstallHooks installs pre-commit hooks in the repository. The hooks validate staged files for unencrypted secrets and drift.

func (*DefaultHookManager) UninstallHooks

func (h *DefaultHookManager) UninstallHooks(ctx context.Context, repoPath string) error

UninstallHooks removes installed hooks from the repository.

func (*DefaultHookManager) ValidatePreCommit

func (h *DefaultHookManager) ValidatePreCommit(ctx context.Context, stagedFiles []string) (*HookResult, error)

ValidatePreCommit runs pre-commit validation on staged files. Returns a HookResult indicating whether the commit should proceed.

type DefaultKeyReconciler

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

DefaultKeyReconciler reconciles SOPS Age recipients with registry metadata.

func NewDefaultKeyReconciler

func NewDefaultKeyReconciler(registry KeyRegistry, secretsManager SecretsManager, logger *slog.Logger) *DefaultKeyReconciler

NewDefaultKeyReconciler creates a key reconciler with the given dependencies.

func (*DefaultKeyReconciler) Reconcile

func (r *DefaultKeyReconciler) Reconcile(ctx context.Context, cluster string, apply bool) (*ReconcileReport, error)

Reconcile compares a cluster's .sops.yaml recipients with its registry. When apply is true, only recipients missing from the active registry are imported. The SOPS file and active registry entries are never removed or rewritten by reconciliation.

type DefaultKeyRegistry

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

DefaultKeyRegistry implements the KeyRegistry interface with SOPS encryption support.

func NewDefaultKeyRegistry

func NewDefaultKeyRegistry(registryPath string, encryptor SOPSEncryptor, logger *slog.Logger) *DefaultKeyRegistry

NewDefaultKeyRegistry creates a new key registry with SOPS encryption. The registry file is stored at <registryPath>/key-registry.yaml and is encrypted with SOPS.

func (*DefaultKeyRegistry) CheckExpiration

func (r *DefaultKeyRegistry) CheckExpiration(ctx context.Context, warnDays int) (*ExpirationReport, error)

CheckExpiration returns keys that are expired or expiring soon. The warnDays parameter specifies the warning threshold in days. Validates: Requirements 4.1, 4.2, 4.3, 4.4 - Check expiration status and warn within 14 days.

func (*DefaultKeyRegistry) GetKey

func (r *DefaultKeyRegistry) GetKey(ctx context.Context, cluster string, keyType KeyType) (*KeyEntry, error)

GetKey retrieves key metadata by cluster and type. It delegates to the active primary key when one exists, falling back to the earliest-registered active key when no primary is set (legacy registries). Returns ErrKeyNotFound if no matching key exists.

func (*DefaultKeyRegistry) GetPrimaryKey

func (r *DefaultKeyRegistry) GetPrimaryKey(ctx context.Context, cluster string, keyType KeyType) (*KeyEntry, error)

GetPrimaryKey retrieves the active primary key for a cluster and type. Returns ErrKeyNotFound if no active primary exists.

func (*DefaultKeyRegistry) ListKeys

func (r *DefaultKeyRegistry) ListKeys(ctx context.Context, cluster string) ([]KeyEntry, error)

ListKeys returns all keys, optionally filtered by cluster. If cluster is empty, returns keys for all clusters.

func (*DefaultKeyRegistry) RebuildFromFiles

func (r *DefaultKeyRegistry) RebuildFromFiles(ctx context.Context, keysDir string) error

RebuildFromFiles reconstructs the registry from existing key files. This is useful when the registry is corrupted or missing. Validates: Requirement 9.8 - Rebuild registry from key files.

func (*DefaultKeyRegistry) RegisterKey

func (r *DefaultKeyRegistry) RegisterKey(ctx context.Context, entry KeyEntry) error

RegisterKey adds a new key to the registry.

Uniqueness is enforced per (cluster, key type, fingerprint) across all statuses: the same key may not be registered twice, and a revoked or archived fingerprint may not be silently reinstated.

Multiple ACTIVE keys per cluster and type are valid and expected. SOPS encrypts a file to many age recipients simultaneously, and dual-key rotation (see DefaultKeyRotator.RotateAgeKey and GetRotationStatus) requires the old and new keys to be active at the same time. Revocation likewise requires at least two active recipients so that revoking one cannot lock the cluster out.

Validates: Requirements 4.7, 9.2 - Record creation timestamp and expiration date.

func (*DefaultKeyRegistry) ReplacePrimary

func (r *DefaultKeyRegistry) ReplacePrimary(ctx context.Context, oldFingerprint string, newEntry KeyEntry) error

ReplacePrimary atomically registers a new primary and clears the predecessor's primary role. The predecessor remains active so Age rotations retain dual-key decryption.

func (*DefaultKeyRegistry) ReplacePrimaryAndArchive

func (r *DefaultKeyRegistry) ReplacePrimaryAndArchive(ctx context.Context, oldFingerprint string, newEntry KeyEntry) error

ReplacePrimaryAndArchive atomically registers a new primary and archives the predecessor. It is used for immediate SSH replacement, where retaining the old key as an active recipient would be incorrect.

func (*DefaultKeyRegistry) SetPrimaryKey

func (r *DefaultKeyRegistry) SetPrimaryKey(ctx context.Context, cluster string, keyType KeyType, fingerprint string) error

SetPrimaryKey selects an exact existing active key and repairs the complete primary group in one transaction.

func (*DefaultKeyRegistry) UpdateKey

func (r *DefaultKeyRegistry) UpdateKey(ctx context.Context, entry KeyEntry) error

UpdateKey updates an existing key entry. Matching is performed by cluster, key type, and fingerprint when available.

func (*DefaultKeyRegistry) UpdateKeyStatus

func (r *DefaultKeyRegistry) UpdateKeyStatus(ctx context.Context, cluster string, keyType KeyType, status KeyStatus) error

UpdateKeyStatus updates the status of a key. Returns ErrKeyNotFound if no matching key exists.

func (*DefaultKeyRegistry) UpdateKeys

func (r *DefaultKeyRegistry) UpdateKeys(ctx context.Context, entries []KeyEntry) error

UpdateKeys applies multiple existing key updates in one locked transaction. All entries are validated and applied in memory before a single registry save, so a failed match or validation leaves the persisted registry unchanged.

type DefaultKeyRevoker

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

DefaultKeyRevoker implements the KeyRevoker interface. It handles key revocation operations for users and compromised keys, with support for emergency revocation that immediately generates a new primary key.

func NewDefaultKeyRevoker

func NewDefaultKeyRevoker(
	registry KeyRegistry,
	rotator KeyRotator,
	secretsManager SecretsManager,
	auditLogger AuditLogger,
	logger *slog.Logger,
) *DefaultKeyRevoker

NewDefaultKeyRevoker creates a new key revoker with the given dependencies.

Parameters:

  • registry: Key registry for tracking key metadata
  • rotator: Key rotator for generating new keys during emergency revocation
  • secretsManager: Secrets manager for re-encrypting manifests
  • auditLogger: Logger for audit events (can be nil to disable audit logging)
  • logger: Logger for operation tracking

Returns:

  • *DefaultKeyRevoker: A new key revoker instance

func (*DefaultKeyRevoker) EmergencyRevoke

func (r *DefaultKeyRevoker) EmergencyRevoke(ctx context.Context, cluster string, fingerprint string) (*RevocationResult, error)

EmergencyRevoke immediately revokes a key and generates a new primary key. This is used when a key is compromised and immediate action is needed.

Validates: Requirements 6.6 - Perform immediate revocation - Generate new primary key

func (*DefaultKeyRevoker) RevokeByFingerprint

func (r *DefaultKeyRevoker) RevokeByFingerprint(ctx context.Context, opts RevokeOptions) (*RevocationResult, error)

RevokeByFingerprint removes a specific key. Re-encrypts all manifests without the revoked key.

Validates: Requirements 6.5, 6.2, 6.3 - Revoke specific key by fingerprint - Re-encrypt all manifests without the revoked key

Returns ErrKeyNotFound if the fingerprint doesn't exist. Returns ErrSingleKeyRevocation if this would remove the only key.

func (*DefaultKeyRevoker) RevokeByUser

func (r *DefaultKeyRevoker) RevokeByUser(ctx context.Context, opts RevokeOptions) (*RevocationResult, error)

RevokeByUser removes all keys associated with a user. Re-encrypts all manifests without the revoked keys.

Validates: Requirements 6.1, 6.2, 6.3, 6.4 - Identify all keys associated with the user - Remove user's Age key public key from .sops.yaml - Re-encrypt all manifests without the revoked key - Log revocation event to audit log

Returns ErrSingleKeyRevocation if this would remove the only key.

type DefaultKeyRotator

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

DefaultKeyRotator implements the KeyRotator interface. It handles key rotation operations with dual-key transition support, allowing for gradual migration from old to new keys.

func NewDefaultKeyRotator

func NewDefaultKeyRotator(
	registry KeyRegistry,
	secretsManager SecretsManager,
	auditLogger AuditLogger,
	logger *slog.Logger,
) *DefaultKeyRotator

NewDefaultKeyRotator creates a new key rotator with the given dependencies.

Parameters:

  • registry: Key registry for tracking key metadata
  • secretsManager: Secrets manager for re-encrypting manifests
  • auditLogger: Logger for audit events (can be nil to disable audit logging)
  • logger: Logger for operation tracking

Returns:

  • *DefaultKeyRotator: A new key rotator instance

func (*DefaultKeyRotator) CompleteRotation

func (r *DefaultKeyRotator) CompleteRotation(ctx context.Context, cluster string, keyType KeyType) error

CompleteRotation removes the old key after dual-key period. Re-encrypts all manifests with only the new key and marks the old key as archived.

Validates: Requirements 3.4 - Remove old key from .sops.yaml - Re-encrypt manifests with new key only - Update registry with archived status for old key

func (*DefaultKeyRotator) GetRotationStatus

func (r *DefaultKeyRotator) GetRotationStatus(ctx context.Context, cluster string) (*RotationStatus, error)

GetRotationStatus returns the current rotation state. Checks if a dual-key rotation is in progress and returns details about the old and new keys.

func (*DefaultKeyRotator) RotateAgeKey

func (r *DefaultKeyRotator) RotateAgeKey(ctx context.Context, opts RotateOptions) (*RotationResult, error)

RotateAgeKey generates a new Age key and re-encrypts secrets. The new key is added alongside the old key in dual-key mode to allow for gradual migration. Call CompleteRotation to finalize the rotation.

Validates: Requirements 3.1, 3.2, 3.3, 3.7 - Generate new Age key pair - Add new public key to .sops.yaml alongside old key - Re-encrypt all manifests with both keys - Archive old key with timestamp

func (*DefaultKeyRotator) RotateSSHKey

func (r *DefaultKeyRotator) RotateSSHKey(ctx context.Context, opts RotateOptions) (*RotationResult, error)

RotateSSHKey generates a new SSH key pair. Updates the config file with the new key paths and archives the old key.

Validates: Requirements 3.5, 3.6 - Generate new SSH key pair - Update config file with new key paths - Archive old SSH key

type DefaultMultiClusterSyncer

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

DefaultMultiClusterSyncer implements the MultiClusterSyncer interface. It provides methods for performing secrets operations across multiple clusters in parallel with configurable concurrency and error handling.

func NewDefaultMultiClusterSyncer

func NewDefaultMultiClusterSyncer(
	secretsManager SecretsManager,
	logger *slog.Logger,
) *DefaultMultiClusterSyncer

NewDefaultMultiClusterSyncer creates a new DefaultMultiClusterSyncer.

Parameters:

  • secretsManager: The secrets manager to use for individual cluster operations
  • logger: Logger for operation tracking

Returns:

  • *DefaultMultiClusterSyncer: A new multi-cluster syncer instance

func (*DefaultMultiClusterSyncer) SyncAll

SyncAll syncs secrets for all clusters in the organization. It discovers clusters from the filesystem, processes them in parallel with configurable concurrency, and handles failures according to the options.

The method continues processing remaining clusters on failure by default, unless StopOnError is set to true.

type DefaultSecretsManager

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

DefaultSecretsManager implements the SecretsManager interface. It provides secrets synchronization, drift detection, and validation by coordinating between config files, SOPS encryption, and manifest generation.

func NewDefaultSecretsManager

func NewDefaultSecretsManager(
	configLoader *v2.ConfigIOHandler,
	sopsManager *sops.DefaultSOPSManager,
	auditLogger AuditLogger,
	logger *slog.Logger,
) *DefaultSecretsManager

NewDefaultSecretsManager creates a new DefaultSecretsManager with the given dependencies.

Parameters:

  • configLoader: Handler for loading and saving config files
  • sopsManager: Manager for SOPS encryption operations
  • auditLogger: Logger for audit events (can be nil to disable audit logging)
  • logger: Logger for operation tracking

Returns:

  • *DefaultSecretsManager: A new secrets manager instance

func (*DefaultSecretsManager) DetectDrift

func (m *DefaultSecretsManager) DetectDrift(ctx context.Context, cluster string) (*DriftReport, error)

DetectDrift identifies differences between config and manifests. This is a lower-level method that returns detailed drift information without the validation context.

func (*DefaultSecretsManager) GetSecretSources

func (m *DefaultSecretsManager) GetSecretSources(ctx context.Context, cluster string) ([]SecretSource, error)

GetSecretSources returns all secret sources for a cluster. This includes the config file path and all manifest paths that contain secrets for the specified cluster.

func (*DefaultSecretsManager) SyncSecrets

func (m *DefaultSecretsManager) SyncSecrets(ctx context.Context, opts SyncOptions) (*SyncResult, error)

SyncSecrets regenerates encrypted manifests from the config file. It reads secrets from the cluster's config file and generates corresponding SOPS-encrypted manifests for each service.

Returns ErrConfigNotFound if the config file does not exist. Returns ErrKeyNotFound if the cluster's Age key is not available.

func (*DefaultSecretsManager) ValidateSecrets

func (m *DefaultSecretsManager) ValidateSecrets(ctx context.Context, opts ValidateOptions) (*ValidationResult, error)

ValidateSecrets compares config secrets against encrypted manifests. It decrypts each manifest and compares the values against the config, reporting any drift, missing manifests, orphaned secrets, or security issues.

Returns ErrConfigNotFound if the config file does not exist. Returns ErrKeyNotFound if the cluster's Age key is not available. Returns ErrDecryptionFailed if a manifest cannot be decrypted.

type DriftField

type DriftField struct {
	// Path is the YAML path (e.g., "data.password").
	Path string

	// ConfigHash is a hash of the config value.
	ConfigHash string

	// ManifestHash is a hash of the manifest value.
	ManifestHash string
}

DriftField represents a single field with drift.

type DriftItem

type DriftItem struct {
	// Service is the service name (e.g., "harbor").
	Service string

	// FieldPath is the path to the differing field (e.g., "data.password").
	FieldPath string

	// ConfigHash is a hash of the config value (for comparison without exposing secrets).
	ConfigHash string

	// ManifestHash is a hash of the manifest value.
	ManifestHash string
}

DriftItem represents a single drift detection.

type DriftReport

type DriftReport struct {
	// Cluster is the cluster name.
	Cluster string

	// Timestamp is when the drift detection was performed.
	Timestamp time.Time

	// ConfigPath is the path to the config file.
	ConfigPath string

	// OverlayPath is the path to the overlay directory.
	OverlayPath string

	// Services contains drift details per service.
	Services []ServiceDrift

	// TotalDriftCount is the total number of drifted fields.
	TotalDriftCount int

	// SecurityViolations is the count of unencrypted secrets.
	SecurityViolations int
}

DriftReport contains comprehensive drift analysis.

type ErrConfigNotFound

type ErrConfigNotFound struct {
	Cluster      string
	ExpectedPath string
}

ErrConfigNotFound is returned when a cluster config file cannot be found.

func (*ErrConfigNotFound) Error

func (e *ErrConfigNotFound) Error() string

type ErrDecryptionFailed

type ErrDecryptionFailed struct {
	FilePath string
	Cause    error
}

ErrDecryptionFailed is returned when a manifest cannot be decrypted.

func (*ErrDecryptionFailed) Error

func (e *ErrDecryptionFailed) Error() string

func (*ErrDecryptionFailed) Unwrap

func (e *ErrDecryptionFailed) Unwrap() error

type ErrEncryptionFailed

type ErrEncryptionFailed struct {
	FilePath string
	Cause    error
}

ErrEncryptionFailed is returned when a manifest cannot be encrypted.

func (*ErrEncryptionFailed) Error

func (e *ErrEncryptionFailed) Error() string

func (*ErrEncryptionFailed) Unwrap

func (e *ErrEncryptionFailed) Unwrap() error

type ErrKeyNotFound

type ErrKeyNotFound struct {
	Cluster string
	KeyType KeyType
}

ErrKeyNotFound is returned when an encryption key cannot be found.

func (*ErrKeyNotFound) Error

func (e *ErrKeyNotFound) Error() string

type ErrNoReachablePrivateKey

type ErrNoReachablePrivateKey struct {
	Cluster string
	KeyType KeyType
	KeyFile string
}

ErrNoReachablePrivateKey is returned when a readable operator key file does not contain any recipient that would remain authorized after revocation.

func (*ErrNoReachablePrivateKey) Error

func (e *ErrNoReachablePrivateKey) Error() string

type ErrPrimaryKeyRevocation

type ErrPrimaryKeyRevocation struct {
	Cluster     string
	KeyType     KeyType
	Fingerprint string
}

ErrPrimaryKeyRevocation is returned when attempting to revoke the active cluster-managed primary key outside the emergency path.

func (*ErrPrimaryKeyRevocation) Error

func (e *ErrPrimaryKeyRevocation) Error() string

type ErrRegistryCorrupted

type ErrRegistryCorrupted struct {
	Cause error
}

ErrRegistryCorrupted is returned when the key registry is invalid or corrupted.

func (*ErrRegistryCorrupted) Error

func (e *ErrRegistryCorrupted) Error() string

func (*ErrRegistryCorrupted) Unwrap

func (e *ErrRegistryCorrupted) Unwrap() error

type ErrRegistryDriftDetected

type ErrRegistryDriftDetected struct {
	Cluster    string
	Recipients []string
}

ErrRegistryDriftDetected is returned when SOPS contains recipients that are not represented by active registry entries.

func (*ErrRegistryDriftDetected) Error

func (e *ErrRegistryDriftDetected) Error() string

type ErrRotationInProgress

type ErrRotationInProgress struct {
	Cluster string
	KeyType KeyType
}

ErrRotationInProgress is returned when attempting an operation that conflicts with an ongoing rotation.

func (*ErrRotationInProgress) Error

func (e *ErrRotationInProgress) Error() string

type ErrSingleKeyRevocation

type ErrSingleKeyRevocation struct {
	Cluster string
	KeyType KeyType
}

ErrSingleKeyRevocation is returned when attempting to revoke the only encryption key.

func (*ErrSingleKeyRevocation) Error

func (e *ErrSingleKeyRevocation) Error() string

type ExpirationReport

type ExpirationReport struct {
	// Expired lists keys that have passed their expiration date.
	Expired []KeyExpirationInfo

	// Warning lists keys expiring within the warning period.
	Warning []KeyExpirationInfo

	// Valid lists keys with time remaining.
	Valid []KeyExpirationInfo
}

ExpirationReport contains key expiration status.

type HookManager

type HookManager interface {
	// InstallHooks installs pre-commit hooks in the repository.
	// The hooks validate staged files for unencrypted secrets and drift.
	InstallHooks(ctx context.Context, repoPath string, cluster string) error

	// ValidatePreCommit runs pre-commit validation on staged files.
	// Returns a HookResult indicating whether the commit should proceed.
	ValidatePreCommit(ctx context.Context, stagedFiles []string) (*HookResult, error)

	// UninstallHooks removes installed hooks from the repository.
	UninstallHooks(ctx context.Context, repoPath string) error
}

HookManager handles Git hook installation and execution.

This interface provides methods for installing pre-commit hooks that validate secrets before commits, preventing plaintext secrets and configuration drift from being pushed to Git.

type HookResult

type HookResult struct {
	// Passed indicates whether the validation passed.
	Passed bool

	// UnencryptedFiles lists files with plaintext secrets.
	UnencryptedFiles []string

	// DriftDetected lists files with configuration drift.
	DriftDetected []string

	// PlaintextKeys lists plaintext key files that were staged.
	PlaintextKeys []string

	// Warnings contains non-blocking warnings.
	Warnings []string
}

HookResult contains pre-commit validation results.

type KeyEntry

type KeyEntry struct {
	// Cluster is the cluster name this key belongs to.
	Cluster string `yaml:"cluster" json:"cluster"`

	// KeyType is "age" or "ssh".
	KeyType KeyType `yaml:"key_type" json:"key_type"`

	// Fingerprint is the unique identifier for the key.
	Fingerprint string `yaml:"fingerprint" json:"fingerprint"`

	// PublicKey is the public key string.
	PublicKey string `yaml:"public_key" json:"public_key"`

	// CreatedAt is when the key was created.
	CreatedAt time.Time `yaml:"created_at" json:"created_at"`

	// ExpiresAt is when the key expires.
	ExpiresAt time.Time `yaml:"expires_at" json:"expires_at"`

	// Status is "active", "archived", or "revoked".
	Status KeyStatus `yaml:"status" json:"status"`

	// RotatedFrom is the fingerprint of the key this was rotated from.
	RotatedFrom string `yaml:"rotated_from,omitempty" json:"rotated_from,omitempty"`

	// RevokedAt is when the key was revoked.
	RevokedAt time.Time `yaml:"revoked_at,omitempty" json:"revoked_at,omitempty"`

	// RevokedBy is who revoked the key.
	RevokedBy string `yaml:"revoked_by,omitempty" json:"revoked_by,omitempty"`

	// RevokedReason is why the key was revoked.
	RevokedReason string `yaml:"revoked_reason,omitempty" json:"revoked_reason,omitempty"`

	// UsedBy lists paths that use this key.
	UsedBy []string `yaml:"used_by,omitempty" json:"used_by,omitempty"`

	// UserEmail is the email of the user who owns this key (for multi-recipient).
	UserEmail string `yaml:"user_email,omitempty" json:"user_email,omitempty"`

	// Primary marks the cluster-managed key that rotation operates on.
	// SOPS has no notion of a primary recipient; this distinguishes the key the CLI manages from additional user recipients that are equally active.
	Primary bool `yaml:"primary,omitempty" json:"primary,omitempty"`
}

KeyEntry represents metadata for a single key.

type KeyExpirationInfo

type KeyExpirationInfo struct {
	// Cluster is the cluster name.
	Cluster string

	// KeyType is "age" or "ssh".
	KeyType KeyType

	// Fingerprint is the key fingerprint.
	Fingerprint string

	// DaysRemaining is days until expiration (negative if expired).
	DaysRemaining int

	// ExpiresAt is the expiration timestamp.
	ExpiresAt time.Time
}

KeyExpirationInfo contains expiration details for a key.

type KeyRegistry

type KeyRegistry interface {
	// RegisterKey adds a new key to the registry.
	// Returns an error if a key with the same cluster, type, and fingerprint
	// already exists in any status.
	//
	// Multiple active keys per cluster and type are valid: SOPS encrypts to
	// many age recipients at once, and dual-key rotation requires the old and
	// new keys to be active simultaneously.
	RegisterKey(ctx context.Context, entry KeyEntry) error

	// GetKey retrieves key metadata by cluster and type.
	// It delegates to the active primary key when one exists, falling back to the earliest-registered active key when no primary is set (legacy registries).
	// Returns ErrKeyNotFound if no matching key exists.
	GetKey(ctx context.Context, cluster string, keyType KeyType) (*KeyEntry, error)

	// GetPrimaryKey retrieves the active primary key for a cluster and type.
	// Returns ErrKeyNotFound if no active primary exists.
	GetPrimaryKey(ctx context.Context, cluster string, keyType KeyType) (*KeyEntry, error)

	// SetPrimaryKey explicitly selects an existing active key as the primary.
	// It clears primary flags from every other key in the same cluster/type group.
	SetPrimaryKey(ctx context.Context, cluster string, keyType KeyType, fingerprint string) error

	// ReplacePrimary atomically registers a new primary and clears the predecessor's primary role.
	// The predecessor remains active so Age rotations retain dual-key decryption.
	ReplacePrimary(ctx context.Context, oldFingerprint string, newEntry KeyEntry) error

	// ReplacePrimaryAndArchive atomically registers a new primary and archives
	// the predecessor in the same locked load/mutate/save transaction.
	ReplacePrimaryAndArchive(ctx context.Context, oldFingerprint string, newEntry KeyEntry) error

	// UpdateKeys applies multiple existing key updates in one locked,
	// all-or-nothing load/mutate/save transaction.
	UpdateKeys(ctx context.Context, entries []KeyEntry) error

	// UpdateKeyStatus updates the status of a key when exactly one active key
	// matches the cluster and type. If multiple active keys match, it returns
	// an ambiguity error; prefer UpdateKey when a specific fingerprint must be changed.
	UpdateKeyStatus(ctx context.Context, cluster string, keyType KeyType, status KeyStatus) error

	// UpdateKey updates an existing key entry, preserving metadata fields that callers modify.
	// Returns ErrKeyNotFound if no matching key exists.
	UpdateKey(ctx context.Context, entry KeyEntry) error

	// ListKeys returns all keys, optionally filtered by cluster.
	// If cluster is empty, returns keys for all clusters.
	ListKeys(ctx context.Context, cluster string) ([]KeyEntry, error)

	// CheckExpiration returns keys that are expired or expiring soon.
	// The warnDays parameter specifies the warning threshold in days.
	CheckExpiration(ctx context.Context, warnDays int) (*ExpirationReport, error)

	// RebuildFromFiles reconstructs the registry from existing key files.
	// This is useful when the registry is corrupted or missing.
	RebuildFromFiles(ctx context.Context, keysDir string) error
}

KeyRegistry manages key metadata and lifecycle.

This interface provides methods for registering, retrieving, and managing encryption keys across clusters. The registry is stored as a SOPS-encrypted YAML file and tracks key fingerprints, creation dates, expiration dates, and lifecycle status.

type KeyRevoker

type KeyRevoker interface {
	// RevokeByUser removes all keys associated with a user.
	// Re-encrypts all manifests without the revoked keys.
	// Returns ErrSingleKeyRevocation if this would remove the only key.
	RevokeByUser(ctx context.Context, opts RevokeOptions) (*RevocationResult, error)

	// RevokeByFingerprint removes a specific key.
	// Re-encrypts all manifests without the revoked key.
	// Returns ErrKeyNotFound if the fingerprint doesn't exist.
	// Returns ErrSingleKeyRevocation if this would remove the only key.
	RevokeByFingerprint(ctx context.Context, opts RevokeOptions) (*RevocationResult, error)

	// EmergencyRevoke immediately revokes a key and generates a new primary key.
	// This is used when a key is compromised and immediate action is needed.
	EmergencyRevoke(ctx context.Context, cluster string, fingerprint string) (*RevocationResult, error)
}

KeyRevoker handles key revocation operations.

This interface provides methods for revoking keys by user email or fingerprint, with support for emergency revocation that immediately generates a new primary key.

type KeyRotator

type KeyRotator interface {
	// RotateAgeKey generates a new Age key and re-encrypts secrets.
	// The new key is added alongside the old key in dual-key mode.
	// Returns ErrKeyNotFound if the cluster has no existing Age key.
	RotateAgeKey(ctx context.Context, opts RotateOptions) (*RotationResult, error)

	// RotateSSHKey generates a new SSH key pair.
	// Updates the config file with the new key paths.
	RotateSSHKey(ctx context.Context, opts RotateOptions) (*RotationResult, error)

	// CompleteRotation removes the old key after dual-key period.
	// Re-encrypts all manifests with only the new key.
	// Returns ErrRotationInProgress if no rotation is in progress.
	CompleteRotation(ctx context.Context, cluster string, keyType KeyType) error

	// GetRotationStatus returns the current rotation state.
	GetRotationStatus(ctx context.Context, cluster string) (*RotationStatus, error)
}

KeyRotator handles key rotation operations.

This interface provides methods for rotating Age and SSH keys with support for dual-key transitions. During rotation, both old and new keys are active to allow for gradual migration.

type KeyStatus

type KeyStatus string

KeyStatus represents the lifecycle status of a key.

const (
	// KeyStatusActive indicates the key is currently in use.
	KeyStatusActive KeyStatus = "active"
	// KeyStatusArchived indicates the key has been rotated and archived.
	KeyStatusArchived KeyStatus = "archived"
	// KeyStatusRevoked indicates the key has been revoked.
	KeyStatusRevoked KeyStatus = "revoked"
)

func (KeyStatus) String

func (ks KeyStatus) String() string

String returns the string representation of the key status.

type KeyType

type KeyType string

KeyType represents the type of encryption key.

const (
	// KeyTypeAge represents an Age encryption key used by SOPS.
	KeyTypeAge KeyType = "age"
	// KeyTypeSSH represents an SSH key pair for cluster access.
	KeyTypeSSH KeyType = "ssh"
)

func (KeyType) String

func (kt KeyType) String() string

String returns the string representation of the key type.

type MultiClusterSyncOptions

type MultiClusterSyncOptions struct {
	// Organization filters to a specific organization.
	Organization string

	// Concurrency is the maximum number of parallel operations.
	Concurrency int

	// StopOnError stops processing on the first failure.
	StopOnError bool

	// DryRun previews changes without applying them.
	DryRun bool
}

MultiClusterSyncOptions configures multi-cluster sync behavior.

type MultiClusterSyncResult

type MultiClusterSyncResult struct {
	// Results maps cluster names to their sync results.
	Results map[string]*SyncResult

	// Failures maps cluster names to their errors.
	Failures map[string]error

	// SuccessCount is the number of successful syncs.
	SuccessCount int

	// FailureCount is the number of failed syncs.
	FailureCount int
}

MultiClusterSyncResult contains the outcome of multi-cluster sync.

type MultiClusterSyncer

type MultiClusterSyncer interface {
	// SyncAll syncs secrets for all clusters in the organization.
	// Processes clusters in parallel with configurable concurrency.
	SyncAll(ctx context.Context, opts MultiClusterSyncOptions) (*MultiClusterSyncResult, error)
}

MultiClusterSyncer handles multi-cluster operations.

This interface provides methods for performing secrets operations across multiple clusters in parallel.

type ReconcileReport

type ReconcileReport struct {
	Cluster                               string
	SOPSConfigPath                        string
	InBoth                                []string
	OnlyInSOPSConfig                      []string
	OnlyInRegistry                        []string
	DuplicateFingerprints                 []string
	RecipientsRevokedButStillInSOPSConfig []string
	Imported                              []string
}

ReconcileReport describes differences between a cluster's SOPS recipients and its active Age entries in the key registry.

func (*ReconcileReport) HasDrift

func (r *ReconcileReport) HasDrift() bool

HasDrift reports whether the registry and SOPS configuration need attention.

type RevocationResult

type RevocationResult struct {
	// RevokedKeys lists fingerprints of revoked keys.
	RevokedKeys []string

	// ReencryptedFiles lists files re-encrypted without the revoked key.
	ReencryptedFiles []string

	// NewPrimaryKey is the new key fingerprint (emergency revocation only).
	NewPrimaryKey string
}

RevocationResult contains the outcome of a revocation.

type RevokeOptions

type RevokeOptions struct {
	// Cluster is the target cluster.
	Cluster string

	// User is the user email (for RevokeByUser).
	User string

	// Fingerprint is the key fingerprint (for RevokeByFingerprint).
	Fingerprint string

	// DryRun previews the revocation without making changes.
	DryRun bool

	// Emergency performs emergency revocation with new key generation.
	Emergency bool

	// Reason is the reason for revocation (for audit logging).
	Reason string
}

RevokeOptions configures revocation behavior.

type RollbackManager

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

RollbackManager handles atomic operations with rollback support. It backs up files before modification and can restore them on failure, ensuring that operations either complete fully or leave no partial changes.

Validates: Requirement 3.9 - Rollback on encryption failure

func NewRollbackManager

func NewRollbackManager(logger *slog.Logger) *RollbackManager

NewRollbackManager creates a new rollback manager.

Parameters:

  • logger: Logger for operation tracking (uses default if nil)

Returns:

  • *RollbackManager: A new rollback manager instance

func (*RollbackManager) Backup

func (r *RollbackManager) Backup(path string) error

Backup creates a backup of the file at the specified path. If the file doesn't exist, it records nil to indicate the file should be deleted during rollback.

Parameters:

  • path: Path to the file to backup

Returns:

  • error: Error if backup fails (file read error)

func (*RollbackManager) BackupCount

func (r *RollbackManager) BackupCount() int

BackupCount returns the number of backed up files.

func (*RollbackManager) Clear

func (r *RollbackManager) Clear()

Clear removes all backup data without performing a rollback. This should be called after a successful operation to free memory.

func (*RollbackManager) HasBackups

func (r *RollbackManager) HasBackups() bool

HasBackups returns true if there are any backed up files.

func (*RollbackManager) Rollback

func (r *RollbackManager) Rollback() error

Rollback restores all backed up files to their original state. Files that didn't exist before are deleted, and files that existed are restored to their original content.

Returns:

  • error: Combined error if any restore operations fail

type RotateOptions

type RotateOptions struct {
	// Cluster is the target cluster.
	Cluster string

	// KeyType is "age" or "ssh".
	KeyType KeyType

	// DryRun previews the rotation plan without making changes.
	DryRun bool

	// Complete indicates this is completing a dual-key rotation.
	Complete bool
}

RotateOptions configures key rotation behavior.

type RotationResult

type RotationResult struct {
	// OldFingerprint is the previous key fingerprint.
	OldFingerprint string

	// NewFingerprint is the new key fingerprint.
	NewFingerprint string

	// ReencryptedFiles lists files that were re-encrypted.
	ReencryptedFiles []string

	// ArchivedKeyPath is the path to the archived old key.
	ArchivedKeyPath string

	// DualKeyActive indicates if dual-key mode is now active.
	DualKeyActive bool
}

RotationResult contains the outcome of a rotation.

type RotationStatus

type RotationStatus struct {
	// InProgress indicates if a rotation is in progress.
	InProgress bool

	// DualKeyActive indicates if dual-key mode is active.
	DualKeyActive bool

	// OldKey is the old key entry (if in dual-key mode).
	OldKey *KeyEntry

	// NewKey is the new key entry (if in dual-key mode).
	NewKey *KeyEntry

	// PendingFiles lists files not yet re-encrypted with new key only.
	PendingFiles []string
}

RotationStatus represents the current rotation state.

type SOPSEncryptor

type SOPSEncryptor interface {
	// EncryptFile encrypts a file using explicit SOPS configuration.
	EncryptFile(ctx context.Context, filePath string, config sops.EncryptionConfig) error

	// DecryptFile decrypts a SOPS-encrypted file and returns the content
	DecryptFile(ctx context.Context, filePath string) ([]byte, error)

	// GetEncryptedContent returns the ciphertext and SOPS metadata.
	GetEncryptedContent(filePath string) (string, error)
}

SOPSEncryptor defines the interface for SOPS encryption/decryption operations.

type SecretSource

type SecretSource struct {
	// Type is "config" or "manifest".
	Type string

	// Path is the file path.
	Path string

	// Service is the service name (for manifests).
	Service string
}

SecretSource represents a source of secrets.

type SecretsManager

type SecretsManager interface {
	// SyncSecrets regenerates encrypted manifests from the config file.
	// It reads secrets from the cluster's config file and generates
	// corresponding SOPS-encrypted manifests for each service.
	//
	// Returns ErrConfigNotFound if the config file does not exist.
	// Returns ErrKeyNotFound if the cluster's Age key is not available.
	SyncSecrets(ctx context.Context, opts SyncOptions) (*SyncResult, error)

	// ValidateSecrets compares config secrets against encrypted manifests.
	// It decrypts each manifest and compares the values against the config,
	// reporting any drift, missing manifests, orphaned secrets, or security issues.
	//
	// Returns ErrConfigNotFound if the config file does not exist.
	// Returns ErrKeyNotFound if the cluster's Age key is not available.
	// Returns ErrDecryptionFailed if a manifest cannot be decrypted.
	ValidateSecrets(ctx context.Context, opts ValidateOptions) (*ValidationResult, error)

	// DetectDrift identifies differences between config and manifests.
	// This is a lower-level method that returns detailed drift information
	// without the validation context.
	DetectDrift(ctx context.Context, cluster string) (*DriftReport, error)

	// GetSecretSources returns all secret sources for a cluster.
	// This includes the config file path and all manifest paths that
	// contain secrets for the specified cluster.
	GetSecretSources(ctx context.Context, cluster string) ([]SecretSource, error)
}

SecretsManager handles secrets synchronization and drift detection.

This interface provides methods for synchronizing secrets from config files to encrypted manifests, validating that manifests match the config, and detecting drift between the source of truth and deployed secrets.

type SecurityIssue

type SecurityIssue struct {
	// FilePath is the path to the file containing the issue.
	FilePath string

	// FieldPath is the path to the unencrypted field.
	FieldPath string

	// Severity indicates the severity level ("critical", "high", "medium").
	Severity string
}

SecurityIssue represents an unencrypted secret found in a manifest.

type ServiceDrift

type ServiceDrift struct {
	// ServiceName is the name of the service.
	ServiceName string

	// ManifestPath is the path to the service's manifest.
	ManifestPath string

	// DriftFields contains the fields with drift.
	DriftFields []DriftField

	// Status is "synced", "drifted", or "missing".
	Status string
}

ServiceDrift contains drift details for a single service.

type SyncError

type SyncError struct {
	// FilePath is the path to the file that failed.
	FilePath string

	// Service is the service name associated with the file.
	Service string

	// Error is the underlying error.
	Error error
}

SyncError represents an error during sync for a specific file.

type SyncOptions

type SyncOptions struct {
	// Cluster is the target cluster name.
	Cluster string

	// Services is an optional list of specific services to sync.
	// If empty, all services are synced.
	Services []string

	// DryRun previews changes without applying them.
	DryRun bool

	// Force overwrites manifests even if no drift is detected.
	Force bool
}

SyncOptions configures secrets synchronization behavior.

type SyncResult

type SyncResult struct {
	// Created lists files that were created.
	Created []string

	// Updated lists files that were updated.
	Updated []string

	// Unchanged lists files with no changes.
	Unchanged []string

	// Errors contains any errors encountered during sync.
	Errors []SyncError
}

SyncResult contains the outcome of a sync operation.

type ValidateOptions

type ValidateOptions struct {
	// Cluster is the target cluster name.
	Cluster string

	// Fix automatically runs opencenter secrets sync to resolve detected drift.
	Fix bool

	// OutputJSON outputs the validation result in JSON format.
	OutputJSON bool
}

ValidateOptions configures secrets validation behavior.

type ValidationResult

type ValidationResult struct {
	// Valid is true if no drift was detected.
	Valid bool

	// DriftItems contains secrets with drift.
	DriftItems []DriftItem

	// MissingManifests lists config secrets without corresponding manifests.
	MissingManifests []string

	// OrphanedSecrets lists manifest secrets not in the config.
	OrphanedSecrets []string

	// SecurityIssues lists unencrypted secrets found in manifests.
	SecurityIssues []SecurityIssue

	// ExitCode is 0 for valid, 1 for drift detected.
	ExitCode int
}

ValidationResult contains drift detection findings.

Jump to

Keyboard shortcuts

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