cli

package
v0.6.11 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExitSuccess             = output.ExitSuccess
	ExitGeneralError        = output.ExitGeneralError
	ExitConfigError         = output.ExitConfigError
	ExitVaultError          = output.ExitVaultError
	ExitGPGError            = output.ExitGPGError
	ExitAuthError           = output.ExitAuthError
	ExitValidationError     = output.ExitValidationError
	ExitFingerprintRequired = output.ExitFingerprintRequired
	ExitAccessDenied        = output.ExitAccessDenied
	ExitAlgorithmNotAllowed = output.ExitAlgorithmNotAllowed
)

Exit code constants - aliases to output package.

Variables

View Source
var ErrUserCancelled = errors.New("cancelled by user")

ErrUserCancelled is returned when the user cancels an interactive prompt (Ctrl-C or Escape)

Functions

func CreateSignedLogin added in v0.0.9

func CreateSignedLogin(gpgClient gpg.Client, fingerprint string) (*config.Login, error)

CreateSignedLogin is the exported version for use by init.go

func ExitWithError

func ExitWithError(err error)

ExitWithError exits the program with the given error.

func PrintHelp

func PrintHelp(w io.Writer)

PrintHelp prints the help message

func PrintSuccess

func PrintSuccess(w io.Writer, message string)

PrintSuccess prints a success message to stdout.

func PrintVersion

func PrintVersion(w io.Writer, version, commit, date string)

PrintVersion prints the version information

func PrintVersionJSON added in v0.0.9

func PrintVersionJSON(w io.Writer, version, commit, date string)

PrintVersionJSON prints version information as JSON.

func PrintWarning

func PrintWarning(w io.Writer, message string)

PrintWarning prints a warning to stderr.

func ResolveConfigPath

func ResolveConfigPath(configPath string, silent bool, stderr io.Writer) string

ResolveConfigPath returns the effective config path considering: 1. Explicit configPath argument (highest priority, e.g. -c flag) 2. DOTSECENV_CONFIG env var 3. XDG default path If configPath is specified and DOTSECENV_CONFIG is set, prints a warning to stderr (unless silent).

Types

type CLI

type CLI struct {
	Silent bool
	// contains filtered or unexported fields
}

CLI represents the command-line interface

func NewCLI

func NewCLI(vaultPaths []string, configPath string, silent bool, stdin io.Reader, stdout, stderr io.Writer) (*CLI, error)

NewCLI creates a new CLI instance

func NewCLIConfigOnly added in v0.5.1

func NewCLIConfigOnly(configPath string, silent bool, stdin io.Reader, stdout, stderr io.Writer) (*CLI, error)

NewCLIConfigOnly creates a CLI instance that only loads config and GPG, without opening any vaults. This is used by commands like `login` that operate purely on config and do not need vault access.

func (*CLI) Close

func (c *CLI) Close() error

Close closes the vault and releases locks

func (*CLI) IdentityAdd

func (c *CLI) IdentityAdd(fingerprint string, addAll bool, vaultPath string, fromIndex int) *Error

IdentityAdd adds a GPG identity to one or more vaults. If addAll is true, the identity is added to every configured vault. If vaultPath is non-empty, only the vault at that path is targeted. If fromIndex > 0, the vault at that 1-based index is targeted. When none of the above are set and exactly one vault is configured, it is auto-selected.

func (*CLI) IdentityCreate added in v0.0.9

func (c *CLI) IdentityCreate(opts IdentityCreateOptions) *Error

IdentityCreate generates a new GPG key or outputs the generation template.

func (*CLI) Login

func (c *CLI) Login(fingerprint string) *Error

Login initializes the user's identity with a signed login proof. If fingerprint is empty, it will interactively prompt the user to select from available secret keys.

func (*CLI) Output

func (c *CLI) Output() *output.Handler

Output returns the unified output handler for this CLI instance.

func (*CLI) Policy added in v0.6.0

func (c *CLI) Policy() policy.Policy

Policy returns the loaded system policy. Empty Policy means no policy is enforced.

func (*CLI) SecretForget added in v0.0.9

func (c *CLI) SecretForget(secretKeyArg, vaultPath string, fromIndex int, ignoreNotFound bool) *Error

SecretForget marks a secret as deleted by adding a deletion marker value. The deletion marker has deleted=true and an empty available_to list.

func (*CLI) SecretGet

func (c *CLI) SecretGet(secretKey string, all bool, last bool, jsonOutput bool, vaultPath string, fromIndex int) *Error

SecretGet retrieves a secret from the vault. If the user cannot access the latest value, falls back to older accessible values with a warning.

func (*CLI) SecretList added in v0.4.3

func (c *CLI) SecretList(jsonOutput bool, vaultPath string, fromIndex int) *Error

SecretList lists all secret keys from vaults. If vaultPath is specified or fromIndex > 0, lists secrets only from that vault. Otherwise, lists secrets from all vaults.

func (*CLI) SecretPut

func (c *CLI) SecretPut(secretKeyArg, vaultPath string, fromIndex int, preReadValue string) *Error

SecretPut stores a secret in the vault. If preReadValue is non-empty, it's used as the secret value (for piped input read before vault lock). If preReadValue is empty, the secret is read from stdin (interactive TTY mode).

func (*CLI) SecretRevoke

func (c *CLI) SecretRevoke(secretKey, targetFingerprint string, vaultIndex int) *Error

SecretRevoke re-encrypts a secret without the specified fingerprint, effectively revoking their access. If the secret is shared with the fingerprint, it re-encrypts with every other public key except the one corresponding to the fingerprint, updates available_to, regenerates the hash, and signs it.

func (*CLI) SecretRevokeAll

func (c *CLI) SecretRevokeAll(secretKey, targetFingerprint string) *Error

SecretRevokeAll revokes access to a secret from a fingerprint across all vaults.

func (*CLI) SecretShare

func (c *CLI) SecretShare(secretKey, targetFingerprint string, vaultIndex int) *Error

SecretShare shares a secret with another identity

func (*CLI) SecretShareAll

func (c *CLI) SecretShareAll(secretKey, targetFingerprint string) *Error

SecretShareAll shares a secret with a fingerprint across all vaults where the secret exists.

func (*CLI) SetJSONMode

func (c *CLI) SetJSONMode(enabled bool)

SetJSONMode enables or disables JSON output mode for the current command. This creates a new handler with fresh warning collection.

func (*CLI) Validate

func (c *CLI) Validate(fix bool) *Error

Validate validates the configuration and vault files

func (*CLI) VaultDescribe added in v0.0.9

func (c *CLI) VaultDescribe(jsonOutput bool) *Error

VaultDescribe lists all vaults with their identities and secrets

func (*CLI) VaultDoctor added in v0.0.9

func (c *CLI) VaultDoctor(jsonOutput bool, fix bool, vaultPath string, fromIndex int) *Error

VaultDoctor runs health checks on the vault configuration and environment. In CI environments, interactive prompts are skipped automatically. When fix is true, upgrades and defragmentation are performed non-interactively.

func (*CLI) Warnf

func (c *CLI) Warnf(format string, args ...interface{})

Warnf prints a warning message to stderr unless silent mode is enabled. Deprecated: For new code, use c.Output().Warnf() with a structured code.

type CryptoInfo added in v0.0.9

type CryptoInfo struct {
	GOFIPS140      string `json:"GOFIPS140,omitempty"`
	FIPS140Enabled bool   `json:"fips140Enabled"`
}

CryptoInfo represents cryptographic module information.

type DoctorCheckJSON added in v0.0.9

type DoctorCheckJSON struct {
	Name    string `json:"name"`
	Status  string `json:"status"` // "ok", "warning", "error"
	Message string `json:"message,omitempty"`
	Details string `json:"details,omitempty"`
}

DoctorCheckJSON represents a single health check in JSON output

type DoctorFixJSON added in v0.4.7

type DoctorFixJSON struct {
	Name    string `json:"name"`
	Status  string `json:"status"` // "ok" or "error"
	Message string `json:"message"`
}

DoctorFixJSON represents a fix action in JSON output

type DoctorResultJSON added in v0.0.9

type DoctorResultJSON struct {
	Status string            `json:"status"` // "healthy", "warning", "error"
	Checks []DoctorCheckJSON `json:"checks"`
	Fixes  []DoctorFixJSON   `json:"fixes,omitempty"`
}

DoctorResultJSON is the JSON output structure for doctor

type Error

type Error struct {
	Message  string
	ExitCode ExitCode
}

Error represents a CLI error with an exit code. Kept for backward compatibility; new code should use output.Error.

func HandleInteractiveSelection

func HandleInteractiveSelection(options []string, prompt string, stderr io.Writer) (int, *Error)

HandleInteractiveSelection prompts the user to select from options and handles cancellation uniformly. It opens /dev/tty directly for input, allowing interactive selection even when stdin is piped. Returns the selected index and nil on success, or writes "Cancelled." to stderr and returns an error on cancellation.

func IdentityCreateStandalone added in v0.0.9

func IdentityCreateStandalone(opts IdentityCreateOptions, out *output.Handler) *Error

IdentityCreateStandalone runs identity create without requiring full CLI initialization. This is used when no config exists yet.

func InitConfig

func InitConfig(configPath string, initialVaults []string, gpgProgram string, loginFingerprint string, out *output.Handler) *Error

InitConfig initializes a configuration file with FIPS-compliant defaults. gpgProgram: if non-empty, set gpg.program to this value (without validation). Otherwise gpg.program defaults to "PATH" (resolved at runtime). loginFingerprint: if non-empty, creates a signed login proof for this fingerprint.

func InitVaultFile

func InitVaultFile(vaultPath string, out *output.Handler) *Error

InitVaultFile initializes a specific vault file

func InitVaultInteractiveStandalone

func InitVaultInteractiveStandalone(configPath string, out *output.Handler) *Error

InitVaultInteractiveStandalone allows user to select a vault from config to initialize This runs without requiring the vaults to be openable (since they might not exist yet)

func NewError

func NewError(message string, code ExitCode) *Error

NewError creates a new CLI error. For new code, prefer output.NewError with a structured code.

func PolicyList added in v0.6.0

func PolicyList(jsonMode, silent bool, stdout, stderr io.Writer) *Error

PolicyList prints the effective system policy with per-field origin attribution. Operates standalone (does not require a loaded user config), so admins can introspect policy without being dotsecenv users themselves.

func PolicyValidate added in v0.6.0

func PolicyValidate(jsonMode, silent bool, stdout, stderr io.Writer) *Error

PolicyValidate parses all fragments and reports structural errors. In text mode (default), prints a short status line. In JSON mode, emits a structured object compatible with the convention from `vault doctor --json` (raw json.NewEncoder output to stdout, no envelope; errors surface via the returned *Error which the caller reports to stderr with the appropriate non-zero exit code).

Returns nil on success (no policy enforced OR all fragments structurally valid). Otherwise returns *Error with a distinct ExitCode per category.

func PromptConfirm

func PromptConfirm(prompt string, stderr io.Writer) (bool, *Error)

PromptConfirm asks the user for a y/n confirmation. Returns true if confirmed, false if declined, or an error on cancellation. Opens /dev/tty directly to work even when stdin is piped.

func ValidateVaultPathsAgainstConfig added in v0.4.4

func ValidateVaultPathsAgainstConfig(configPath string, vaultPaths []string, out *output.Handler) *Error

ValidateVaultPathsAgainstConfig checks if specified vault paths are allowed per config. Returns an error if restrict_to_configured_vaults is true and paths are not in config. Prints a warning if paths are not in config but restriction is off. If configPath is empty, uses the default resolved config path.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type ExitCode

type ExitCode = output.ExitCode

ExitCode represents the exit code for an error. This is an alias to the output package for backward compatibility.

func PrintError

func PrintError(w io.Writer, err error) ExitCode

PrintError prints an error to stderr and returns the exit code. Handles both legacy Error and output.Error types.

type IdentityCreateOptions added in v0.0.9

type IdentityCreateOptions struct {
	Algorithm    string // Algorithm to use (ED25519, RSA4096, P384, P521)
	Name         string // User's full name
	Email        string // User's email address
	TemplateOnly bool   // If true, only output the template without generating
	NoPassphrase bool   // If true, create key without passphrase (for CI/automation)
}

IdentityCreateOptions holds options for the identity create command.

type SecretListJSON added in v0.4.3

type SecretListJSON struct {
	Key     string `json:"key"`
	Vault   string `json:"vault,omitempty"`
	Deleted bool   `json:"deleted,omitempty"`
}

SecretListJSON is the JSON output structure for secret list

type SecretValueJSON

type SecretValueJSON struct {
	AddedAt     time.Time   `json:"added_at"`
	Value       interface{} `json:"value"`
	Vault       string      `json:"vault,omitempty"`
	AvailableTo []string    `json:"available_to,omitempty"`
	SignedBy    string      `json:"signed_by,omitempty"`
}

SecretValueJSON is the JSON output structure for secret values. AvailableTo and SignedBy are populated when --all is used so the JSON output is sufficient for auditing access control across versions.

type ValidationError

type ValidationError struct {
	Level   string // "GLOBAL", "IDENTITY", "SECRET", "STRUCTURE"
	Message string
	Path    string // For errors in specific items
}

ValidationError represents a validation error with context

type VaultDescribeIdentityJSON added in v0.0.9

type VaultDescribeIdentityJSON struct {
	UID           string     `json:"uid"`
	Fingerprint   string     `json:"fingerprint"`
	Algorithm     string     `json:"algorithm"`
	AlgorithmBits int        `json:"algorithm_bits"`
	Curve         string     `json:"curve,omitempty"`
	CreatedAt     time.Time  `json:"created_at"`
	ExpiresAt     *time.Time `json:"expires_at,omitempty"`
}

VaultDescribeIdentityJSON represents an identity in the vault describe JSON output

type VaultDescribeJSON added in v0.0.9

type VaultDescribeJSON struct {
	Position   int                         `json:"position"`
	Vault      string                      `json:"vault"`
	Identities []VaultDescribeIdentityJSON `json:"identities"`
	Secrets    []VaultDescribeSecretJSON   `json:"secrets"`
}

VaultDescribeJSON is the JSON output structure for vault describe

type VaultDescribeSecretJSON added in v0.0.9

type VaultDescribeSecretJSON struct {
	Key         string   `json:"key"`
	Deleted     bool     `json:"deleted,omitempty"`
	AvailableTo []string `json:"available_to,omitempty"`
}

VaultDescribeSecretJSON represents a secret in the vault describe JSON output. AvailableTo reflects the current authorization snapshot (the most-recent value's access list); it is omitted for deleted secrets and secrets without values.

type VaultResolver

type VaultResolver interface {
	GetIdentityByFingerprint(fingerprint string) *vault.Identity
	AddSecret(secret vault.Secret, index int) error
	SaveAll() error
	GetSecretFromAnyVault(key string, stderr io.Writer) (*vault.SecretValue, error)
	GetAccessibleSecretFromAnyVault(key, fingerprint string) (*vault.SecretValue, error)
	GetSecretByKeyFromVault(index int, key string) *vault.Secret
	FindSecretVaultIndex(key string) int
	GetVaultManager(index int) *vault.Manager
	AddIdentity(identity vault.Identity, index int) error
	GetConfig() vault.VaultConfig
	GetVaultPaths() []string
	GetAvailableVaultPathsWithIndices() []vault.VaultPathWithIndex
	IsPathInConfig(path string) bool
	IdentityExistsInVault(fingerprint string, index int) bool
	SaveVault(index int) error
	CloseAll() error
	GetLoadError(index int) error
	GetSecret(index int, key string) (*vault.SecretValue, error)
	OpenVaultsFromPaths(paths []string, stderr io.Writer) error
	OpenVaults(stderr io.Writer) error
	VaultCount() int
	ListAllSecretKeys() []vault.SecretKeyInfo
	ListSecretKeysFromVault(index int) []vault.SecretKeyInfo
}

VaultResolver defines the interface for vault operations required by the CLI

type VersionInfo added in v0.0.9

type VersionInfo struct {
	Version        string     `json:"version"`
	Commit         string     `json:"commit"`
	BuiltAt        string     `json:"builtAt"`
	GoBuildVersion string     `json:"goBuildVersion"`
	Crypto         CryptoInfo `json:"crypto"`
}

VersionInfo represents version information as a structured object.

Jump to

Keyboard shortcuts

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