agent

package
v0.1.54 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 57 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 agent is the node agent core: it enrolls with the panel, keeps ONE agent session open (mTLS Connect by default, or the signed WebSocket link when the agent has a link URL and the panel advertises it; a link that fails to establish falls back to mTLS and is retried after a hold period; reconnecting with backoff), applies desired state to engines, reports traffic reliably (seq + ack), executes commands and serves its own log. The wire protocol is specified in the comment block of proto/mistgate/agent/v1/agent.proto; this package implements it, nothing more.

Concurrency model: one worker goroutine owns every mutation of engine and host state (desired-state apply, kick, restart, retire, credential-expiry sweep), so the engines see one caller for Apply/Remove/ Kick as their contract demands. Each stream has a reader (the session goroutine) and one writer; the statistics collector, certificate renewal and the expiry timer run for the agent's whole life, across reconnects.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotEnrolled is returned by New when the state directory holds no identity.
	ErrNotEnrolled = errors.New("agent is not enrolled (run `mistgate-node enroll` first)")
	// ErrRetired is returned by Run after the panel retired the node; the caller should exit 0.
	ErrRetired = errors.New("node retired by the panel")
)

Functions

func IsEnrolled

func IsEnrolled(dir string) bool

IsEnrolled reports whether dir holds an identity (enroll writes identity.pem last).

Types

type Agent

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

Agent is the node agent. Build it with New and run it with Run.

func New

func New(cfg Config, engines map[string]engine.Factory, host hostctl.Host) (*Agent, error)

New loads the identity from cfg.StateDir and builds the engines. The panel is not contacted. Returns ErrNotEnrolled when `enroll` has not been run.

func (*Agent) AwgBackend

func (a *Agent) AwgBackend() string

AwgBackend returns NodeSettings.awg_backend ("" = auto). The awg engine factory asks for it when it builds its backend, like the engines ask for DNS.

func (*Agent) ClientIPv6Disabled added in v0.1.22

func (a *Agent) ClientIPv6Disabled() bool

ClientIPv6Disabled returns NodeSettings.client_ipv6_disabled: "IPv6 for clients" is off. The direct egress of the protocol engines asks for it on every dial, like the engines ask for DNS.

func (*Agent) DNS

func (a *Agent) DNS() []string

DNS returns the resolvers from NodeSettings (empty = engine default). Engines call it per use.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context) error

Run blocks until ctx is cancelled (returns nil) or the panel retires the node (returns ErrRetired). On a normal stop the engines are closed but host state (hop rules, sysctl) is left in place so the node keeps its baseline across an agent restart.

func (*Agent) WarpEvent

func (a *Agent) WarpEvent(ev warp.Event)

WarpEvent turns an event of the WARP manager into an agent Event (warp_state, warp_needs_attention). The manager is built before the agent, so its Emit option calls this through a closure.

type Config

type Config struct {
	// StateDir holds the identity and the persisted desired state (created by Enroll).
	StateDir string
	// LinkURL is the full wss://host/<secret-prefix> base for the optional signed WebSocket transport.
	LinkURL string
	// Version is reported in Hello; defaults to buildinfo.Version.
	Version string
	// Built is the Unix time of the source commit (Hello.built); 0 = buildinfo.BuiltUnix().
	Built int64
	// Updater is the self-update machinery (internal/node/update). Nil = this agent never lists an update capability and
	// refuses UpdateAgent and RollbackAgent.
	Updater *update.Updater
	// Log receives the agent's records; every record also goes to the in-memory ring that LogRequest reads.
	// Nil = slog.Default().
	Log *slog.Logger

	// Host-side services handed to the engines (engine.Env). Nil Certs means engines get no certificates,
	// nil Egress means only a "no egress configured" error. Nil Masquerade uses the persisted node decoy site.
	Certs      engine.CertSource
	Egress     func(name string) (engine.Egress, error)
	Masquerade func(inboundID string) http.Handler

	// DoctorEnv adjusts the doctor's view of the machine before the doctor is built (tests point it at a fake
	// root directory and fake commands). Nil = the real host.
	DoctorEnv func(doctor.Env) doctor.Env

	// Warp is the node-level WARP manager (internal/node/warp.Manager). Nil = this build has no WARP: the agent does not
	// list "warp/1", and an inbound whose egress is WARP is not started. The manager is also what Egress("warp") returns.
	Warp WarpManager
	// UnitGen is the generation of the systemd unit the agent runs from (MISTGATE_UNIT_GEN); 3 is listed as "unit/3".
	UnitGen int
	// UnitUnderSystemd detects the service manager environment even if this build cannot launch unit refresh.
	UnitUnderSystemd bool
	// UnitSkipReason is "other_unit" when the process belongs to systemd but not mistgate-node.service.
	UnitSkipReason string
	// UnitRefreshLauncher is available only in Linux systemd services; nil disables refresh_unit and its capability.
	UnitRefreshBusy     func(context.Context) error
	UnitRefreshReserve  func(context.Context) (release func(started bool), err error)
	UnitRefreshLauncher func(context.Context, func()) error
	// AwgPrepare builds the AmneziaWG kernel module on request (internal/node/awgprep). Nil = this agent does not list
	// "awg-prepare/1", and the admin UI keeps showing the manual command.
	AwgPrepare *awgprep.Controller
	// SpeedTest runs one bandwidth measurement (MeasureBandwidth). Nil = the real one against the public test servers; tests
	// give a fake, since they have no internet.
	SpeedTest func(ctx context.Context) (speedtest.Result, error)

	// MaxPending and MaxPendingBytes bound the queue of unacked reliable messages (defaults 2160 = 6 h of
	// 10 s batches, and 32 MiB).
	MaxPending      int
	MaxPendingBytes int
}

Config is what the caller (cmd/mistgate-node, or a test) provides.

type EnrollConfig

type EnrollConfig struct {
	StateDir         string
	Panel            string // host:port
	SNI              string
	CASHA256         string // hex fingerprint of the panel CA certificate (colons and case ignored)
	Token            string
	Version          string // defaults to buildinfo.Version
	Force            bool   // overwrite an existing identity
	ResumePendingKey bool   // persist and reuse the CSR key if enrollment is interrupted
	Timeout          time.Duration
	// LinkURL (wss://host/<secret-prefix>/) enrols over the panel's public link route instead of the pinned mTLS
	// endpoint: system-root TLS carries the token, the CA pin then vouches for the panel. Exclusive with Panel and SNI.
	LinkURL string
	// contains filtered or unexported fields
}

EnrollConfig is the input of the `enroll` command.

type Meta

type Meta struct {
	Panel  string `json:"panel"`   // host:port
	SNI    string `json:"sni"`     // secret agent SNI
	NodeID string `json:"node_id"` // informational; the certificate is authoritative
	// Link is the wss://host/<secret-prefix>/ the agent enrolled through. Set = link-only: the agent never dials mTLS
	// (Panel and SNI are empty), renews over its link session and lists no self-update.
	Link string `json:"link,omitempty"`
}

Meta is what enrollment leaves next to the key material.

func Enroll

func Enroll(ctx context.Context, cfg EnrollConfig) (Meta, error)

Enroll generates a P-256 key and a CSR, exchanges the one-time token for a node certificate over TLS that trusts ONLY a CA with the given fingerprint, and stores key, certificate, CA and panel address.

type SettingsAware

type SettingsAware interface {
	NodeSettings(ctx context.Context, st *pb.NodeSettings) (reset bool)
}

SettingsAware is implemented by an engine whose configuration comes from NodeSettings (awg: the backend). The worker calls NodeSettings before every reconcile with the settings the agent holds; an engine that dropped its inbounds because of a change returns reset=true and every inbound of its protocol is applied again in the same reconcile.

type WarpManager

type WarpManager interface {
	// Apply makes the node match the spec: nil removes WARP, Enabled=false pauses it. Idempotent and cheap for a
	// spec it already runs (it only re-asserts the routing).
	Apply(ctx context.Context, spec *plugin.WarpSpec) error
	// Reconnect rebuilds a down tunnel without changing its account or routed subnets. False means it recovered already.
	Reconnect(ctx context.Context) (bool, error)
	// CheckNow retries one current failed check and reports whether WARP is down at its failure threshold.
	CheckNow(ctx context.Context) (checked, thresholdDown bool, err error)
	// SetRoutedSubnets sets the client subnets of the awg inbounds with egress "warp".
	SetRoutedSubnets(ctx context.Context, subnets []netip.Prefix) error
	// Configured says whether the node has a WARP configuration (paused included).
	Configured() bool
	// Health is the last measured state; ok=false when the node has no WARP.
	Health() (warp.Health, bool)
	// Preflight lists clashes with the host (routing table, rule preferences, a FORWARD drop policy); the doctor shows them.
	Preflight(ctx context.Context) []warp.Finding
	// Run drives the health checks until ctx ends.
	Run(ctx context.Context)
	// Cleanup removes everything the manager installed on the host.
	Cleanup(ctx context.Context) error
}

WarpManager is what the agent needs of internal/node/warp.Manager (the real one implements it; tests use a fake). The manager is handed to the engines through Config.Egress; the agent owns its lifecycle and feeds it the spec.

Jump to

Keyboard shortcuts

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