sops

package
v5.91.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package sops provides SOPS encryption, decryption, and editing operations for YAML and JSON files. It wraps the core SOPS library to provide a simplified API for age-based key management and file operations.

Index

Constants

View Source
const (
	// TmpFilePermissions is the permission mode for temporary files during edit.
	TmpFilePermissions = os.FileMode(0o600)
	// EncryptedFilePermissions is the permission mode for encrypted output files.
	EncryptedFilePermissions = os.FileMode(0o644)
	// DecryptedFilePermissions is the permission mode for decrypted output files.
	DecryptedFilePermissions = os.FileMode(0o600)
	// AgeKeyFilePermissions is the permission mode for age key files.
	AgeKeyFilePermissions = os.FileMode(0o600)
	// AgeKeyDirPermissions is the permission mode for the age key directory.
	AgeKeyDirPermissions = os.FileMode(0o700)
	// AgeKeyPrefix is the expected prefix for age private keys.
	AgeKeyPrefix = "AGE-SECRET-KEY-"
	// MinAgeKeyLength is the minimum required length for age private keys.
	MinAgeKeyLength = 60
)
View Source
const NotBinaryHint = "This is likely not an encrypted binary file."

NotBinaryHint provides a user-friendly message when SOPS encounters binary data.

Variables

View Source
var (
	ErrDumpingTree              = errors.New("error dumping file")
	ErrInvalidExtractPath       = errors.New("invalid extract path format")
	ErrInvalidEditor            = errors.New("invalid editor configuration")
	ErrNoEditorAvailable        = errors.New("no editor available")
	ErrStoreNoExampleGeneration = errors.New("store does not support example file generation")
	ErrCouldNotGenerateDataKey  = errors.New("could not generate data key")
	ErrUnsupportedFileFormat    = errors.New("unsupported file format")
	ErrInvalidAgeKey            = errors.New("invalid age key format")
	ErrFailedToCreateDir        = errors.New("failed to create directory")
	ErrFailedToWriteKey         = errors.New("failed to write key")
	ErrFailedToDetermineAge     = errors.New("failed to determine age key path")
)

Exported error variables for SOPS operations.

Functions

func AppendToExistingFile

func AppendToExistingFile(targetPath, formattedKey string) error

AppendToExistingFile appends the formatted key to an existing file.

func CanonicalizeAndGetStores

func CanonicalizeAndGetStores(inputPath string) (string, sops.Store, sops.Store, error)

CanonicalizeAndGetStores resolves the input path to a canonical form and returns the appropriate SOPS stores.

func CreateEditorCommand

func CreateEditorCommand(path string) (*exec.Cmd, error)

CreateEditorCommand creates the exec.Cmd for the editor.

func CreateSOPSTree

func CreateSOPSTree(
	branches sops.TreeBranches,
	config EncryptConfig,
	inputPath string,
) (*sops.Tree, error)

CreateSOPSTree creates a SOPS tree with the given branches, metadata config, and input path.

func CreateTempDir

func CreateTempDir() (string, func(), error)

CreateTempDir creates a temporary directory for editing.

func CreateTempFileWithContent

func CreateTempFileWithContent(opts EditOpts, tree *sops.Tree) (string, func(), error)

CreateTempFileWithContent creates a temporary file with the tree content.

func Decrypt

func Decrypt(opts DecryptOpts) ([]byte, error)

Decrypt performs the core decryption logic for a file. It loads the encrypted file, decrypts it, and handles extraction if specified.

func DecryptTree

func DecryptTree(opts DecryptOpts) (*sops.Tree, error)

DecryptTree loads and decrypts a SOPS tree from the input file. It handles loading the encrypted file and decrypting its contents.

func DecryptTreeWithKey

func DecryptTreeWithKey(opts DecryptOpts) (*sops.Tree, []byte, error)

DecryptTreeWithKey loads and decrypts a SOPS tree, returning both tree and data key. This is useful when the caller needs the data key for re-encryption.

func DerivePublicKey

func DerivePublicKey(privateKey string) (string, error)

DerivePublicKey derives the public key from an age private key.

func Edit

func Edit(opts EditOpts) ([]byte, error)

Edit loads, decrypts, and allows editing of an existing encrypted file.

func EditExample

func EditExample(opts EditExampleOpts) ([]byte, error)

EditExample creates and edits an example file when the target file doesn't exist.

func EditNewFile

func EditNewFile(opts EditOpts, inputStore sops.Store) ([]byte, error)

EditNewFile handles editing a new file that doesn't exist yet.

func EditTree

func EditTree(opts EditOpts, tree *sops.Tree, dataKey []byte) ([]byte, error)

EditTree handles the core edit workflow: write to temp file, launch editor, re-encrypt.

func EmitTreeContent

func EmitTreeContent(opts EditOpts, tree *sops.Tree) ([]byte, error)

EmitTreeContent emits the tree content for editing.

func Encrypt

func Encrypt(opts EncryptOpts) ([]byte, error)

Encrypt performs the core encryption logic for a file. It loads the file, validates that it's not already encrypted, generates encryption keys using the configured key services, encrypts the data, and returns the encrypted file content.

func EncryptAndEmit

func EncryptAndEmit(opts EditOpts, tree *sops.Tree, dataKey []byte) ([]byte, error)

EncryptAndEmit encrypts the tree and emits the encrypted file.

func EncryptTreeAndEmit

func EncryptTreeAndEmit(
	tree *sops.Tree,
	dataKey []byte,
	cipher sops.Cipher,
	outputStore sops.Store,
) ([]byte, error)

EncryptTreeAndEmit encrypts a tree and emits the encrypted file content. This is a common helper shared by encrypt and edit operations.

func EnsureNoMetadata

func EnsureNoMetadata(opts EncryptOpts, branch sops.TreeBranch) error

EnsureNoMetadata checks whether a file already contains SOPS metadata. This prevents re-encryption of already encrypted files, which would corrupt them.

func Extract

func Extract(tree *sops.Tree, path []any, outputStore sops.Store) ([]byte, error)

Extract retrieves a specific value or subtree from the decrypted tree. It supports extracting nested keys using a path array.

func FormatAgeKeyWithMetadata

func FormatAgeKeyWithMetadata(privateKey, publicKey string) string

FormatAgeKeyWithMetadata formats an age private key with metadata comments.

func GetAgeKeyPath

func GetAgeKeyPath() (string, error)

GetAgeKeyPath returns the platform-specific path for the age keys file. It follows the SOPS convention:

  • First checks SOPS_AGE_KEY_FILE environment variable
  • Linux: $XDG_CONFIG_HOME/sops/age/keys.txt or $HOME/.config/sops/age/keys.txt
  • macOS: $XDG_CONFIG_HOME/sops/age/keys.txt or $HOME/Library/Application Support/sops/age/keys.txt
  • Windows: %AppData%\sops\age\keys.txt

func GetDecryptStores

func GetDecryptStores(inputPath string, readFromStdin bool) (sops.Store, sops.Store, error)

GetDecryptStores returns the appropriate SOPS stores for decryption. When reading from stdin, it defaults to YAML format. For JSON format from stdin, users can pipe to a file first.

func GetStores

func GetStores(inputPath string) (sops.Store, sops.Store, error)

GetStores returns the appropriate SOPS stores (input and output) based on file extension. It supports YAML (.yaml, .yml) and JSON (.json) file formats.

func HandleEmitError

func HandleEmitError(err error, data []byte) ([]byte, error)

HandleEmitError processes errors from EmitPlainFile operations.

func HandleMasterKeysMode

func HandleMasterKeysMode(opts RunEditorUntilOkOpts, edited []byte) error

HandleMasterKeysMode handles the show master keys mode validation.

func HandleNewFile

func HandleNewFile(targetPath, formattedKey string, statErr error) error

HandleNewFile creates a new file with the formatted key or returns an error if stat failed for other reasons.

func HashFile

func HashFile(filePath string) ([]byte, error)

HashFile computes the SHA256 hash of a file.

func ImportKey

func ImportKey(privateKey string) error

ImportKey imports an age private key and automatically derives the public key.

func LoadFile

func LoadFile(opts EncryptOpts) ([]byte, error)

LoadFile reads file content either from stdin or from a file path. The source is determined by the ReadFromStdin option.

func LookupAnyEditor

func LookupAnyEditor(editorNames ...string) (string, error)

LookupAnyEditor searches for any of the specified editors in PATH.

func MetadataFromEncryptionConfig

func MetadataFromEncryptionConfig(config EncryptConfig) sops.Metadata

MetadataFromEncryptionConfig creates SOPS metadata from the encryption configuration. It converts the EncryptConfig fields into a sops.Metadata structure that will be stored in the encrypted file.

func ParseEditorCommand

func ParseEditorCommand(editor, envVar string) ([]string, error)

ParseEditorCommand parses the editor command string.

func ParseExtractPath

func ParseExtractPath(extract string) ([]any, error)

ParseExtractPath converts a JSONPath-like extract string into a path array. Example: '["data"]["password"]' -> []any{"data", "password"}.

func ProcessEditedContent

func ProcessEditedContent(opts RunEditorUntilOkOpts, edited []byte) (bool, error)

ProcessEditedContent processes the edited content and updates the tree.

func RunEditor

func RunEditor(path string) error

RunEditor launches the editor specified by SOPS_EDITOR or EDITOR environment variables. Falls back to vim, nano, or vi if no editor is configured.

func RunEditorUntilOk

func RunEditorUntilOk(opts RunEditorUntilOkOpts) error

RunEditorUntilOk runs the editor in a loop until the file is valid or user cancels.

func ValidateAgeKey

func ValidateAgeKey(privateKey string) error

ValidateAgeKey performs basic validation on an age private key string. The input must start with "AGE-SECRET-KEY-" and meet minimum length requirements.

func ValidateEditedFile

func ValidateEditedFile(opts RunEditorUntilOkOpts) (bool, error)

ValidateEditedFile validates the edited file and updates the tree.

func ValidateTreeMetadata

func ValidateTreeMetadata(opts RunEditorUntilOkOpts) (bool, error)

ValidateTreeMetadata validates the tree metadata and updates version if needed.

func WriteKeyToFile

func WriteKeyToFile(targetPath, formattedKey string) error

WriteKeyToFile writes the formatted key to the target path, either creating a new file or appending to existing one.

func WriteTempFile

func WriteTempFile(tmpdir string, opts EditOpts, tree *sops.Tree, cleanup func()) (string, error)

WriteTempFile writes the tree content to a temporary file.

Types

type DecryptOpts

type DecryptOpts struct {
	Cipher          sops.Cipher
	InputStore      sops.Store
	OutputStore     sops.Store
	InputPath       string
	ReadFromStdin   bool
	IgnoreMAC       bool
	Extract         []any
	KeyServices     []keyservice.KeyServiceClient
	DecryptionOrder []string
}

DecryptOpts contains all options needed for the decryption operation.

type EditExampleOpts

type EditExampleOpts struct {
	EditOpts

	EncryptConfig

	InputStoreWithExample StoreWithExample
}

EditExampleOpts combines EditOpts with encryption configuration for creating and editing example files.

type EditOpts

type EditOpts struct {
	Cipher          sops.Cipher
	InputStore      sops.Store
	OutputStore     sops.Store
	InputPath       string
	IgnoreMAC       bool
	KeyServices     []keyservice.KeyServiceClient
	DecryptionOrder []string
	ShowMasterKeys  bool
}

EditOpts contains all options needed for the edit operation.

type EncryptConfig

type EncryptConfig struct {
	UnencryptedSuffix       string
	EncryptedSuffix         string
	UnencryptedRegex        string
	EncryptedRegex          string
	UnencryptedCommentRegex string
	EncryptedCommentRegex   string
	MACOnlyEncrypted        bool
	KeyGroups               []sops.KeyGroup
	GroupThreshold          int
}

EncryptConfig holds configuration options for SOPS encryption. It defines patterns for which values should be encrypted/unencrypted, key groups for encryption, and Shamir secret sharing threshold.

type EncryptOpts

type EncryptOpts struct {
	EncryptConfig

	Cipher        sops.Cipher
	InputStore    sops.Store
	OutputStore   sops.Store
	InputPath     string
	ReadFromStdin bool
	KeyServices   []keyservice.KeyServiceClient
}

EncryptOpts contains all options needed for the encryption operation. It combines encryption configuration with runtime parameters like cipher, stores, and key services.

type FileAlreadyEncryptedError

type FileAlreadyEncryptedError struct{}

FileAlreadyEncryptedError indicates that a file already contains SOPS metadata and cannot be re-encrypted without first decrypting it.

func (*FileAlreadyEncryptedError) Error

func (err *FileAlreadyEncryptedError) Error() string

type RunEditorUntilOkOpts

type RunEditorUntilOkOpts struct {
	TmpFileName    string
	OriginalHash   []byte
	InputStore     sops.Store
	ShowMasterKeys bool
	Tree           *sops.Tree
	Logger         *logrus.Logger
}

RunEditorUntilOkOpts contains options for the editor loop.

type StoreWithExample

type StoreWithExample interface {
	sops.Store
	EmitExample() []byte
}

StoreWithExample is an interface for stores that can emit example files.

Jump to

Keyboard shortcuts

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