Documentation
¶
Overview ¶
Package config manages jms metadata (TOML) and credential storage.
Design contract (DESIGN.md「配置与凭据分层」): the configuration file holds metadata only — alias, internal/external URL, username, prefer, ssh_port. It never holds a password or a TOTP secret; those live in the OS credential store (see credentials.go). The file is therefore safe to back up, sync, or commit.
Dependency direction: config depends on nothing else in this module.
Package config — Linux Secret Service credential path.
Why this file exists (2026-10-27):
The generic credential path uses github.com/zalando/go-keyring, whose Linux implementation calls the Secret Service D-Bus API synchronously and without a timeout (secret_service.go: `s.object.Call(...).Store(...)`). When the login collection is locked, the service answers Unlock with a *prompt* path and the client then waits for a human to type the unlock password into a graphical prompt (go-keyring's handlePrompt).
On a headless machine there is nobody to answer that prompt: the D-Bus call blocks forever. The user sees no output, no error and no audit record — the process is simply killed by an external timeout. That is the defect reported against `jms exec` on a machine with no graphical session (XDG_SESSION_TYPE and DISPLAY both empty).
This file replaces the Linux read path with one that never blocks indefinitely:
- every D-Bus call carries a context with a deadline, so a wedged service surfaces as a timeout error instead of a hang;
- the collection's Locked property is inspected *before* any Unlock call, so a locked keyring fails immediately instead of provoking a prompt that can never be answered;
- the resulting error names the environment variable that provides a way out, satisfying DESIGN.md「配置与凭据分层」 ("两处都没有 → 明确报错并 给出指引").
Only the read path is replaced. Writes still go through go-keyring: creating an item in a locked collection legitimately needs the unlock prompt, and that is a user-initiated action where waiting for a prompt is the correct behaviour.
Index ¶
- Constants
- Variables
- func CheckCredentialsRefused(cfg *AppConfig) error
- func ConfigDir() (string, error)
- func CredentialHint(alias string) string
- func DefaultPath() (string, error)
- func EnvVarName(alias, kind string) (string, error)
- func IsProxyOff(raw string) bool
- func Save(path string, cfg *AppConfig) error
- func Validate(s *ServerConfig) error
- type AppConfig
- func (c *AppConfig) DefaultServer() (*ServerConfig, error)
- func (c *AppConfig) Delete(name string) error
- func (c *AppConfig) Get(name string) (*ServerConfig, error)
- func (c *AppConfig) Names() []string
- func (c *AppConfig) ProxyFor(srv *ServerConfig) string
- func (c *AppConfig) Put(s *ServerConfig) error
- func (c *AppConfig) SetDefault(name string) error
- type CredentialStore
- type LockedError
- type ServerConfig
Constants ¶
const ( KindInternal = "internal" KindExternal = "external" )
Address kinds. These strings are also the values accepted by ServerConfig.Prefer and by the CLI --endpoint flag.
const ( PreferInternal = KindInternal PreferExternal = KindExternal )
Preference values accepted by ServerConfig.Prefer. An empty Prefer means PreferInternal.
const ( CredPassword = "password" CredOTP = "otp" )
Credential kinds accepted by CredentialStore.
const ConfigVersion float64 = 2
ConfigVersion is the schema version written to new configuration files.
const DefaultSSHPort = 2222
DefaultSSHPort is the KoKo SSH port used when ServerConfig.SSHPort is unset.
const EnvConfig = "JMS_CONFIG"
EnvConfig overrides the configuration file path.
const MaxAuditKeepDays = 3650
MaxAuditKeepDays bounds the retention window (ten years).
const ProxyOff = "direct"
ProxyOff is the value that explicitly forces a direct connection, overriding a global proxy setting. An empty Proxy means "inherit".
Variables ¶
var ( // ErrNotFound is returned by CredentialStore.Get when a credential // is absent from every backing store. ErrNotFound = errors.New("credential not found") // ErrReadOnly is returned by CredentialStore.Set/Delete for stores // that cannot be written (the environment-variable store). ErrReadOnly = errors.New("credential store is read-only") // ErrConfigNotFound is returned by Load when the configuration file // does not exist. ErrConfigNotFound = errors.New("config file not found") // ErrNoServers is returned when no server is configured at all. ErrNoServers = errors.New("no servers configured") // ErrServerNotFound is returned when an alias does not exist. ErrServerNotFound = errors.New("server not found") // ErrLegacyConfig is returned when a pre-rewrite jms-cli config.yaml // is detected. The rewrite deliberately does not import it // (DESIGN.md「配置与凭据分层」). ErrLegacyConfig = errors.New("detected legacy jms-cli config") )
Sentinel errors. Callers should test them with errors.Is.
var ErrCredentialStoreLocked = errors.New("credential store is locked")
ErrCredentialStoreLocked reports that the OS credential store exists but is locked and cannot be unlocked unattended.
Callers test for it with errors.Is. It is deliberately distinct from ErrNotFound: "the entry is absent" and "the store is locked" call for different user actions, and the difference is what makes the failure diagnosable.
Functions ¶
func CheckCredentialsRefused ¶
func ConfigDir ¶
ConfigDir returns the directory that holds config.toml, state.json and the audit directory. It is the directory of DefaultPath, so JMS_CONFIG relocates the whole directory.
func CredentialHint ¶ added in v0.1.7
CredentialHint renders the operator-facing hint for a credential that could not be read.
It names the environment variable that bypasses the credential store, because that is the way out on a machine with no graphical session, and it never contains a credential value.
func DefaultPath ¶
DefaultPath returns the configuration file path.
Resolution order:
- the JMS_CONFIG environment variable, when set and non-empty
- <os.UserConfigDir()>/jms/config.toml
On Windows os.UserConfigDir is %AppData% (Roaming), on Unix it is $XDG_CONFIG_HOME or ~/.config.
func EnvVarName ¶
EnvVarName renders the environment variable that holds alias's credential of the given kind. An unknown kind falls back to the password variable, matching the CredentialStore contract where kind is always one of CredPassword/CredOTP. EnvVarName renders the environment variable that holds alias's credential of kind. Unknown kinds must fail rather than silently alias to the password variable - the keyring path rejects them, and a mistyped kind would otherwise hand a TOTP code where a password is expected (or the reverse).
func IsProxyOff ¶
IsProxyOff reports whether a configured proxy value explicitly forces a direct connection rather than inheriting the global setting.
func Save ¶
Save writes the configuration file atomically (temp file in the same directory + fsync + rename) with permissions 0600 on Unix. The parent directory is created when missing.
Every server is validated before anything is written, so a rejected entry never truncates or corrupts an existing file.
func Validate ¶
func Validate(s *ServerConfig) error
Validate checks a server entry.
Rules: Name and Username non-empty; at least one of Internal/External set; every non-empty address is an absolute http(s) URL; Prefer is empty or a known kind; SSHPort is 0 or in 1..65535.
Types ¶
type AppConfig ¶
type AppConfig struct {
Version float64
Default string
// Proxy is the global proxy policy: empty (or "direct") means every
// connection is made directly, which is the default and never consults
// HTTP_PROXY/HTTPS_PROXY (DESIGN.md「代理策略」).
Proxy string
// AuditKeepDays is the local audit retention window in days.
//
// 0 means "never prune". The value is a property of this machine rather
// than of a server, so it lives at the top level: one retention rule per
// audit directory, whatever alias produced the records.
AuditKeepDays int
Servers map[string]*ServerConfig
}
AppConfig is the parsed configuration file.
Servers is keyed by alias. Iteration order is not meaningful: use Names for a deterministic order.
func Load ¶
Load reads and validates the configuration file.
An empty path means DefaultPath. A missing file yields ErrConfigNotFound, unless a pre-rewrite config.yaml is found next to it, in which case ErrLegacyConfig is returned (the rewrite deliberately does not import the legacy format; DESIGN.md「配置与凭据分层」).
func (*AppConfig) DefaultServer ¶
func (c *AppConfig) DefaultServer() (*ServerConfig, error)
DefaultServer returns the default server.
When Default names an existing alias it wins; otherwise the alphabetically first alias is used, so the fallback is deterministic.
Errors: ErrNoServers (wrapped) when nothing is configured.
func (*AppConfig) Delete ¶
Delete removes the server with the given alias. When it was the default, the alphabetically first remaining alias becomes the default (or Default is cleared when none remain).
Errors: ErrServerNotFound (wrapped) when the alias is unknown.
func (*AppConfig) Get ¶
func (c *AppConfig) Get(name string) (*ServerConfig, error)
Get returns the server with the given alias.
Errors: ErrServerNotFound (wrapped) when the alias is unknown; the message lists the available aliases.
func (*AppConfig) Names ¶
Names returns every server alias in sorted order. It returns an empty slice (never nil) for a nil receiver, so callers can range over it.
func (*AppConfig) ProxyFor ¶
func (c *AppConfig) ProxyFor(srv *ServerConfig) string
ProxyFor returns the effective proxy value for a server: the server's own setting when it has one, otherwise the global default.
A nil receiver or nil server yields "" (direct), so a caller that has no configuration at all still gets the safe default.
func (*AppConfig) Put ¶
func (c *AppConfig) Put(s *ServerConfig) error
Put validates s and stores it under s.Name, creating the Servers map when needed. Name, Username and both addresses are trimmed and Prefer is lowercased before validation, so callers may pass raw input. The first server added becomes the default.
func (*AppConfig) SetDefault ¶
SetDefault marks an existing alias as the default server.
Errors: ErrServerNotFound (wrapped) when the alias is unknown.
type CredentialStore ¶
type CredentialStore interface {
// Get returns the credential of kind ("password" or "otp") for alias.
Get(alias, kind string) (string, error)
// Set stores the credential of kind for alias.
Set(alias, kind, value string) error
// Delete removes every credential held for alias.
Delete(alias string) error
}
CredentialStore abstracts credential persistence so the CLI can be tested without touching the real OS credential store.
Implementations must return ErrNotFound (wrapped or bare) for absent credentials and must never return a credential together with a non-nil error.
func Chain ¶
func Chain(stores ...CredentialStore) CredentialStore
Chain returns a CredentialStore that consults stores in order and returns the first hit. Writes go to the first store that accepts them.
The conventional chain is Chain(NewEnvStore(), NewKeyringStore()): environment variables win over the OS credential store, and because the environment store is read-only a Set falls through to the keyring (DESIGN.md「凭据分层」).
func NewEnvStore ¶
func NewEnvStore() CredentialStore
NewEnvStore returns a read-only CredentialStore backed by environment variables, for headless Linux, CI and WSL.
JMS_PASSWORD_<ALIAS> and JMS_OTP_<ALIAS>, with the alias uppercased and every '-' replaced by '_' (DESIGN.md「凭据分层」).
func NewKeyringStore ¶
func NewKeyringStore() CredentialStore
NewKeyringStore returns a CredentialStore backed by the OS credential store (Windows Credential Manager / macOS Keychain / Linux Secret Service).
service is "jms-client"; the account is "<alias>/password" or "<alias>/otp_secret", matching DESIGN.md「凭据分层」.
func NewMemoryStore ¶
func NewMemoryStore() CredentialStore
NewMemoryStore returns an in-memory CredentialStore for tests and for cross-package fakes. It is safe for concurrent use.
type LockedError ¶ added in v0.1.7
type LockedError struct {
// Alias is the server alias whose credential could not be read.
Alias string
// Cause is the underlying failure, if any.
Cause error
// Hint overrides the operator-facing advice. The default names the
// environment variable, which is the way out when reading - but the
// environment store is read-only, so a write needs different advice.
Hint string
}
LockedError reports that the OS credential store is locked and cannot be read unattended.
It exists so the message can carry the operator-facing hint while errors.Is still recognises ErrCredentialStoreLocked. Wrapping the sentinel with %w would append "credential store is locked" to the message, which says the same thing twice.
func (*LockedError) Error ¶ added in v0.1.7
func (e *LockedError) Error() string
Error renders the message an operator sees.
func (*LockedError) Unwrap ¶ added in v0.1.7
func (e *LockedError) Unwrap() error
Unwrap exposes the sentinel so errors.Is(err, ErrCredentialStoreLocked) holds.
type ServerConfig ¶
type ServerConfig struct {
Name string
Internal string // internal URL, may be empty
External string // external URL, may be empty
Username string
Prefer string // "internal" (default) | "external"
// Pin, when set to a known address kind, restricts the server to that one
// address: no probing of the other, no failover. For a user who knows
// which network they are always on, it removes all guessing.
Pin string
// Proxy overrides the global proxy setting for this server. An empty
// value inherits it; "direct" forces a direct connection even when a
// global proxy is configured.
Proxy string
SSHPort int // KoKo SSH port; 0 means DefaultSSHPort
}
ServerConfig is one JumpServer entry.
A server may define an internal address, an external address, or both; at least one is required. Credentials are NOT stored here — see CredentialStore.
func (*ServerConfig) Port ¶
func (s *ServerConfig) Port() int
Port returns SSHPort, or DefaultSSHPort when it is unset or out of range.
func (*ServerConfig) Preferred ¶
func (s *ServerConfig) Preferred() string
Preferred reports which address kind to try first: Prefer when it is valid, otherwise internal. The result is always KindInternal or KindExternal.
func (*ServerConfig) URLFor ¶
func (s *ServerConfig) URLFor(kind string) (string, bool)
URLFor returns the configured URL for kind ("internal" or "external").
The returned URL is exactly as configured (no normalization); api.New normalizes it. ok is false when the address is empty, whitespace-only, or kind is not a known address kind.