auth

package
v0.40.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const DenyProbeInterval = 15 * time.Minute

DenyProbeInterval is how long a token stays suppressed after Vault rejected it, before one lookup is allowed through again.

A strict never-retry cache would be the obvious reading of "blacklist the token", and for the case that motivates this — an expired or revoked token sitting in ~/.dotvault-token — it is also the correct one: that token is permanently dead and no amount of re-asking changes the answer. But a 403 on lookup-self is not exclusively "the token is dead": a token whose policy set omits auth/token/lookup-self answers identically (see the least-privilege policy notes in the config reference), and so does a token presented while Vault is mid-failover or misconfigured at the namespace level. Those clear up server-side without anything happening on this host, and a never-retry cache would wedge the daemon until someone restarted it or rewrote the token file.

So the suppression is a long re-probe window rather than a permanent verdict. At the lifecycle manager's 10s recovery cadence this turns ~8,600 lookups per day into ~96 — the volume problem is gone either way — while leaving the daemon able to heal itself from a server-side fix. Every event that plausibly means "the credential situation changed" (a token-file write, a peer socket reconnecting, SIGHUP) clears the cache outright, so the window is only ever the fallback for changes dotvault cannot observe.

The cost of the window, stated plainly: while a token is suppressed the manager is not calling lookup-self, and so is not renewing either. For the case this exists for that is no loss (a dead token cannot be renewed), but in the "403 that was not about the token" case it means a token that was fine can go up to this long without a renewal it might have needed. Renewal was already unreachable on that path before this change — checkAndRenew returns on the lookup error and never gets as far as RenewSelf — so the window lengthens an existing gap rather than opening a new one. It is bounded well under a typical Vault token TTL, and any of the clearing events closes it immediately.

Variables

View Source
var ErrBorrowOnly = errors.New("borrow-only mode: no token could be borrowed from a peer socket, and this host runs no fresh-auth flow of its own")

ErrBorrowOnly is returned by Login when BorrowOnly is set and no token could be borrowed from any of TokenSockets: there is no fresh-auth flow to fall back to, by design (see Manager.BorrowOnly). Callers that must succeed eventually rather than fail (the daemon's startup) treat this the same way they already treat a headless host with no interactive facility — idle and retry the borrow — rather than surfacing it as a fatal error.

View Source
var ErrHeldNotExportable = errors.New("held certificate key is not exportable")

ErrHeldNotExportable is returned when the held certificate's key is hardware-sealed or lives in the OS certificate store, or the configured method is not plain mtls. The decision rests on the configured method and the envelope's recorded backend, never on the in-memory key type: the TPM backend unseals its scalar into software, so the type of the loaded key says nothing about where it is meant to stay.

View Source
var ErrNoCertCredential = errors.New("no usable certificate credential on this host")

tryExistingCredential loads the stored signer, optionally rotates a cert inside the re-issue window, and logs in. Returns (true, nil) when the Manager's client now holds an operational token. ErrNoCertCredential marks a certificate-login failure whose cause is local to this host — no credential enrolled, an unreadable envelope, an expired or wrong-identity certificate, or an unavailable secure store — as opposed to a failure talking to Vault.

The distinction is load-bearing for the public client facade. A Vault that is unreachable, rate-limited, or 5xx-ing is a retry condition; a missing or unusable credential means the host must be enrolled. A transport failure carries no HTTP response, so a caller cannot reliably tell the two apart by inspecting the error alone — hence an explicit sentinel rather than a heuristic. See client.AuthenticateCached.

View Source
var ErrTokenAtRest = errors.New("token file could not be removed")

ErrTokenAtRest marks a login that succeeded at Vault but could not honour the no-token-at-rest guarantee, because a token file already on disk could not be removed (on Windows, typically a sharing violation from antivirus, backup, or indexing holding it open).

It exists so callers can tell this apart from "the credential on this host is unusable". They look identical — both are just an error out of certLogin — but they call for opposite responses: an unusable credential should be re-seeded, whereas here the certificate is perfectly good and re-seeding fixes nothing. Without the distinction authenticateMTLS treats an undeletable file as a broken credential and falls through to a full interactive bootstrap (an OIDC browser flow or an LDAP TTY prompt) plus a fresh PKI issuance, which then hits the same undeletable file and fails anyway — so a file the OS briefly will not unlink costs a human prompt and a wasted certificate on every startup.

Functions

func BaseMethod added in v0.23.0

func BaseMethod(method string) string

BaseMethod strips a modifier suffix ("+tpm" or "+os"), returning the underlying auth flow: "oidc", "ldap", "token", or "mtls". The login dispatch switches on this so a modified variant routes to the same flow as its base.

func BuildCSR added in v0.39.0

func BuildCSR(signer crypto.Signer, commonName string) (string, error)

BuildCSR creates a PEM-encoded CSR over the given signer. It is exported so the short-lived client-certificate source builds its requests the same way.

func Downscope added in v0.25.0

func Downscope(ctx context.Context, vc *vault.Client, token string, c PolicyConstraint) (string, error)

Downscope exchanges a freshly-minted broad login token for a least-privilege child token carrying only the configured policies, when the constraint is active. The child is minted on an isolated sibling of vc (CreateChildTokenFor) so vc itself is never set to the broad token — Vault still enforces that the requested policies are a subset of the parent's, so this can only drop privilege. Returns the token the caller should adopt and persist: the downscoped child when a constraint is active, otherwise the original token unchanged.

Downscope is a pure "maybe exchange the token" helper: it never warns and never mutates vc. The transition notice for an unrestricted login lives in WarnUnrestrictedPolicy, called only at the sites that adopt a final operational token — so the mtls bootstrap login (whose broad token is transient and never persisted) does not emit it.

On both the active-success and the failure paths the caller's shared client is left exactly as it was, so a downscope failure cannot leave the broad token installed on (or retrievable from) the web server's shared client, and there is no window in which a concurrent reader observes the broad token. The caller is therefore responsible for adopting the returned token — it must call vc.SetToken on the result itself; Downscope deliberately does not.

A downscoping failure is returned as an error rather than silently falling back to the broad token: least privilege must fail closed. The caller treats it like any other login failure.

func IsDenied added in v0.33.0

func IsDenied(err error) bool

IsDenied reports whether err is the suppressed-token sentinel. Distinct from IsTokenRejected, which classifies a live Vault error: this one says "we did not ask", where that one says "we asked and were refused".

func IsExpired

func IsExpired(err error) bool

IsExpired reports whether err is the token-expired sentinel. The Start loop uses this to route expired tokens through the same recovery path as a 403 response.

func IsNoToken added in v0.33.0

func IsNoToken(err error) bool

IsNoToken reports whether err is the no-token sentinel.

func IsRenewFailed added in v0.30.0

func IsRenewFailed(err error) bool

IsRenewFailed reports whether err came from a failed renewal of a token that still passes lookup-self. The Start loop uses it to attempt a peer borrow: a token at its max TTL cannot be extended, so the only way to stay authenticated without an interactive login is to pick up someone else's.

func IsTokenRejected added in v0.33.0

func IsTokenRejected(err error) bool

IsTokenRejected reports whether err from a Vault call is Vault saying the presented token is no good — a 403 (revoked, expired, or denied) or the lifecycle manager's expired-token sentinel. It is deliberately narrow: anything else (connection refused, a sealed or failing-over Vault, a 5xx) is a fault of the moment rather than a verdict on the token, and must leave the token usable so the next attempt can succeed.

func PersistTokenAtRest added in v0.31.0

func PersistTokenAtRest(method string) bool

PersistTokenAtRest reports whether the operational Vault token may be cached on disk at all. It is false for exactly one method — "mtls+os" — and true for every other, including any other base wearing the "+os" suffix.

The literal comparison is deliberate. The suffix parses on any base for uniformity (BaseMethod strips it), but nothing else about "+os" is implemented off "mtls": there is no auth_method allowlist, so a config naming "oidc+os" loads and routes to authenticateOIDC, which writes the token file unconditionally and never consults this predicate. Keying off the bare suffix would make this function claim no-persist for a flow that then persists anyway — a guarantee stated but not enforced, which is worse than not claiming it. This godoc is the canonical statement of that reasoning; other sites applying the gate should point here rather than restate it.

The point of "mtls+os" is that the credential lives inside the OS-native certificate store and never leaves it: the CNG key is generated non-exportable and verified so at generation time. A plaintext 0600 token file sitting beside that store would undo the guarantee — it is a bearer credential for the same Vault identity, obtainable by anything that can read one file, protected by nothing the OS store provides.

Unlike "+tpm", which keeps a file and seals it, "+os" keeps no file. Sealing under the OS store is not available in the way the TPM offers it: the CNG key is deliberately non-exportable and sign-oriented, and "mtls+os" accepts EC P-256 as well as RSA, so there is no decrypt primitive that works for both key types. Wrapping the token under some *other* Windows facility (DPAPI, say) would protect it, but it would also create a second durable secret-bearing artefact outside the certificate store — precisely what this method exists to avoid.

Not writing the token costs little, because it is not load-bearing here. The certificate is the credential; an operational token is re-derived from it by Manager.CertLoginFromStore with no human involvement, so the file was only ever a latency optimisation. Callers that previously read it need a different answer under this method — see the call sites in cmd/dotvault and client.AuthenticateCached.

func ReadTokenEnv

func ReadTokenEnv() string

ReadTokenEnv reads the Vault token from the DOTVAULT_TOKEN environment variable. VAULT_TOKEN is deliberately ignored — it belongs to the `vault` CLI, and honouring it would let an unrelated shell session's token leak into the daemon (the Vault SDK's own VAULT_TOKEN pickup is likewise neutralised in internal/vault.NewClient).

An env-var token is necessarily plaintext: there is no way to TPM-seal an environment value. The "+tpm" sealing applies only to the token file.

func ReadTokenFile

func ReadTokenFile(path string) (string, error)

ReadTokenFile reads a Vault token from a file, trimming whitespace. Returns empty string (not error) if the file doesn't exist.

A file written by WriteTokenFile with sealing on carries sealedTokenPrefix; this transparently unseals it via the TPM. A plaintext file is returned verbatim, so existing token files keep working and migration is free.

func RemoveTokenFile added in v0.31.0

func RemoveTokenFile(path string) error

RemoveTokenFile deletes a cached token file, treating an already-absent file as success.

It exists for auth methods that must not leave a token at rest ("mtls+os"). Simply declining to write is not enough: a host that previously ran plain "mtls", or an older build of "mtls+os", still has a readable plaintext token on disk, and it stays valid until its TTL runs out. Without an explicit removal the no-plaintext-at-rest guarantee would hold only for hosts that had never run anything else — which is not a guarantee worth stating.

func ResolveToken

func ResolveToken(tokenFilePath string) string

ResolveToken returns a Vault token, checking the DOTVAULT_TOKEN env var first, then the token file. Returns empty string if neither is set. A sealed token file that cannot be unsealed resolves to "" (the warning is logged in ReadTokenFile), which the auth flow treats as "no usable token, re-authenticate" — never a silent plaintext fallback.

func SealTokenAtRest added in v0.23.0

func SealTokenAtRest(method string) bool

SealTokenAtRest reports whether the auth method requests TPM-sealing of the token file — the "+tpm" suffix. When true, WriteTokenFile seals the token under the TPM and writes a self-describing sealed envelope, which ReadTokenFile transparently unseals on read (so the daemon, the CLI, and the public client/ facade all consume it without knowing the method). The "+os" modifier does NOT seal the token (it governs cert-key storage only).

func WarnUnrestrictedPolicy added in v0.25.0

func WarnUnrestrictedPolicy(c PolicyConstraint)

WarnUnrestrictedPolicy logs the one-line transition warning when no least-privilege constraint is configured, nudging the operator toward vault.policies before a future release makes restriction the default. It is a no-op once the operator has opted in.

Call it only at the sites that adopt a final operational token from a downscopeable login: the real CLI oidc/ldap logins, the mtls operational login, and the web oidc/ldap handlers. It is deliberately NOT called on the mtls bootstrap sub-login (whose broad token is transient, unpersisted, and about to be replaced by the downscoped cert-auth token), nor for the `token` auth method / web token-login (a user-supplied token dotvault never downscopes — the nudge to set vault.policies would not apply). Keeping the notice tied to the operational token is why it lives here rather than inside Downscope, which the bootstrap path also runs.

func WriteTokenFile

func WriteTokenFile(path string, token string, seal bool) error

WriteTokenFile writes a Vault token to a file with 0600 permissions. When seal is true the token is sealed under the TPM (machine-bound) and written as a self-describing sealed envelope that ReadTokenFile transparently unseals. Sealing requires a working TPM (Linux/Windows); seal=true on a host with no hardware backend returns an error rather than silently writing plaintext — the same no-silent-fallback contract as mtls+tpm key sealing.

An empty path is a deliberate no-op: it means "do not persist this token". The mTLS bootstrap login uses this so its broad, PKI-capable bootstrap token lives only in memory (long enough to mint the certificate) and is never left in the on-disk cache if a later step fails — only the final cert-auth working token is persisted, by certLogin with the real path.

Types

type CertCredentialInfo added in v0.31.0

type CertCredentialInfo struct {
	// Present is false when no credential is enrolled on this host.
	Present bool
	// Identity is the OS user the credential was issued to.
	Identity string
	// Backend is the securestore that holds the key ("file", "tpm", "os").
	Backend string
	// NotAfter is the certificate's expiry. Zero when unknown.
	NotAfter time.Time
	// Expired reports whether NotAfter is in the past. A credential that is
	// present but expired cannot mint a token: re-issuance needs a still-valid
	// certificate, so recovering from this state requires a fresh bootstrap.
	Expired bool
}

CertCredentialInfo is a read-only view of the stored certificate credential, for callers that need to report or reason about it without performing a login. It deliberately exposes no key material and no handle.

func InspectCertCredential added in v0.31.0

func InspectCertCredential(storageDir string) (CertCredentialInfo, error)

InspectCertCredential reports what is knowable about the stored certificate credential from disk alone — no Vault call, no key use, no side effects.

It exists because "is this host set up?" is a different question from "does this host hold a token", and under mtls+os it is the only one with a durable answer: no token is kept at rest, so the credential is the thing to look at. `dotvault status` reports from it, and `dotvault login-check` uses it to decide whether a shell startup needs to warn about a bootstrap.

A malformed envelope is reported as an error rather than as absent, so a caller can distinguish "never enrolled" from "enrolled but broken".

type CredentialVersion added in v0.39.0

type CredentialVersion struct {
	ModTime time.Time
	Size    int64
	// contains filtered or unexported fields
}

CredentialVersion identifies one write of credential.json: its full-resolution mtime, its size and the file's identity. Comparable with ==.

The envelope is replaced by temp file and rename, so every rotation lands as a new file, and the identity is what catches a rotation that keeps the size and lands in the same mtime tick on a filesystem with a coarse clock. On Unix it is the device and inode. On Windows it is the volume serial number and file index (GetFileInformationByHandle, which opens the file for attributes only, sharing read, write and delete so it never blocks a writer's rename); if that query fails the identity is left zero and the version falls back to mtime and size, as it is on platforms with neither.

func StatCredential added in v0.39.0

func StatCredential(storageDir string) (CredentialVersion, error)

StatCredential reports the version of the credential envelope under storageDir without reading it, for a caller that keeps an exported HeldCertificate and wants to know cheaply whether it is still current. It stats the same file ExportHeldCertificate reads; an empty storageDir is refused for the same reason it is there.

type HeldCertificate added in v0.39.0

type HeldCertificate struct {
	// CertPEM is the leaf and chain exactly as recorded in the envelope.
	CertPEM []byte
	// KeyPEM is the private key as a PKCS#8 "PRIVATE KEY" block.
	KeyPEM []byte
	// NotAfter is the leaf's expiry.
	NotAfter time.Time
	// Serial is the leaf's serial as recorded in the envelope.
	Serial string
	// Version identifies the credential.json this was read from, taken
	// before the content was read, so a caller comparing it with a later
	// StatCredential notices a rotation that replaced the credential.
	Version CredentialVersion
}

HeldCertificate is the certificate dotvault already holds for Vault cert auth, exported for use by other tools. It exists only for a host running plain `mtls`, whose key sits in the file backend and so is already readable by this user; nothing here widens what the user could read from disk.

func ExportHeldCertificate added in v0.39.0

func ExportHeldCertificate(storageDir, method, username string) (*HeldCertificate, error)

ExportHeldCertificate returns the certificate and key stored for cert auth. It is refused with ErrHeldNotExportable unless method is exactly "mtls" and the envelope's backend is "file". It wraps ErrNoCertCredential when no usable credential exists: the envelope is absent, expired, or issued to another user than username. No error or log line carries key material.

type LifecycleManager

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

LifecycleManager manages token TTL checks and renewal.

func NewLifecycleManager

func NewLifecycleManager(client *vault.Client, checkInterval time.Duration, disableRenewal bool) *LifecycleManager

NewLifecycleManager creates a new token lifecycle manager. When disableRenewal is true the manager still monitors TTL and signals re-auth when the token expires, but never calls RenewSelf.

func (*LifecycleManager) NeedsReauth

func (lm *LifecycleManager) NeedsReauth() bool

NeedsReauth reports whether the client's token should be treated as unusable right now — either because re-authentication has been signalled, or because the manager is mid-replacement and the client still carries the token that failed.

Consumers of this as a gate (the SSH agent's Sign/List, the web UI's /api/v1/token) want both: they are asking "is it safe to use the shared client", and a replacement in flight answers no just as firmly as a declared re-auth. The manager's own branch decisions read lm.needsReauth directly instead, because those turn on whether the *signal* has been raised.

func (*LifecycleManager) NotifyRejected added in v0.34.0

func (lm *LifecycleManager) NotifyRejected(err error)

NotifyRejected lets a subsystem that shares the daemon's Vault client — the SSH agent's vault-ca source minting a certificate, a managed SSH forward resolving its signing identity — report a 403/invalid-token failure it observed independently of this manager's own LookupSelf poll, so recovery starts now instead of waiting out checkInterval (5 minutes by default).

Without this, a token that goes bad is detected by whichever of these call paths happens to ask Vault a question first, but only THIS manager's answer matters: the agent and sshfwd have no channel back into it, so they just keep retrying the same dead token on their own backoff while this manager sits blind until its next tick.

err is classified with the same predicate checkAndRenew uses (vault.IsForbidden / IsExpired via IsTokenRejected) so a transient fault — Vault unreachable, sealed, mid-failover — does not trigger a recovery pass over nothing: those must stay retryable, not treated as a verdict on the token. Coalescing and non-blocking like Reload: several sources hitting the same dead token in the same instant collapse to one wakeup, and a call before Start is buffered rather than dropped.

Rate-limited to at most once per recoveryInterval (see lastRejectNotifyAt): IsTokenRejected can't tell "the shared token is dead" apart from "this one Vault path denied the token", and the second case can repeat far faster than a real outage would — once per SSH connection attempt, sub-second under load — without ever becoming true grounds for another lookup-self. The limiter is deliberately coarser than rejectCh's channel-buffer coalescing: that only catches a concurrent burst landing in the same instant, not a sustained stream arriving one at a time. A call that misses the window is simply dropped — the next scheduled tick or a later report still gets a chance.

The window is consumed only by a call that actually queues a nudge. A report dropped because rejectCh is already full has cost nothing and releases the window again: letting it burn the full interval would mean a redundant report suppressing the next genuine one for as long as a real nudge would have.

The signalled pass runs the full recovery branch (tryReload then tryRecover under the withTokenInFlux gate), not just tryReload — unlike Reload, which only re-reads file/env/socket candidates. A rejection report means "Vault has spoken", the same verdict checkAndRenew's own 403 produces, so it must reach the same fallback-to-unattended-recovery path (the case that matters for mtls+os, which keeps no token file to reload from at all).

func (*LifecycleManager) ReauthSignalled added in v0.34.0

func (lm *LifecycleManager) ReauthSignalled() bool

ReauthSignalled reports whether the manager has declared that it needs a new token from outside — the state signalReauth raises and clearReauth ends.

This is the *signal*, and it is the narrower of the two: it excludes a replacement already in flight. A caller asking "should I go find this daemon a token" wants this, because during a reload the manager is already doing exactly that. NeedsReauth is the gate, and answering the signal question with it would make every routine reload look like a daemon in need of rescue.

func (*LifecycleManager) Reload

func (lm *LifecycleManager) Reload()

Reload signals the lifecycle goroutine to perform an immediate tryReload on the next scheduling pass — used by the SIGHUP handler and by the in-process token-file watcher (internal/tokenwatch) so a freshly-written token file (the configured tokenFilePath, by default ~/.dotvault-token) is picked up without waiting for the 5-minute lifecycle tick. Coalescing: concurrent or back-to-back calls collapse into a single reload. Safe to call before or after Start; calls made before Start are buffered and consumed by the goroutine on its first select.

func (*LifecycleManager) SetBorrower added in v0.37.0

func (lm *LifecycleManager) SetBorrower(b peer.Borrower)

SetBorrower wires the peer socket pool so the recovery path can borrow a peer's live token before declaring re-auth necessary. Nil disables it.

func (*LifecycleManager) SetOnReauth

func (lm *LifecycleManager) SetOnReauth(fn func())

SetOnReauth registers a callback fired when the manager transitions into the needs-reauth state. The callback runs synchronously on the lifecycle goroutine — keep it short. In web mode this is used to clear the in-memory Vault token so the web UI reflects "logged out".

func (*LifecycleManager) SetRecover added in v0.31.0

func (lm *LifecycleManager) SetRecover(fn func(context.Context) error)

SetRecover registers an unattended recovery function that mints a fresh token from a credential this host already holds. See the recover field.

It must be safe to call repeatedly (it is retried on every recovery poll) and must not block indefinitely — it runs on the lifecycle goroutine, so a hung call stalls token management. It must not prompt: a background goroutine has no user attached.

func (*LifecycleManager) SetTokenDenylist added in v0.33.0

func (lm *LifecycleManager) SetTokenDenylist(d *TokenDenylist)

SetTokenDenylist replaces the manager's denied-token cache with a shared one. The daemon uses this to hand over the cache its startup path (the initial reuse check, the peer borrow, and the headless idle loop) has already been populating, so a token those steps watched Vault reject is not re-presented once the lifecycle manager takes over. A nil argument is ignored — the manager always has a working cache.

Call before Start: like the other Set* wiring, this is an unsynchronised field write that the lifecycle goroutine reads.

func (*LifecycleManager) SetTokenFilePath

func (lm *LifecycleManager) SetTokenFilePath(p string)

SetTokenFilePath wires a token file path so that on detection of an invalid/expired token the manager will attempt to reload (and re-validate) the token from disk or DOTVAULT_TOKEN before declaring re-auth necessary. This lets an external facility (e.g. a tty session running `dotvault login`) recover a running daemon without a restart.

func (*LifecycleManager) Start

func (lm *LifecycleManager) Start(ctx context.Context) <-chan error

Start begins the token lifecycle goroutine. Returns a channel that receives errors (e.g., when re-auth is needed). The goroutine stops when ctx is cancelled.

type LoginStatus

type LoginStatus struct {
	State      string            `json:"state"`
	Token      string            `json:"-"`
	Error      string            `json:"error,omitempty"`
	MFAMethods []vault.MFAMethod `json:"mfa_methods,omitempty"`
}

LoginStatus represents the current state of an async login attempt.

type LoginTracker

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

LoginTracker manages async login attempts keyed by session ID.

func NewLoginTracker

func NewLoginTracker(vc *vault.Client) *LoginTracker

NewLoginTracker creates a new LoginTracker.

func (*LoginTracker) Clear

func (lt *LoginTracker) Clear(sessionID string)

Clear removes a completed login session.

func (*LoginTracker) Close

func (lt *LoginTracker) Close()

Close stops the background GC goroutine.

func (*LoginTracker) GetStatus

func (lt *LoginTracker) GetStatus(sessionID string) *LoginStatus

GetStatus returns the current login status for a session. Returns nil if the session does not exist.

func (*LoginTracker) StartLogin

func (lt *LoginTracker) StartLogin(sessionID, mount, username, password string)

StartLogin begins an async LDAP login attempt. The login runs in a background goroutine with a 5-minute timeout. Poll GetStatus to check progress.

func (*LoginTracker) SubmitTOTP

func (lt *LoginTracker) SubmitTOTP(sessionID, passcode string)

SubmitTOTP submits a TOTP passcode for an in-progress MFA login.

type MTLSParams added in v0.23.0

type MTLSParams struct {
	// Connectivity for building a cert-presenting login client.
	VaultAddress  string
	CACert        string
	TLSSkipVerify bool

	Method          string // "mtls" | "mtls+tpm" | "mtls+os"
	BootstrapMethod string
	BootstrapMount  string
	CertMount       string
	CertRole        string
	PKIMount        string
	PKIRole         string
	KeyType         string
	KeyBits         int    // RSA modulus size; 0 = backend default (2048). Ignored for EC.
	CommonName      string // template over {{.user}}
	TTL             string
	ReissueBefore   time.Duration
	// SkipRevokeSuperseded is the resolved vault.mtls.revoke_superseded
	// tri-state, INVERTED: true means do not revoke the certificate a rotation
	// replaced. See MTLSConfig.RevokeSuperseded for why that opt-out exists.
	//
	// Negative on purpose. MTLSParams is built at several sites — the daemon,
	// the client facade, the integration harness — and a positively-spelled
	// field would make "forgot to set it" mean "revocation off", silently
	// disabling a security default. Spelled this way the zero value is the safe
	// one, so only a caller that deliberately opts out has to say anything.
	SkipRevokeSuperseded bool
	SealToPCRs           bool
	StorageDir           string
	BYOCert              string
	BYOKey               string
}

MTLSParams carries everything the cert-auth flow needs. It is populated by the daemon (cmd/dotvault) from the validated vault.mtls config and attached to a Manager whose AuthMethod is "mtls", "mtls+tpm", or "mtls+os".

type Manager

type Manager struct {
	VaultClient   *vault.Client
	TokenFilePath string
	// AuthMethod is the configured method: "oidc", "ldap", "token", "mtls",
	// "mtls+tpm", or "mtls+os". A "+tpm" suffix on any base method (e.g.
	// "oidc+tpm") also requests TPM-sealing of the cached token file at rest;
	// for "mtls+tpm" that is in addition to the cert key the cert flow already
	// seals. The "mtls+os" modifier instead stores the cert key in the OS-native
	// certificate store (it does not seal the token).
	AuthMethod string
	AuthMount  string // auth mount path
	AuthRole   string // optional role
	Username   string
	// OIDCCallbackPort is the fixed local TCP port authenticateOIDC binds for
	// the OAuth redirect_uri (vault.oidc_callback_port). Zero defaults to
	// 8250 (the `vault` CLI's own default); if that port is unavailable,
	// authenticateOIDC falls back to a random port. See oidc.go.
	OIDCCallbackPort int
	// Borrower, when non-nil, is tried first by Login: a live token borrowed
	// from a peer dotvault (dotvault-to-dotvault sharing) means no browser,
	// TTY or TPM is needed. Callers pass a *peer.Pool built from
	// config.TokenBorrowSockets. Best-effort; a nil Borrower is skipped.
	Borrower peer.Borrower
	// BorrowOnly, when true, makes Login refuse to run AuthMethod's
	// fresh-auth flow at all: if the Borrower borrow above does not
	// produce a usable token, Login returns ErrBorrowOnly instead of falling
	// through to the oidc/ldap/mtls/token dispatch below. Mirrors
	// config.VaultConfig.BorrowOnly; see its doc comment for the use case.
	BorrowOnly bool
	// Policy narrows a freshly-minted login token to a least-privilege child
	// token (vault.policies / vault.no_default_policy). The zero value applies
	// no narrowing — the token carries every policy the auth role granted,
	// today's behaviour. Consulted by the oidc/ldap/mtls flows; the bootstrap
	// login that mints an mtls cert is deliberately left un-narrowed because it
	// needs the pki/sign capability.
	Policy PolicyConstraint
	// MTLS is required when the base auth method is "mtls".
	MTLS *MTLSParams
	// BootstrapLogin, when non-nil, supplies the transient bootstrap token for
	// the mTLS certificate bootstrap instead of running the CLI oidc/ldap flow.
	// It returns a raw Vault token that MUST NOT have been downscoped (the
	// bootstrap needs pki/sign, which an operational policy set would strip) and
	// MUST NOT have been adopted onto any shared client.
	BootstrapLogin func(ctx context.Context) (string, error)
}

Manager orchestrates Vault authentication.

func (*Manager) Authenticate

func (m *Manager) Authenticate(ctx context.Context) error

Authenticate attempts to authenticate with Vault. It first tries to reuse an existing token, then falls back to the configured method.

func (*Manager) CertLoginFromStore added in v0.31.0

func (m *Manager) CertLoginFromStore(ctx context.Context) error

CertLoginFromStore mints a fresh operational token by performing the certificate login against the credential this host already holds. It is the non-interactive half of certificate auth, split out so callers that must never involve a human can use it:

  • the daemon's unattended token recovery (LifecycleManager.SetRecover), which is what makes certificate auth headless in steady state — the cert login otherwise happens only at startup, and ReissueIfDue rotates the *certificate*, not the token, so an expired token used to strand the daemon until a restart despite the credential sitting right there;
  • the public client facade (client.AuthenticateCached), where a consumer on a cert-auth host can obtain a token without a cached one and without ever prompting.

It deliberately does NOT fall back to the bootstrap flow. Bootstrap needs a human; these callers have none — a background goroutine with nobody attached, or a library inside someone else's process. Spontaneously launching a browser, or blocking on a login that will never come, would be worse than reporting the failure. A host whose certificate is missing or expired past re-issue reports an error here and is handled by the caller.

It also does not rotate the certificate (see loginWithCredential): rotation belongs to the startup path and the hourly re-issue check, which own it and must not race a second writer.

Safe to call repeatedly: it re-reads the credential each time and does nothing beyond a fresh login.

func (*Manager) Login

func (m *Manager) Login(ctx context.Context) error

Login runs the configured fresh-auth flow unconditionally, without attempting to reuse an existing token. Used by `dotvault login` and as the fallback path inside Authenticate.

func (*Manager) ReissueIfDue added in v0.23.0

func (m *Manager) ReissueIfDue(ctx context.Context) error

ReissueIfDue rotates the certificate when it is inside the re-issue window, using the current operational Vault token (no human). It is a no-op for non-cert methods, when no credential exists, or when the cert is not yet due for rotation. The daemon calls this periodically so a long-running process whose token keeps renewing still rotates its certificate before expiry — without this, a warm daemon never re-enters the cert flow and the cert could expire unrotated. Safe to call repeatedly: after one successful rotation the fresh NotAfter moves out of the window and subsequent calls return nil.

type PolicyConstraint added in v0.25.0

type PolicyConstraint struct {
	// Policies is the explicit set of Vault policies the working token should
	// carry. When non-empty the login token is exchanged for a child token
	// restricted to exactly these policies (a subset of the login token's own
	// policies — Vault enforces the subset rule). Empty means "carry whatever
	// the auth role granted".
	Policies []string
	// NoDefaultPolicy, when true, strips the implicit `default` policy from the
	// downscoped token.
	NoDefaultPolicy bool
}

PolicyConstraint describes the least-privilege downscoping applied to a freshly-minted login token. Its two fields come straight from the vault config (vault.policies / vault.no_default_policy).

The zero value applies no narrowing — the working token carries every policy the auth role granted, which is dotvault's historical behaviour. Operators opt in to least privilege by populating Policies (and, increasingly, NoDefaultPolicy); see docs/configuration/config-reference.md for the staged rollout that ends with no_default_policy forced on at 1.0.

func (PolicyConstraint) Active added in v0.25.0

func (c PolicyConstraint) Active() bool

Active reports whether any narrowing is requested. With neither an explicit policy set nor no_default_policy, the login token is adopted verbatim.

type TokenDenylist added in v0.33.0

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

TokenDenylist remembers Vault tokens that Vault has already answered "denied" for, so the daemon stops re-presenting them on every poll.

The bug it exists to fix: with an expired token in ~/.dotvault-token, the lifecycle manager's recovery poll (and, at startup, the headless idle loop) re-read that same file every 10 seconds and re-ran lookup-self against it forever. Nothing about the request changed between attempts, so the answer could not either — one host produced tens of thousands of denied lookups a week, and a fleet of them produced millions.

Entries are keyed by SHA-256 of the token rather than the token itself. The cache is a pure lookup-suppression structure and never needs to reproduce a token, so hashing costs nothing and keeps a long-lived process-wide map from becoming somewhere Vault credentials accumulate. (The live token is of course still in memory on the Vault client — this is about not adding a second, broader home for dead ones.)

All methods are safe on a nil receiver, so a call site that has no denylist wired (tests, one-shot commands) needs no branch.

func NewTokenDenylist added in v0.33.0

func NewTokenDenylist() *TokenDenylist

NewTokenDenylist returns an empty denylist using the default re-probe window.

func (*TokenDenylist) Clear added in v0.33.0

func (d *TokenDenylist) Clear(ctx context.Context) int

Clear drops every suppression and reports how many were dropped. Called when something that plausibly changes the credential situation happens — the token file being rewritten, a peer socket reconnecting, an operator SIGHUP — so a token given up on gets an immediate retry rather than waiting out the window. A token Vault denies again is re-denied on the spot and suppression resumes.

func (*TokenDenylist) Denied added in v0.33.0

func (d *TokenDenylist) Denied(ctx context.Context, token string) bool

Denied reports whether token is currently suppressed, and records the avoided-lookup metric when it is. An expired suppression is dropped here, so the next attempt goes to Vault normally and either succeeds (the server-side cause cleared) or re-denies (restarting the window).

The empty token is never suppressed: "no token at all" is a different state, handled by the caller's own empty checks, and treating it as a denylist entry would collide across unrelated call sites.

func (*TokenDenylist) Deny added in v0.33.0

func (d *TokenDenylist) Deny(token string) bool

Deny suppresses token for the re-probe window and reports whether this was a new suppression (as opposed to extending one already in force). Callers use the return value to log once per episode rather than once per attempt.

func (*TokenDenylist) Len added in v0.33.0

func (d *TokenDenylist) Len() int

Len reports how many suppressions are currently held, lapsed ones included (they are dropped lazily on the next Denied). For tests and introspection.

func (*TokenDenylist) NoteRejection added in v0.33.0

func (d *TokenDenylist) NoteRejection(ctx context.Context, token string, err error)

NoteRejection records token when err is Vault's way of saying the token itself was rejected, logging and metering the first suppression of an episode. Errors that mean anything else (Vault unreachable, sealed, a 5xx) are ignored: those are transient, and suppressing a token over them would turn a blip into a stall.

Jump to

Keyboard shortcuts

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