store

package
v0.18.2 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: AGPL-3.0 Imports: 35 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 store keeps komando state (inventory, conns, keys, snippets, jobs, tunnels, settings) in the sealed store under $KOMANDO_HOME (default ~/.komando).

Index

Constants

View Source
const (
	KindCredential   = "credential"
	KindCredStore    = "credstore" // an outside secret store (credential store <provider>)
	KindGroup        = "group"
	KindApprovalSeed = "approvalseed" // the approval code's seed: never a credential
)

Record types that format 3 adds.

View Source
const (
	CredPassword = "password"
	CredToken    = "token"
	CredKey      = "key"
)

Credential kinds. A trusted host CA (kind certificate) stays a hostca record, whose fields already are that kind's.

View Source
const (
	KindHost   = "host"
	KindConn   = "conn"
	KindVpn    = "vpn"
	KindKey    = "key"
	KindRecipe = "recipe"
)

Kinds of records, the record types in the store.

View Source
const (
	KindPin        = "pin"        // a server's pinned host keys
	KindPinRevoked = "pinrevoked" // host keys never to trust
	KindHostCA     = "hostca"     // a trusted host CA
)

The record types sshx keeps here, named in this package so the policy MAC covers them (policy.go).

View Source
const (
	LoginModeAsk      = "ask"      // a person types the password at every connect
	LoginModeKey      = "key"      // a key komando names (--key or --identity)
	LoginModePassword = "password" // a stored password (--credential)
	LoginModeAgent    = "agent"    // ssh-agent and the default keys in ~/.ssh
)

The ways a server logs in, as host show and host list name them (LoginMode).

View Source
const ApprovalSeedName = "komando-approval-totp"

ApprovalSeedName is the name the approval code's seed is sealed under, the vault name it had (cli approvalSecret).

View Source
const CredentialFix = "save the secret as a credential with `komando credential password add NAME`, then use credential:NAME"

CredentialFix is the one line that says what to do with a field that takes a credential and was given anything else, an outside store among them (C547, until the credential store paths of C485).

View Source
const Format3 = 3

Format3 is the store format the migration writes.

View Source
const LastFormat2Release = "v0.17.5"

LastFormat2Release is the newest komando release that opens a store of format 2, where a field that the move cannot take is fixed. It is the one place the version is spelled: raise it when a newer v0.17 release ships (TestLastFormat2ReleaseSpelledOnce).

View Source
const LoginAsk = "ask"

LoginAsk is Host.Login for a server whose password a person types at every connect; komando never stores it.

View Source
const LoginModeNone = "none"

LoginModeNone is a conn's login when komando sends no password of its own: the URL's own login, a cloud login, or none.

View Source
const OSWindows = "windows"

OSWindows is Host.OS for a Windows server.

View Source
const OldExportFix = "import it with komando " + LastFormat2Release + " into a folder of its own (KOMANDO_HOME=FOLDER), " +
	"move that folder with `komando doctor` of this komando, then export it again and import the new file " +
	"(docs/features/import.md, \"An export file from v0.17\")"

OldExportFix is what a person does with an export file from before v0.18.0: the release that reads it imports it into a home of its own, this komando moves that home, and its export is a file this komando imports. docs/features/import.md has the same steps.

View Source
const SealedKeyPrefix = sealedKeyPrefix

SealedKeyPrefix starts the Path of a key kept in the sealed store; a preview of a new key shows it alone, as the record's ID is made only when the key is written.

View Source
const StoreFile = "store.db"

StoreFile is the sealed store's file name in the home folder.

View Source
const TransportWinRM = "winrm"

TransportWinRM is Host.Transport for a server reached over WinRM.

Variables

View Source
var AccountHome = accountHome

AccountHome is the home folder of the account komando runs as, from the system's user database (getpwuid on Unix; the profile folder of the process's token on Windows), never from $HOME or $USERPROFILE. Tests replace it, so they never touch the real one.

View Source
var AgentCaller func() bool

AgentCaller reports that an AI agent makes this call (the vault sets it from vault.AgentCall). Nil counts as an agent: a store is never started beside a keychain that cannot be read unless the caller is known to be a person or a script.

View Source
var AncestorAgent = engine.ParentAgent

AncestorAgent names the AI agent among the processes above this program. Tests replace it.

View Source
var ErrDryRun = errors.New("this command cannot preview its change; nothing was changed")

ErrDryRun is returned by writes that cannot be previewed (the vault).

View Source
var ErrKeychainSlow = errors.New("store: the keychain did not answer in time")

ErrKeychainSlow wraps a keychain that did not answer in time. A command goes on unchecked then, and only to read (a busy keychain must not stop all work, but nothing is changed on a store that was not checked); doctor warns about it. So does a keychain that could not be read beside a store whose key is elsewhere (checkGeneration).

View Source
var ErrNoStore = errors.New("store: no store yet")

ErrNoStore: a read of a fresh home, which has no store yet. Callers treat it as empty.

View Source
var ErrOldCopy = errors.New("store: an older copy than the keychain's")

ErrOldCopy: the store is older than the keychain says.

View Source
var ErrRuntimeOnly = errors.New("store: UpdateRuntime changed more than runtime data; use Update")

ErrRuntimeOnly: fn of UpdateRuntime changed the inventory, which UpdateRuntime does not save. A bug in the caller.

View Source
var KeepHomeMode func() bool

KeepHomeMode, set by the cli, says whether a komando folder that others may read keeps its mode for now: a dry run writes nothing, not even the folder's mode (Audit E1); doctor reports the folder.

View Source
var KeySource func(meta map[string]string, create bool) (master []byte, newMeta map[string]string, err error)

KeySource gives the store's 32-byte master key. meta holds the store's readable settings (key_mode, salt, ...); with create, there is no store yet and KeySource picks the mode and returns the settings to keep. A create with meta key_mode "keyfile" keeps the new key out of the keychain (it could not be read): in a key file, or from the passphrase when one is given. The vault package sets it (it owns the keychain, key file and passphrase).

View Source
var MigrateCaller = func() MigrateCall { return MigrateCall{Way: MigrateRefuse} }

MigrateCaller is this process's caller. Unset, nobody migrates.

View Source
var Notice func(msg string)

Notice tells the person a one-line note on stderr (the cli sets it to the running calls' stderr). Nil: os.Stderr.

View Source
var OldCopyOK func() bool

OldCopyOK says whether an old copy may be opened to be looked at. The commands that may look are doctor and dry runs: they change nothing, and doctor must be able to say what is wrong. The cli sets it: true only while every command running in the process may look, so one command's allowance never opens an old copy for another. Nil means never.

Functions

func AcceptOldCopy added in v0.12.0

func AcceptOldCopy(want uint64) (from uint64, err error)

AcceptOldCopy makes the keychain remember this store's number, so an old copy put back on purpose (a restore) is used from now on. want is the number the person saw and said yes to: another one is refused. For a person only: the caller checks.

func BackupParts added in v0.18.0

func BackupParts() ([]string, error)

BackupParts names the .partial files of backups that a stopped migration left, never a backup under its final name. It changes nothing (doctor --dry-run).

func CheckWritable added in v0.12.0

func CheckWritable() error

CheckWritable opens this home's store (making it on a fresh home) and checks the file can be written, so a command that changes something, and records it in the audit log, finds out before it runs.

func Close added in v0.13.0

func Close()

Close closes every store this process has open; the next DB opens it again. A command calls it when it ends, an app when it quits, and a test before its folder is removed: Windows cannot remove a file that is still open.

func Commits added in v0.12.0

func Commits() uint64

Commits is how many write steps of this process changed the store.

func CopyState added in v0.12.0

func CopyState() (have, kept uint64, guardedStore, old bool, err error)

CopyState says how this home's store compares with the keychain: guarded is false when its key is not in the keychain (no protection); slow when the keychain did not answer, so nothing was compared.

func CredentialRef added in v0.18.0

func CredentialRef(what, ref string) error

CredentialRef checks a reference given as what for a field that names a credential (a password, sudo password, key passphrase, VPN key, shared key or config). The spelling of format 2 stops with a hint that names credential:NAME. An outside reference (env:VAR, op://...) stops too, with CredentialFix: no command and no migration makes a credential store item for a login (CLI-5, 2026-11-26, confirmed 2026-11-27 in C547; `komando credential` in C485 adds them). Empty, credential:NAME and text that is no reference at all pass.

func DB added in v0.12.0

func DB(create bool) (*sealdb.DB, error)

DB opens the sealed store of this home, once per process. With create, a home without store.db gets one, with a new key; without, it returns ErrNoStore, so a read makes no file and no key. An old copy stops with STORE_OLD_COPY unless OldCopyOK; then it opens to be read only.

func DBPath added in v0.12.0

func DBPath() string

DBPath is the file of this home's sealed store.

func DeleteVPNState added in v0.13.0

func DeleteVPNState(vpn string) error

DeleteVPNState forgets vpn's state (vpn rm).

func EndOldJobs added in v0.18.0

func EndOldJobs(ctx context.Context, ids []string, by string) error

EndOldJobs marks each named record ended in the format-2 store, so the move goes ahead. Each must be a record with no end. A job runs on its server, which this computer cannot see: the person who marks it looked there (doctor says so). by is that person, as the audit log names them.

func EnsureHome

func EnsureHome() error

EnsureHome creates the state directory tree.

func ExportRecord3 added in v0.18.0

func ExportRecord3(kind string) bool

ExportRecord3 reports whether an export takes records of type kind: the approval code's seed never leaves this computer (Audit L1).

func Home

func Home() string

Home is komando's data folder: KOMANDO_HOME, else .komando in UserHome.

func Lock added in v0.3.0

func Lock(name string) (unlock func(), err error)

Lock takes an exclusive lock on the file name in the state directory and returns the function that releases it. komando processes running at the same time (parallel agents) wait for each other.

func MasterKey added in v0.12.0

func MasterKey() ([]byte, error)

MasterKey returns this home's sealed store master key, for keys made from it under other labels (the vault's entries). ErrNoStore when there is no store yet.

func MetaSealed added in v0.17.0

func MetaSealed() (bool, error)

MetaSealed reports whether this home's store has the sealed copy; a home without a store counts as sealed (a new store gets it).

func MkdirPrivate added in v0.13.0

func MkdirPrivate(parts ...string) error

MkdirPrivate makes the folder parts inside komando's folder, and komando's folder first when it is missing, readable by this user only.

func OldMarker added in v0.18.0

func OldMarker(text string) (string, bool)

OldMarker reports whether text holds the marker of format 2 for a vault value and returns the marker that replaced the first one ({{credential:NAME}}). Text for a file that holds one is refused (Audit E1-3): it is never written as it is.

func OldRefError added in v0.18.0

func OldRefError(what, ref string) error

OldRefError is the usage error for a reference in the spelling of format 2: it names the spelling that replaced it, never a value.

func OldReference added in v0.18.0

func OldReference(s string) (string, bool)

OldReference reports whether s is a reference in the spelling format 2 used (secret:NAME), which no command reads any more, and returns the spelling that replaced it (credential:NAME). Every reader of a reference refuses the old one with that hint.

func Opens added in v0.17.0

func Opens(master []byte) error

Opens reports sealdb.ErrWrongKey when master does not open this home's store.

func OutsideRefOf added in v0.18.0

func OutsideRefOf(name string) (string, error)

OutsideRefOf is the reference that the credential name reads its value from when it names an item of an outside credential store (env:VAR, op://VAULT/ITEM/FIELD...). When the credential does not exist or is not such an item: "" and no error.

func Path

func Path(parts ...string) string

func PolicyErr added in v0.17.0

func PolicyErr(err error) *out.Error

PolicyErr is the error of a safety row that does not match the policy MAC, or of a store that lost its MAC; nil for any other error.

func ReadPrivateKey added in v0.12.0

func ReadPrivateKey(k *Key) ([]byte, error)

ReadPrivateKey returns the private key of k.

func RefuseOldExport added in v0.18.0

func RefuseOldExport(file string, hosts []*Host, conns []*Conn, vpns []*Vpn, keyPassphrases map[string]string) error

RefuseOldExport stops an import of the export file named file when one of its entries names a secret the way format 2 did: komando cannot link it, and clearing it would leave the server without its password. It names the fields, never a value; nil when there is none.

func Rekey added in v0.12.0

func Rekey(newMaster []byte, meta map[string]string, then func(tx *sealdb.Tx) error) error

Never call Rekey from inside Update or UpdateRuntime: it takes the runtime lock, which they hold.

Rekey seals this home's store again under a new master key and keeps meta as its readable key settings, in one write step; then runs inside it, with the new key in force (the vault reseals its values there), and the safety rows get their policy MAC under the new policy key.

func RemoveBackupParts added in v0.18.0

func RemoveBackupParts() ([]string, error)

RemoveBackupParts removes the files BackupParts names (doctor), under the store lock: a move at work writes its backup under a .partial name while it holds the lock. It returns the names removed.

func RemoveManagedKey added in v0.12.0

func RemoveManagedKey(k *Key) error

RemoveManagedKey deletes a key komando made from the store. A key that is gone already is not an error.

func ResealMeta added in v0.17.0

func ResealMeta() (map[string]string, error)

ResealMeta is doctor --reseal-meta: this home's store is closed, opened with its key without comparing its meta table, every record checked, and its meta sealed again. It returns the meta it kept. An older copy than the keychain remembers is not resealed: the write would raise its change count, and it could pass for the newest.

func ReservedCredential added in v0.18.0

func ReservedCredential(name string) error

ReservedCredential refuses the name of the approval code's seed: a person manages it with `config approval-code`, and no credential verb, import or export reaches it (Audit M1).

func SealMeta added in v0.17.0

func SealMeta() (bool, error)

SealMeta gives this home's store the sealed copy of its meta table when it has none and this process already opened it (a command that did not open the store opens nothing for it). It reports whether it wrote one.

func SealedKey added in v0.12.0

func SealedKey(k *Key) bool

SealedKey reports a key kept inside the sealed store, which has no file.

func SetStoreMeta added in v0.12.0

func SetStoreMeta(meta map[string]string) error

SetStoreMeta changes readable key settings of this home's store (a key moved out of the keychain into a key file, a move under way).

func SetVPNState added in v0.13.0

func SetVPNState(vpn string, values map[string][]byte) error

SetVPNState keeps values in vpn's state; a nil value removes its key.

func StartGeneration added in v0.12.0

func StartGeneration() error

StartGeneration writes the keychain's number for a store whose key has just gone into the keychain (a new store, `secret keychain`), so a missing number is never normal.

func Update

func Update(w Write, fn func(s *State) error) error

Update reads the inventory, applies fn and writes what changed, in one write step of the store; with Preview() it only applies fn to a copy. Safe for concurrent komando processes (parallel agents).

func UpdateRuntime added in v0.12.0

func UpdateRuntime(w Write, fn func(s *State) error) error

UpdateRuntime is Update for a change to runtime data only (Sessions, Logins, Jobs, Tunnels). It takes the runtime lock and not the inventory lock, and saves runtime.json only, so background processes do not wait for, or rewrite, the inventory. fn sees the whole state; a change to anything else stops it with ErrRuntimeOnly and nothing is saved.

With Preview(), fn runs on a copy and nothing is saved or locked.

Never call Update or UpdateRuntime from inside fn.

func UserHome added in v0.15.0

func UserHome() (string, error)

UserHome is the home folder komando's own paths start from. For an AI agent (its variables are in this process's environment, or an agent runs a process above it) it is AccountHome; for anyone else $HOME (os.UserHomeDir). When the user database and getent have no entry for the account (a container's made-up uid), there is nothing to check $HOME against: $HOME is used, and the cli stops an agent's commands until a person allows it (guardHome).

func VPNState added in v0.13.0

func VPNState(vpn, key string) ([]byte, bool, error)

VPNState returns the value key of vpn's state, and whether there is one.

func WriteFileAtomic

func WriteFileAtomic(path string, b []byte, mode os.FileMode) (err error)

WriteFileAtomic replaces path with b: a temporary file next to it is written, flushed to disk and renamed into place, and the folder is flushed too, so after a crash or power loss path holds either the old content or the new, never an empty or half-written file. The temporary file is removed on any failure.

func WriteManagedKey added in v0.12.0

func WriteManagedKey(name string, private, public []byte) (string, error)

WriteManagedKey keeps the private and public parts of a key komando made under name in the store, and returns its Path (sealed:ID).

Types

type BackupFile added in v0.18.0

type BackupFile struct {
	Name     string
	Modified time.Time
}

BackupFile is a backup the store migration left in the komando home.

func Backups added in v0.18.0

func Backups() ([]BackupFile, error)

Backups lists the migration's backups under their final names. Each is whole: it was checked under its .partial name before it got this one.

type Conn added in v0.2.0

type Conn struct {
	Name        string `json:"name"`
	Kind        string `json:"kind"` // a name from driver.Kinds: postgres, redis, s3, kafka ...
	URL         string `json:"url"`
	PasswordRef string `json:"password_ref,omitempty"` // credential:<name>, env:<VAR> or file:<path>
	// Login is "ask" (LoginAsk) for a conn whose password is never
	// stored: a person types it at every connect (add --login ask)
	Login     string            `json:"login,omitempty"`
	Via       string            `json:"via,omitempty"`     // host used to reach the resource
	ViaIDs    []string          `json:"via_ids,omitempty"` // the record IDs of Via's steps (refs.go)
	Groups    []string          `json:"groups,omitempty"`
	Tags      []string          `json:"tags,omitempty"`
	Labels    map[string]string `json:"labels,omitempty"`
	Options   map[string]string `json:"options,omitempty"` // kind-specific settings
	Protected bool              `json:"protected,omitempty"`
	Notes     string            `json:"notes,omitempty"`
	// TrustedPlugin is the hash of the kubeconfig login program a person
	// trusted for this conn (import kubeconfig). Not an Option: only a
	// person's import sets it, never --option.
	TrustedPlugin string `json:"trusted_plugin,omitempty"`
	// PluginProgram is the full path of that login program as the import
	// found it, and PluginSearchPath the PATH of that import: an AI
	// agent's command runs this file with this PATH, not what its own
	// PATH would find.
	PluginProgram    string `json:"plugin_program,omitempty"`
	PluginSearchPath string `json:"plugin_search_path,omitempty"`
	// Manager is a swarm cluster's manager server, ManagerID its record ID
	Manager   string    `json:"manager,omitempty"`
	ManagerID string    `json:"manager_id,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	Rec       Rec       `json:"-"`
}

Conn is a non-SSH resource (database, cache, ...) reached directly or through an SSH host. The URL never holds a password; see PasswordRef.

func (*Conn) AskLogin added in v0.15.0

func (c *Conn) AskLogin() bool

AskLogin reports a conn whose password a person types at every connect.

func (*Conn) LoginMode added in v0.15.0

func (c *Conn) LoginMode() string

LoginMode is how komando logs in to c: ask, password or none.

type Credential added in v0.18.0

type Credential struct {
	Name      string         `json:"name"`
	Kind      string         `json:"kind"`
	User      string         `json:"user,omitempty"`
	Value     *SealedValue   `json:"value,omitempty"`
	Store     string         `json:"store,omitempty"`
	Item      string         `json:"item,omitempty"`
	Ask       bool           `json:"ask,omitempty"`
	Key       *CredentialKey `json:"key,omitempty"`
	UpdatedAt time.Time      `json:"updated_at"`
}

Credential is what an entry logs in with. A value komando keeps is in Value; one kept outside is Item in Store; a key is in Key. Ask: a person types the password at every connect and nothing is kept.

type CredentialKey added in v0.18.0

type CredentialKey struct {
	Path        string `json:"path,omitempty"`
	Type        string `json:"type,omitempty"`
	PublicKey   string `json:"public_key,omitempty"`
	Fingerprint string `json:"fingerprint,omitempty"`
	Passphrase  string `json:"passphrase,omitempty"` // a credential name
	CertPath    string `json:"cert_path,omitempty"`
	Managed     bool   `json:"managed,omitempty"`
	Agent       bool   `json:"agent,omitempty"`
}

CredentialKey is an SSH key pair: a file of the person, the sealed pair komando made (Path sealed:<keydata ID>), or ssh-agent (Agent).

type CredentialStore added in v0.18.0

type CredentialStore struct {
	Name     string            `json:"name"`
	Provider string            `json:"provider"`
	Options  map[string]string `json:"options,omitempty"`
}

CredentialStore is an outside secret store; its options come from the environment until `credential store <provider> edit` sets them.

type ExecSession added in v0.18.0

type ExecSession struct {
	ID        string    `json:"id"`
	Host      string    `json:"host"`
	Command   string    `json:"command"` // as shown, never the filled command
	PID       int       `json:"pid"`
	PGID      int       `json:"pgid"`
	ProcStart string    `json:"proc_start"` // the process's start as the server gave it (execsession.ParseFacts)
	StartedAt time.Time `json:"started_at"`
	Sudo      bool      `json:"sudo,omitempty"`
	SudoUser  string    `json:"sudo_user,omitempty"` // empty with Sudo: root
	Actor     string    `json:"actor"`               // who the audit log names
	Agent     bool      `json:"agent,omitempty"`     // the actor is an AI agent
}

ExecSession is a run exec started in a session folder on a Unix server (internal/execsession). PID, PGID and ProcStart are read when it starts and are the only facts a stop trusts: the folder on the server belongs to the running command, which could rewrite its own pid file.

type GenerationKeep added in v0.12.0

type GenerationKeep struct {
	Get func() (n uint64, ok bool, err error)
	// Ask, when set, reads now every setting Get reads and returns a Get
	// that reads none later: probeCount calls it before it starts the
	// goroutine it may stop waiting for. A keeper that sets Get alone
	// leaves it nil.
	Ask func() func() (n uint64, ok bool, err error)
	Set func(n uint64) error
	Del func() // the store went aside (a failed move, an undo)
}

GenerationKeep reads and writes the number in the keychain.

var GenerationKeeper GenerationKeep

GenerationKeeper is set by the vault package (it owns the keychain).

type Group added in v0.18.0

type Group struct {
	Name    string   `json:"name"`
	Members []string `json:"members"`
}

Group holds entries and snippets by record ID.

type Host

type Host struct {
	Name        string `json:"name"`
	Address     string `json:"address"`
	Port        int    `json:"port,omitempty"`
	User        string `json:"user,omitempty"`
	Key         string `json:"key,omitempty"`          // name of a key in the keychain
	KeyID       string `json:"key_id,omitempty"`       // that key's record ID (refs.go)
	Identity    string `json:"identity,omitempty"`     // path to a private key file
	PasswordRef string `json:"password_ref,omitempty"` // credential:<name> or env:<VAR>
	// Login is "ask" (LoginAsk) for a server whose password is never
	// stored: a person types it at every connect (host add --login ask).
	// Empty: keys, ssh-agent and PasswordRef, as komando always logs in.
	Login   string `json:"login,omitempty"`
	SudoRef string `json:"sudo_ref,omitempty"` // sudo password ref (credential:/env:)
	Via     string `json:"via,omitempty"`      // the way there: host name(s), comma-separated chain
	// ViaIDs are the record IDs of Via's steps, in order ("" for a step
	// that names no server or VPN); see refs.go
	ViaIDs []string `json:"via_ids,omitempty"`
	// ProxyCommand is a program on this computer whose stdin and stdout
	// carry the SSH connection (OpenSSH ProxyCommand): aws ssm start-session,
	// gcloud compute start-iap-tunnel, cloudflared access ssh. %h %p %r %n.
	ProxyCommand string            `json:"proxy_command,omitempty"`
	Groups       []string          `json:"groups,omitempty"`
	Tags         []string          `json:"tags,omitempty"`
	Labels       map[string]string `json:"labels,omitempty"`
	Env          map[string]string `json:"env,omitempty"` // exported before every command
	Protected    bool              `json:"protected,omitempty"`
	// ForwardAgent lends the server this computer's ssh-agent while
	// komando is connected (host edit --forward-agent; root there can use
	// the keys in it meanwhile)
	ForwardAgent bool   `json:"forward_agent,omitempty"`
	Notes        string `json:"notes,omitempty"`
	// OS is "windows" for a Windows server: commands are PowerShell, not
	// sh. Empty: Linux or another Unix (docs/features/windows.md).
	OS string `json:"os,omitempty"`
	// Transport is "winrm" for a Windows server reached over WinRM, with
	// its settings in WinRMOpts. Empty: SSH.
	Transport string     `json:"transport,omitempty"`
	WinRMOpts *WinRMOpts `json:"winrm,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	Rec       Rec        `json:"-"`
}

func (*Host) AskLogin added in v0.15.0

func (h *Host) AskLogin() bool

AskLogin reports a server whose password a person types at every connect.

func (*Host) EffectivePort

func (h *Host) EffectivePort() int

func (*Host) LoginMode added in v0.15.0

func (h *Host) LoginMode() string

LoginMode is how komando logs in to h: ask, key, password or agent. A server with a key and a stored password is "key": the key goes first.

func (*Host) WinRM added in v0.9.0

func (h *Host) WinRM() bool

WinRM reports a server reached over WinRM.

func (*Host) Windows added in v0.9.0

func (h *Host) Windows() bool

Windows reports a Windows server: its commands are PowerShell.

type HostV3 added in v0.18.0

type HostV3 struct {
	Name           string            `json:"name"`
	Provider       string            `json:"provider"`
	Address        string            `json:"address"`
	Port           int               `json:"port,omitempty"`
	Credential     string            `json:"credential,omitempty"`
	CredentialID   string            `json:"credential_id,omitempty"`
	SudoCredential string            `json:"sudo_credential,omitempty"`
	Login          string            `json:"login,omitempty"`
	Via            string            `json:"via,omitempty"`
	ViaIDs         []string          `json:"via_ids,omitempty"`
	ProxyCommand   string            `json:"proxy_command,omitempty"`
	Tags           []string          `json:"tags,omitempty"`
	Labels         map[string]string `json:"labels,omitempty"`
	Env            map[string]string `json:"env,omitempty"` // credential:NAME for a credential's value
	Protected      bool              `json:"protected,omitempty"`
	ForwardAgent   bool              `json:"forward_agent,omitempty"`
	Notes          string            `json:"notes,omitempty"`
	OS             string            `json:"os,omitempty"`
	WinRMOpts      *WinRMOpts        `json:"winrm,omitempty"` // CA: credential:NAME
	CreatedAt      time.Time         `json:"created_at"`
	UpdatedAt      time.Time         `json:"updated_at"`
}

HostV3 is a server in format 3: provider ssh or winrm. The login user lives in its credential (owner, O-42).

type Job

type Job struct {
	ID        string    `json:"id"`
	Host      string    `json:"host"`
	Command   string    `json:"command"`
	PID       int       `json:"pid"`
	RemoteDir string    `json:"remote_dir"`
	StartedAt time.Time `json:"started_at"`
	// Ended is how the job ended (exited, killed, lost) the last time
	// komando asked its server, or "marked" when a person marked it ended
	// before the move to format 3 (EndOldJobs); empty while it ran or
	// nobody asked yet
	Ended string `json:"ended,omitempty"`
	// EndedBy is the person (the audit log's actor) who marked it ended
	EndedBy string `json:"ended_by,omitempty"`
}

type Key

type Key struct {
	Name          string `json:"name"`
	Path          string `json:"path"`
	Type          string `json:"type,omitempty"`
	PublicKey     string `json:"public_key,omitempty"`
	Fingerprint   string `json:"fingerprint,omitempty"`
	PassphraseRef string `json:"passphrase_ref,omitempty"`
	// CertPath is an OpenSSH user certificate for the key (key add --cert);
	// without it a key file's KEY-cert.pub next to it is used, as ssh does
	CertPath  string    `json:"cert_path,omitempty"`
	Managed   bool      `json:"managed"` // generated/stored by komando
	CreatedAt time.Time `json:"created_at"`
	Rec       Rec       `json:"-"`
}

type MigrateCall added in v0.18.0

type MigrateCall struct {
	Way      MigrateWay
	Why      string                               // who the caller is, for NEEDS_PERSON
	Ask      func(text string) bool               // the approval window (MigrateWindow)
	Alive    func(pid int, procStart string) bool // whether a local komando process runs
	RefGuard func(kind, name string) error        // the vault's reference guard
}

MigrateCall is what the caller hands the store.

type MigrateWay added in v0.18.0

type MigrateWay int

MigrateWay is how this call may start the migration.

const (
	// MigrateRefuse: an AI agent, a script or CI; it gets NEEDS_PERSON.
	MigrateRefuse MigrateWay = iota
	// MigrateTerminal: a person at a terminal.
	MigrateTerminal
	// MigrateWindow: the person answers komando's safety-tier approval
	// window (`komando doctor` run by the Komando app).
	MigrateWindow
)

type MigrationPreview added in v0.18.0

type MigrationPreview struct {
	Format    string `json:"format"` // the store's format now: 1, 2, 3, or none
	WouldMove bool   `json:"would_move"`
	// Counts is, per record type, the number now and after the move.
	Counts             map[string][2]int `json:"counts,omitempty"`
	NamesChanged       int               `json:"names_changed"`
	FieldsRewritten    int               `json:"fields_rewritten"`
	KeyAndPassword     int               `json:"servers_with_key_and_password"`
	SnippetsWithOldRef int               `json:"snippets_with_old_reference"`
	MergedGroups       int               `json:"groups_merged"`
	Backup             string            `json:"backup_would_be,omitempty"`
	// WouldRefuse is each reason the move would stop, by kind and field.
	WouldRefuse []string `json:"would_refuse,omitempty"`
	// Fix is the steps for the fields in WouldRefuse, the same the move
	// gives when it stops on them (C558).
	Fix []string `json:"fix,omitempty"`
	// NotChecked is what only the real move checks.
	NotChecked []string `json:"not_checked,omitempty"`
}

MigrationPreview is what the move of this home's store to format 3 would do: counts only, never the name of a record, a secret or a server, and never a value.

func PreviewMigration added in v0.18.0

func PreviewMigration(ctx context.Context, refGuard func(kind, name string) error) (MigrationPreview, error)

PreviewMigration reads this home's store and says what moving it to format 3 would do (the dry run a person runs before the real move). It writes nothing: the store is opened read-only, no lock, backup, key or marker file is made, and the keychain is only read. refGuard is the vault's reference guard, as for the real move.

type NoKeychain added in v0.14.0

type NoKeychain struct{ Err error }

NoKeychain is the error of a GenerationKeep.Get that found no keychain on this computer to ask (turned off, or no keychain tool): no count can be kept there, so there is none. Any other error means a count may be there but could not be read.

func (NoKeychain) Error added in v0.14.0

func (e NoKeychain) Error() string

func (NoKeychain) Unwrap added in v0.14.0

func (e NoKeychain) Unwrap() error

type OldJob added in v0.18.0

type OldJob struct {
	ID      string    `json:"id"`
	Host    string    `json:"server"`
	Name    string    `json:"command_name"` // the program alone: the arguments may hold secret values
	Started time.Time `json:"started"`
	Folder  string    `json:"folder"` // on the server
}

OldJob is a v0.17 job record with no end, as doctor lists it.

func OldJobs added in v0.18.0

func OldJobs(ctx context.Context) ([]OldJob, error)

OldJobs lists the job records with no end of a format-2 store, by ID. A store of format 3, or none, has none.

type Rec added in v0.12.0

type Rec struct {
	ID      string `json:"id"`
	Version uint64 `json:"version"`
}

Rec is a record's identity: a random ID that stays when the record is renamed, and a version that goes up by one each time the record changes. The sealed store keys its rows by ID.

type RuleOff added in v0.18.0

type RuleOff struct {
	Rule       string   `json:"rule"`
	Everywhere bool     `json:"everywhere,omitempty"`
	HostIDs    []string `json:"host_ids,omitempty"`
	Groups     []string `json:"groups,omitempty"`
}

RuleOff switches one policy rule off: on every server, or only on the servers HostIDs names by record ID (a group is read into its servers when the switch is made; Groups keeps its name as a label).

type Runtime added in v0.12.0

type Runtime struct {
	Sessions map[string]*VpnSession `json:"vpn_sessions,omitempty"`
	Logins   map[string]*SSHLogin   `json:"ssh_logins,omitempty"`
	Jobs     map[string]*Job        `json:"jobs,omitempty"`
	// ExecSessions are exec's runs in a session folder, by session ID
	ExecSessions map[string]*ExecSession `json:"exec_sessions,omitempty"`
	Tunnels      map[string]*Tunnel      `json:"tunnels,omitempty"`
	// LoginDeclined: when a person last cancelled the password window of
	// a login-ask server, by its record ID (sshx.LoginID); the window stays shut for a
	// short while after (cli loginCoolDown)
	LoginDeclined map[string]time.Time `json:"login_declined,omitempty"`
	// Mark ties the file to store.db: one that differs from the store's is
	// read as empty (runtime_mark.go)
	Mark string `json:"mark,omitempty"`
}

Runtime is what komando's background work keeps between commands: VPN sessions, server logins, exec sessions and tunnels, and v0.17's job records, which only the store's move reads. It lives in runtime.json, apart from the inventory in store.db, so a VPN marking itself used does not rewrite the inventory, and the coming sealed store can seal it on its own.

func ReadRuntime added in v0.12.0

func ReadRuntime() (*Runtime, error)

ReadRuntime reads runtime.json alone, sealed or not, for a caller that needs only the running sessions and tunnels (the shell prompt).

type RuntimePIDs added in v0.12.0

type RuntimePIDs struct {
	Vpns    []VpnPID `json:"vpns,omitempty"`
	Tunnels []int    `json:"tunnels,omitempty"`
}

RuntimePIDs is what the shell prompt may know of a sealed home's runtime data without its key: the processes of running VPNs (with when each was last used) and tunnels. No names, logins or tokens.

func ReadRuntimePIDs added in v0.12.0

func ReadRuntimePIDs() (*RuntimePIDs, error)

ReadRuntimePIDs reads runtime.pids: on a sealed home, the only runtime data that opens without the store's key.

type SSHLogin added in v0.8.0

type SSHLogin struct {
	Host      string    `json:"host"`
	Target    string    `json:"target"` // user@address:port when it logged in: the login is used only while the host still points there
	PID       int       `json:"pid"`
	Exe       string    `json:"exe,omitempty"`
	ProcStart string    `json:"proc_start,omitempty"` // when that process started (netx.ProcessStart)
	Socket    string    `json:"socket"`
	Token     string    `json:"token"`    // the socket's password, random per login
	HostKey   string    `json:"host_key"` // the socket's own key (authorized_keys form), random per login
	LogFile   string    `json:"log_file,omitempty"`
	StartedAt time.Time `json:"started_at"`
	Until     time.Time `json:"until"`
}

SSHLogin is a server login a person made with `komando test NAME`, held by a background komando process (sshx/held.go) on a Unix socket only this user can open, and only for a client with Token.

type SealedValue added in v0.18.0

type SealedValue struct {
	Nonce []byte `json:"nonce"`
	Data  []byte `json:"data"`
}

SealedValue is a value sealed with the vault's value key and bound to the name of the record that holds it.

type ServiceV3 added in v0.18.0

type ServiceV3 struct {
	Name             string            `json:"name"`
	Type             string            `json:"type"`
	Provider         string            `json:"provider"`
	URL              string            `json:"url,omitempty"` // no user; ?ca=credential:NAME
	Manager          string            `json:"manager,omitempty"`
	ManagerID        string            `json:"manager_id,omitempty"`
	Credential       string            `json:"credential,omitempty"`
	Login            string            `json:"login,omitempty"`
	Via              string            `json:"via,omitempty"`
	ViaIDs           []string          `json:"via_ids,omitempty"`
	Tags             []string          `json:"tags,omitempty"`
	Labels           map[string]string `json:"labels,omitempty"`
	Options          map[string]string `json:"options,omitempty"`
	Protected        bool              `json:"protected,omitempty"`
	Notes            string            `json:"notes,omitempty"`
	TrustedPlugin    string            `json:"trusted_plugin,omitempty"`
	PluginProgram    string            `json:"plugin_program,omitempty"`
	PluginSearchPath string            `json:"plugin_search_path,omitempty"`
	CreatedAt        time.Time         `json:"created_at"`
	UpdatedAt        time.Time         `json:"updated_at"`
}

ServiceV3 is a conn in format 3, typed by (type, provider): a database, cache, queue, storage, cluster or registry. A swarm cluster names its manager server instead of a URL.

type Settings

type Settings struct {
	HostKeyPolicy    string    `json:"host_key_policy"` // accept-new | strict | off
	DefaultUser      string    `json:"default_user,omitempty"`
	DefaultTimeout   string    `json:"default_timeout"`
	ConnectTimeout   string    `json:"connect_timeout"`
	Parallel         int       `json:"parallel"`
	MaxOutputBytes   int       `json:"max_output_bytes"`
	ExtraDenyPattern []string  `json:"extra_deny_patterns,omitempty"`
	RulesOff         []RuleOff `json:"rules_off,omitempty"` // rules a person switched off (policy edit)
	Audit            bool      `json:"audit"`
	AuditSQL         string    `json:"audit_sql"`                    // full | hash | off: how SQL text is kept in the audit log
	VpnIdle          string    `json:"vpn_idle"`                     // a VPN session unused this long is disconnected
	LoginFor         string    `json:"login_for"`                    // how long `komando test TARGET` keeps a server's login
	ApprovalCode     bool      `json:"approval_code,omitempty"`      // the approval window asks for a TOTP code
	ApprovalCodeStep int64     `json:"approval_code_step,omitempty"` // the last 30 s step whose code was accepted: it is not taken again
	AuditSyslog      string    `json:"audit_syslog,omitempty"`       // also send audit records to this log server (udp://, tcp://, tls://)
	MaskPersonal     string    `json:"mask_personal,omitempty"`      // protected | all | off: where AI agents see personal data hidden
	ApprovalLanguage string    `json:"approval_language,omitempty"`  // auto | en | id: the approval window's words
	PromptStyle      string    `json:"prompt_style,omitempty"`       // auto | lines: how komando asks a person (lines = one question at a time, never the screen)
}

func DefaultSettings

func DefaultSettings() Settings

type Snippet

type Snippet struct {
	Name        string `json:"name"`
	Command     string `json:"command"`
	Description string `json:"description,omitempty"`
	Sudo        bool   `json:"sudo,omitempty"`
	// ReadOnly snippets skip the protected-host check. A snippet without it
	// counts as a change.
	ReadOnly  bool      `json:"read_only,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	Rec       Rec       `json:"-"`
}

type State

type State struct {
	Hosts    map[string]*Host    `json:"hosts"`
	Conns    map[string]*Conn    `json:"conns,omitempty"`
	Vpns     map[string]*Vpn     `json:"vpns,omitempty"`
	Keys     map[string]*Key     `json:"keys"`
	Snippets map[string]*Snippet `json:"snippets"`
	// Runtime data (VPN sessions, logins, jobs, tunnels) lives in its own
	// file (runtime.go); Load puts it here.
	Runtime
	Settings Settings `json:"settings"`
	// contains filtered or unexported fields
}

func Load

func Load() (*State, error)

Load reads the inventory. Callers that change it use Update.

func (*State) FindName added in v0.2.0

func (s *State) FindName(name string) (kind, existing string, found bool)

FindName finds the host or conn whose name equals name, ignoring case, so "Web1" and "web1" cannot both exist. existing is the name as stored. Hosts and conns share one namespace so selectors stay unambiguous.

func (*State) SortedConns added in v0.2.0

func (s *State) SortedConns() []*Conn

func (*State) SortedHosts

func (s *State) SortedHosts() []*Host

func (*State) SortedVpns added in v0.2.0

func (s *State) SortedVpns() []*Vpn

type Tunnel

type Tunnel struct {
	ID        string    `json:"id"`
	Host      string    `json:"host"`
	Via       string    `json:"via,omitempty"`  // the --via chain when forwarding to a conn
	Conn      string    `json:"conn,omitempty"` // the conn this tunnel leads to
	Kind      string    `json:"kind"`           // local | remote | dynamic
	Spec      string    `json:"spec"`
	PID       int       `json:"pid"`
	ProcStart string    `json:"proc_start,omitempty"` // when that process started (netx.ProcessStart)
	LogFile   string    `json:"log_file"`
	StartedAt time.Time `json:"started_at"`
}

type Vpn added in v0.2.0

type Vpn struct {
	Name      string            `json:"name"`
	Kind      string            `json:"kind"`                 // see netx.Kinds
	Config    string            `json:"config,omitempty"`     // wireguard: the wg-quick file without its keys
	ConfigRef string            `json:"config_ref,omitempty"` // openvpn: the whole .ovpn, kept in the vault (it may hold keys)
	Address   string            `json:"address,omitempty"`    // socks: host:port of the proxy
	Portal    string            `json:"portal,omitempty"`     // openconnect kinds: the VPN server or portal
	Service   string            `json:"service,omitempty"`    // system: the OS VPN's name, to connect it with `vpn KIND start`
	Server    string            `json:"server,omitempty"`     // tailscale: a Headscale login server; l2tp, ipsec, ikev2: the VPN server
	User      string            `json:"user,omitempty"`       // user name, if the VPN wants one
	KeyRef    string            `json:"key_ref,omitempty"`    // password, private key or auth key, as credential:/env:/file:
	PSKRef    string            `json:"psk_ref,omitempty"`    // wireguard, l2tp, ipsec, ikev2: preshared key, if any
	LocalID   string            `json:"id,omitempty"`         // ipsec: the group name; ikev2: our identity
	RemoteID  string            `json:"remote_id,omitempty"`  // ikev2: the server's identity (default: --server)
	CA        string            `json:"ca,omitempty"`         // ikev2: PEM of the CA that signed the server certificate
	MFA       bool              `json:"mfa,omitempty"`        // a human must log in (`vpn KIND start`); never automated
	Protected bool              `json:"protected,omitempty"`  // changing or removing it needs a person's yes
	Check     string            `json:"check,omitempty"`      // host:port that answers only through the VPN
	Groups    []string          `json:"groups,omitempty"`
	Tags      []string          `json:"tags,omitempty"`
	Labels    map[string]string `json:"labels,omitempty"`
	Notes     string            `json:"notes,omitempty"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`

	// Weaker logins a person allowed for this VPN (`vpn edit`, with a yes).
	LegacyCrypto bool `json:"legacy_crypto,omitempty"` // l2tp, ipsec: also offer 3DES and DH groups 2 and 5
	AllowPAP     bool `json:"allow_pap,omitempty"`     // l2tp: the server may pick PAP, which sends the password itself

	Rec Rec `json:"-"`
}

Vpn is a network komando opens inside its own process to reach targets (docs/features/vpn.md). Keys live in the vault, referenced by KeyRef.

type VpnPID added in v0.12.0

type VpnPID struct {
	PID      int       `json:"pid"`
	LastUsed time.Time `json:"last_used"`
}

VpnPID is one running VPN in RuntimePIDs.

type VpnSession added in v0.2.0

type VpnSession struct {
	Vpn       string    `json:"vpn"`
	PID       int       `json:"pid"`
	Socks     string    `json:"socks,omitempty"`      // local SOCKS5 address; empty when the OS routes the traffic
	SocksUser string    `json:"socks_user,omitempty"` // login for the container's SOCKS port, random per session
	SocksPass string    `json:"socks_pass,omitempty"`
	Exe       string    `json:"exe,omitempty"`        // the program the pid must still be, so a reused pid is never signalled
	ProcStart string    `json:"proc_start,omitempty"` // when that process started (netx.ProcessStart): a pid used again is another process
	LogFile   string    `json:"log_file,omitempty"`
	StartedAt time.Time `json:"started_at"`
	LastUsed  time.Time `json:"last_used"`
	// SharedWith names the VPN whose WireGuard session this one uses: both
	// have the same key, which runs in one session at a time.
	SharedWith string `json:"shared_with,omitempty"`
}

VpnSession is a VPN kept up in the background between commands.

type VpnV3 added in v0.18.0

type VpnV3 struct {
	Name             string            `json:"name"`
	Provider         string            `json:"provider"`
	Config           string            `json:"config,omitempty"`
	ConfigCredential string            `json:"config_credential,omitempty"`
	Address          string            `json:"address,omitempty"`
	Portal           string            `json:"portal,omitempty"`
	Service          string            `json:"service,omitempty"`
	Server           string            `json:"server,omitempty"`
	User             string            `json:"user,omitempty"`
	Credential       string            `json:"credential,omitempty"`
	PSKCredential    string            `json:"psk_credential,omitempty"`
	LocalID          string            `json:"id,omitempty"`
	RemoteID         string            `json:"remote_id,omitempty"`
	CA               string            `json:"ca,omitempty"`
	MFA              bool              `json:"mfa,omitempty"`
	Protected        bool              `json:"protected,omitempty"`
	Check            string            `json:"check,omitempty"`
	Tags             []string          `json:"tags,omitempty"`
	Labels           map[string]string `json:"labels,omitempty"`
	Notes            string            `json:"notes,omitempty"`
	LegacyCrypto     bool              `json:"legacy_crypto,omitempty"`
	AllowPAP         bool              `json:"allow_pap,omitempty"`
	CreatedAt        time.Time         `json:"created_at"`
	UpdatedAt        time.Time         `json:"updated_at"`
}

VpnV3 is a VPN in format 3; its secrets are credentials.

type WinRMOpts added in v0.9.0

type WinRMOpts struct {
	Auth string `json:"auth,omitempty"` // ntlm (default) | basic
	// TLS: "" checks the certificate (HTTPS, port 5986), skip-verify does
	// not, off is plain HTTP (port 5985)
	TLS string `json:"tls,omitempty"`
	CA  string `json:"ca,omitempty"` // credential:NAME holding the PEM of the CA that signed the server's certificate
}

WinRMOpts is how komando speaks WinRM to a server.

type Write added in v0.14.0

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

Write says what a change does: Save() makes it; Preview() (a command's --dry-run) applies it to a copy that is never saved, so the command shows the result of its change (and its validation errors) without making it. Each command passes its own, so a dry run never turns another command's change into a preview. A struct, not a bool, so a bare true or false does not compile: every change names Save() or Preview(). Functions, not variables, so no code can set one to the other; the zero Write names neither, and a change with it stops (Check).

func Preview added in v0.14.0

func Preview() Write

Preview is the Write that only previews a change (--dry-run).

func Save added in v0.14.0

func Save() Write

Save is the Write that makes a change.

func (Write) Check added in v0.14.0

func (w Write) Check() error

Check is nil for Save() and Preview(), and an error for the zero Write, which names neither.

Jump to

Keyboard shortcuts

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