Documentation
¶
Overview ¶
Package fleet is the panel side of the node fleet: the panel CA and the agent endpoint (mTLS), node enrollment, the agent stream (liveness, reliable stats/events ingestion), desired-state computation and push, and the admin NodeService / FleetService handlers backed by that data.
Index ¶
- Constants
- func LinkChallenge(audience string) (nonce, frame []byte, err error)
- func LinkMarker() http.Handler
- type AdminRequest
- type CloseClass
- type Config
- type EffectKind
- type EventKind
- type Fleet
- func (f *Fleet) AgentHandler() http.Handler
- func (f *Fleet) AgentTLSConfig(h *tls.ClientHelloInfo) (*tls.Config, error)
- func (f *Fleet) ApplyFix(ctx context.Context, nodeID, fixID string, dryRun bool, ...) (*agentv1.CommandResult, error)
- func (f *Fleet) CACertPEM() string
- func (f *Fleet) CAFingerprint() string
- func (f *Fleet) CheckPorts(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)
- func (f *Fleet) CheckPortsAsSystem(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)
- func (f *Fleet) CreateProvisionEnrollment(ctx context.Context, spec provision.NodeSpec, actor string, ...) (string, string, error)
- func (f *Fleet) FleetHandler(opts ...connect.HandlerOption) (string, http.Handler)
- func (f *Fleet) LinkAccept(ctx context.Context, nodeID, audience string, nonce, authFrame []byte) (serial string, notAfter time.Time, frame []byte, ok bool)
- func (f *Fleet) LinkHandler() http.Handler
- func (f *Fleet) Live(ctx context.Context) ([]store.NodeLiveRow, error)
- func (f *Fleet) NodeHandler(opts ...connect.HandlerOption) (string, http.Handler)
- func (f *Fleet) NodeLive(ctx context.Context, nodeID string) (store.NodeLiveRow, error)
- func (f *Fleet) NodeStatusWithLive(ctx context.Context, n store.NodeRow, live store.NodeLiveRow) adminv1.NodeStatus
- func (f *Fleet) Online(ctx context.Context) []OnlineSession
- func (f *Fleet) OnlineByInbound(ctx context.Context) map[string]int
- func (f *Fleet) OnlineUsers() map[string]string
- func (f *Fleet) ProvisionNodeState(ctx context.Context, nodeID string) (string, bool, error)
- func (f *Fleet) RollbackAgent(ctx context.Context, nodeID string, wait time.Duration) (*agentv1.CommandResult, error)
- func (f *Fleet) Run(ctx context.Context) error
- func (f *Fleet) RunDoctor(ctx context.Context, nodeID string, checks []string, wait time.Duration) (*agentv1.DoctorReport, error)
- func (f *Fleet) SetHealth(h Health)
- func (f *Fleet) SetUpdates(u Updates)
- func (f *Fleet) SetWarp(w Warp)
- func (f *Fleet) StateChanged()
- func (f *Fleet) UpdateAgent(ctx context.Context, nodeID string, manifest, signature []byte, ...) (*agentv1.CommandResult, error)
- func (f *Fleet) WarpPauseApplied(ctx context.Context, nodeID string) bool
- type Health
- type OnlineSession
- type PendingRequest
- type PendingRequestKind
- type PoisonBatch
- type SessionClose
- type SessionCore
- type SessionEffect
- type SessionEvent
- type SessionState
- type Transition
- type Updates
- type Warp
Constants ¶
const APIVersion = 1
APIVersion is the agent wire API version this panel serves (Hello.api_version, EnrollRequest.api_version).
const LinkMarkerHeader = "X-Mistgate-Link"
LinkMarkerHeader carries the node id of a LinkMarker answer; the Worker strips it.
Variables ¶
This section is empty.
Functions ¶
func LinkChallenge ¶ added in v0.1.27
LinkChallenge is the panel's first handshake frame: a fresh nonce bound to the host the agent dialled. The VPS handler and the edge Durable Object both run it.
func LinkMarker ¶ added in v0.1.27
LinkMarker is what the edge mounts under its link prefix instead of LinkHandler: a Worker cannot keep a WebSocket in the panel's wasm, so a GET with an upgrade is answered 204 with the node's id, and the Worker hands the original request to that node's Durable Object.
Types ¶
type AdminRequest ¶ added in v0.1.26
type AdminRequest struct {
RequestID string
Deadline time.Time
Frame *agentv1.ConnectResponse
Kind PendingRequestKind
}
AdminRequest carries a request frame and its correlation metadata into the core.
type CloseClass ¶ added in v0.1.26
type CloseClass uint8
CloseClass identifies why a session should terminate.
const ( CloseInvalidArgument CloseClass = iota + 1 CloseFailedPrecondition CloseUnauthenticated CloseConflict CloseDeadline CloseInternal CloseCanceled )
type Config ¶
type Config struct {
// AgentSNI is the secret server name of the agent endpoint (e.g. "q3m8x2kd7w.invalid"). Required.
AgentSNI string
// PanelAddr is the host:port agents dial; it goes into the install command. Required for CreateEnrollment.
PanelAddr string
// LinkServed reports whether the signed WebSocket agent link is mounted on the public listener.
LinkServed bool
// ExpectedAgentVersion is the newest agent version this panel ships (ListNodes marks older agents).
ExpectedAgentVersion string
// Debounce is the StateChanged coalescing window. Default 200 ms.
Debounce time.Duration
// Desired is the desired-state source, required: it returns the enabled inbounds of a node with their
// complete credential sets (the access module's effective-access rule, so it exists once). Spec.ID must
// be set. This module owns revisions, hashes, deltas and push.
Desired func(ctx context.Context, nodeID string) ([]statehash.Inbound, error)
// MaxNodeBytesPerSec is the most traffic one node may report in total per second of a stats interval; a batch
// above it is dropped (see statsguard.go). Default 1.25e9 bytes/s (10 Gbit/s).
MaxNodeBytesPerSec uint64
// OnUsage is called after a stats batch added usage to these users (new used_bytes are committed), e.g.
// access.Service.Recompute, so a quota overrun takes effect within one stats interval.
OnUsage func(ctx context.Context, userIDs []string)
// OnAwgPrepareFailed is called when a node reports that the build of its AmneziaWG kernel module failed (the Telegram
// alerts hang on it). at is the time the node gave; a replay of the same report carries the same value. Must not block.
OnAwgPrepareFailed func(nodeID, code string, at int64)
// Actor returns the admin id for audit rows. Default: the signed-in admin from the auth interceptor.
Actor func(context.Context) string
Log *slog.Logger
// Now is the clock (tests). Default time.Now.
Now func() time.Time
// Limiter is the shared backend for security-sensitive limits. Nil uses bounded in-memory state.
Limiter securitylimit.Limiter
}
Config configures Fleet.
type EffectKind ¶ added in v0.1.26
type EffectKind uint8
EffectKind identifies an adapter action requested by the session core.
const ( EffectUsage EffectKind = iota + 1 EffectCommandResult EffectDoctorReport EffectLogChunk EffectWarpAttention EffectPrepareDesired EffectConnectEvents )
type EventKind ¶ added in v0.1.26
type EventKind uint8
EventKind identifies one input that the session core can process.
type Fleet ¶
type Fleet struct {
// contains filtered or unexported fields
}
Fleet is the fleet module.
func New ¶
New builds the module: it loads (or creates) the panel CA. Call Run to start the background work.
func (*Fleet) AgentHandler ¶
AgentHandler serves EnrollmentService and AgentService. Mount it on the agent endpoint only (TLS with AgentTLSConfig); it refuses requests that did not arrive with the agent SNI.
func (*Fleet) AgentTLSConfig ¶
AgentTLSConfig is the per-SNI tls.Config of the agent endpoint, for tls.Config.GetConfigForClient of the panel's main listener. For any other server name it returns (nil, nil): the listener then keeps its normal behaviour, so a prober without the secret name sees only the decoy.
For the agent SNI the panel presents a server certificate from its own CA and asks for a client certificate without demanding one (VerifyClientCertIfGiven): the Enroll RPC has no certificate yet. AgentHandler enforces per RPC that everything except Enroll carries a verified, non-revoked node certificate; VerifyConnection already rejects revoked or retired certificates at the handshake.
func (*Fleet) ApplyFix ¶
func (f *Fleet) ApplyFix(ctx context.Context, nodeID, fixID string, dryRun bool, params map[string]string) (*agentv1.CommandResult, error)
ApplyFix sends one fix (or its dry run) to a connected node with the doctor capability and waits up to the node's apply timeout for the CommandResult.
func (*Fleet) CAFingerprint ¶
CAFingerprint is the lowercase hex SHA-256 of the panel CA certificate (what install commands carry).
func (*Fleet) CheckPorts ¶ added in v0.1.28
func (f *Fleet) CheckPorts(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)
CheckPorts runs one bounded UDP delivery check and returns the sending node id (or "panel") and a stable result code.
func (*Fleet) CheckPortsAsSystem ¶ added in v0.1.29
func (f *Fleet) CheckPortsAsSystem(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)
CheckPortsAsSystem runs the same check for a panel-owned schedule and audits it as the system actor.
func (*Fleet) CreateProvisionEnrollment ¶
func (f *Fleet) CreateProvisionEnrollment(ctx context.Context, spec provision.NodeSpec, actor string, now, expires time.Time) (string, string, error)
CreateProvisionEnrollment creates the pending node, or rotates its pending enrollment token when a job is resumed. The token is returned exactly once to the caller and is never written to an audit row.
func (*Fleet) FleetHandler ¶
FleetHandler is the admin FleetService (Overview, ListEvents); see NodeHandler for opts.
func (*Fleet) LinkAccept ¶ added in v0.1.27
func (f *Fleet) LinkAccept(ctx context.Context, nodeID, audience string, nonce, authFrame []byte) (serial string, notAfter time.Time, frame []byte, ok bool)
LinkAccept is linkAccept for the edge Durable Object (the VPS runs it inside LinkHandler): it reports the certificate the agent proved.
func (*Fleet) LinkHandler ¶ added in v0.1.26
LinkHandler serves the public, signed WebSocket transport. Mount it only beneath the stored secret path prefix.
func (*Fleet) Live ¶
Live reads the durable live projection without the admin view's larger live_json column.
func (*Fleet) NodeHandler ¶
NodeHandler is the admin NodeService. Pass connect.WithInterceptors(auth.Interceptor()) so that it is behind the admin session; the path is the Connect prefix to mount it on.
func (*Fleet) NodeLive ¶ added in v0.1.29
NodeLive reads one node's durable liveness projection without live_json.
func (*Fleet) NodeStatusWithLive ¶ added in v0.1.29
func (f *Fleet) NodeStatusWithLive(ctx context.Context, n store.NodeRow, live store.NodeLiveRow) adminv1.NodeStatus
NodeStatusWithLive derives status from a projection already read for the surrounding request.
func (*Fleet) Online ¶
func (f *Fleet) Online(ctx context.Context) []OnlineSession
Online returns the open sessions reported by connected nodes' live projections.
func (*Fleet) OnlineByInbound ¶
OnlineByInbound counts the open sessions of every inbound of the connected nodes (the health and WARP dialogs say how many connections a restart or a pause drops).
func (*Fleet) OnlineUsers ¶
OnlineUsers maps each user with an open session to the node of the newest one (access.OnlineSource).
func (*Fleet) ProvisionNodeState ¶
ProvisionNodeState reports the durable fleet state and connection used to resume an installation safely.
func (*Fleet) RollbackAgent ¶
func (f *Fleet) RollbackAgent(ctx context.Context, nodeID string, wait time.Duration) (*agentv1.CommandResult, error)
RollbackAgent asks a connected node with the update capability to put its previous binary back.
func (*Fleet) Run ¶
Run drives the debounced recompute and the node-down sweeper until ctx ends, then closes all streams.
func (*Fleet) RunDoctor ¶
func (f *Fleet) RunDoctor(ctx context.Context, nodeID string, checks []string, wait time.Duration) (*agentv1.DoctorReport, error)
RunDoctor asks a connected node with the doctor capability to run checks (nil = all) and waits for the report that echoes the request. The report has been handed to Health by then. A node without the capability is never sent anything (FAILED_PRECONDITION "agent too old").
func (*Fleet) SetHealth ¶
SetHealth connects the health module. Call it before serving; nil disconnects.
func (*Fleet) SetUpdates ¶
SetUpdates connects the updates module. Call it before serving; nil disconnects (FetchUpdate answers UNIMPLEMENTED).
func (*Fleet) SetWarp ¶
SetWarp connects the WARP module. Call it before serving; nil disconnects (no WarpSpec is sent, no health is stored).
func (*Fleet) StateChanged ¶
func (f *Fleet) StateChanged()
StateChanged tells the module that something that feeds desired state changed (users, profiles, inbounds, nodes). It returns at once; a debounced recompute pushes the result to connected nodes.
func (*Fleet) UpdateAgent ¶
func (f *Fleet) UpdateAgent(ctx context.Context, nodeID string, manifest, signature []byte, wait time.Duration) (*agentv1.CommandResult, error)
UpdateAgent sends a signed manifest to a connected node with the update capability and waits up to wait for the CommandResult (the download is part of it). The agent answers before it re-executes; a stream that drops right after the answer still delivers it.
func (*Fleet) WarpPauseApplied ¶
WarpPauseApplied reports whether the node holds a paused WARP: the last state sent on its stream pauses it, and the node confirmed exactly that state. It is RestartWarp's proof that the tunnel went down; another change applied meanwhile (a state that still runs WARP) does not count.
type Health ¶
type Health interface {
// DoctorReport hands over every DoctorReport of a node (periodic, requested or the re-check after a fix).
DoctorReport(ctx context.Context, nodeID string, r *agentv1.DoctorReport)
// NodeReturned says that an active node came back after a silence of less than the blip window with an
// unchanged boot time: health writes the history record.
NodeReturned(ctx context.Context, nodeID string, silentSince, now time.Time)
// NodeHealth is what the node status and card show: the synthetic checks of the node all failing
// (noTraffic, with how many of how many) and the check of the worst FAIL of its last doctor report.
NodeHealth(nodeID string) (noTraffic bool, failed, total int, doctorFail string)
// AlertCounts feeds the badge of the Overview: active alerts not muted and not INFO, and the critical ones.
AlertCounts(ctx context.Context) (active, critical uint32)
}
Health is implemented by the health module. All methods must be cheap and must not call back into the stream they run on.
type OnlineSession ¶
type OnlineSession struct {
NodeID, UserID, DeviceID, Protocol, InboundID string
ConnectedAt time.Time
}
OnlineSession is one open client session as last reported by a node.
type PendingRequest ¶ added in v0.1.26
type PendingRequest struct {
Kind PendingRequestKind `json:"k,omitempty"`
Deadline time.Time `json:"d,omitzero"`
}
PendingRequest is serialized request metadata. VPS channels remain in the adapter; edge delivery is a later round.
type PendingRequestKind ¶ added in v0.1.26
type PendingRequestKind uint8
PendingRequestKind identifies the agent result expected for a request.
const ( PendingCommand PendingRequestKind = iota + 1 PendingDoctor PendingLog PendingAutoBandwidth )
type PoisonBatch ¶ added in v0.1.27
PoisonBatch identifies the last stats batch refused by the store.
type SessionClose ¶ added in v0.1.26
type SessionClose struct {
Class CloseClass
Reason string
}
SessionClose describes a protocol-level reason to end the connection.
type SessionCore ¶ added in v0.1.26
type SessionCore struct {
// contains filtered or unexported fields
}
SessionCore processes one event at a time without owning goroutines, timers, channels, or transports.
func NewSessionCore ¶ added in v0.1.26
func NewSessionCore(f *Fleet) *SessionCore
NewSessionCore creates a session transition engine backed by fleet services.
func (*SessionCore) Step ¶ added in v0.1.26
func (c *SessionCore) Step(ctx context.Context, state *SessionState, event SessionEvent) (Transition, error)
Step processes one event and writes the resulting protocol state back to the supplied session. On error the caller must end the session; state may already reflect work completed before the error.
type SessionEffect ¶ added in v0.1.26
type SessionEffect struct {
Kind EffectKind
RequestID string
PreviousNode *store.NodeRow
BootAt time.Time
At time.Time
CommandResult *agentv1.CommandResult
DoctorReport *agentv1.DoctorReport
LogChunk *agentv1.LogChunk
Users []string
WarpReason string
}
SessionEffect asks the adapter to perform work requested by a core transition.
type SessionEvent ¶ added in v0.1.26
type SessionEvent struct {
Kind EventKind
At time.Time
Frame *agentv1.ConnectRequest
Request *AdminRequest
Prepared *preparedDesiredState
Err error
}
SessionEvent is a timestamped input to SessionCore.Step.
type SessionState ¶ added in v0.1.26
type SessionState struct {
Version uint8 `json:"v"`
NodeID string `json:"n,omitempty"`
OwnerGeneration uint64 `json:"o,omitempty"`
InstanceID string `json:"i,omitempty"`
LivenessNanos int64 `json:"l,omitempty"`
HelloDeadline time.Time `json:"h,omitzero"`
// LivenessDeadline keeps Go's monotonic reading on the VPS: a wall-clock step cannot close a live session.
LivenessDeadline time.Time `json:"d,omitzero"`
AutoBandwidthDeadline time.Time `json:"b,omitzero"`
NextAckTick time.Time `json:"a,omitzero"`
NextCertCheck time.Time `json:"x,omitzero"`
AckPending uint64 `json:"p,omitempty"`
AckSent uint64 `json:"s,omitempty"`
LastAck time.Time `json:"k,omitzero"`
LastReject time.Time `json:"r,omitzero"`
LastEndUnix int64 `json:"e,omitempty"`
LastSeenAt time.Time `json:"v_at,omitzero"`
SentRevision uint64 `json:"q,omitempty"`
SentStateHash string `json:"sh,omitempty"`
SentWithheld []string `json:"wh,omitempty"`
SentSettingsHash string `json:"ss,omitempty"`
DriftResent bool `json:"dr,omitempty"`
Drift bool `json:"dt,omitempty"`
FullResendPending bool `json:"fr,omitempty"`
HelloAppliedRevision uint64 `json:"har,omitempty"`
HelloAppliedStateHash string `json:"hah,omitempty"`
Preparing bool `json:"prep,omitempty"`
PrepareDirty bool `json:"pd,omitempty"`
PrepareRetryAt time.Time `json:"pra,omitzero"`
Poison *PoisonBatch `json:"p_seq,omitempty"`
PeerCertSerial string `json:"cs,omitempty"`
PeerCertNotAfter time.Time `json:"ce,omitzero"`
Pending map[string]PendingRequest `json:"pr,omitempty"`
L3 l3MemoState `json:"m,omitzero"`
Disconnected bool `json:"z,omitempty"`
}
SessionState is the compact connection protocol state. The live admin view is stored in node_live.
type Transition ¶ added in v0.1.26
type Transition struct {
Frames []*agentv1.ConnectResponse
Effects []SessionEffect
NextAlarm *time.Time
Close *SessionClose
}
Transition contains the outputs produced by one session event.
type Updates ¶
type Updates interface {
// Updating reports that a rollout step of the node is in flight (command sent, reconnect or gate pending): its
// stream drops when the agent re-executes, and that is neither a blip nor an outage.
Updating(nodeID string) bool
// Serve streams the named file of the current trusted bundle from offset: send gets at most 256 KiB at a time
// and the size of the whole file. Errors are Connect errors (NOT_FOUND, RESOURCE_EXHAUSTED, FAILED_PRECONDITION).
Serve(ctx context.Context, nodeID, name string, offset uint64, send func(chunk []byte, total uint64) error) error
// NodeBinary is the absolute path, on the panel's server, of the agent binary for the platform in the current
// trusted bundle; "" when there is none. The add-node window offers it as a ready scp command.
NodeBinary(goos, goarch string) string
}
Updates is implemented by the updates module. Both methods must be cheap; Serve blocks for the length of a download.
type Warp ¶
type Warp interface {
// Spec is the node's WarpSpec (nil = the node has no account; Enabled=false = paused). It is sent only to a stream
// that listed "warp/1".
Spec(ctx context.Context, nodeID string) (*plugin.WarpSpec, error)
// StoreHealth keeps the last WarpHealth of a node (for GetWarp and the node badge).
StoreHealth(ctx context.Context, nodeID string, h *agentv1.WarpHealth) error
// NeedsAttention records why the owner has to decide ("" clears it).
NeedsAttention(ctx context.Context, nodeID, reason string) error
// RefreshByNode reads the account back from Cloudflare because the node's WARP could not heal itself (read only).
RefreshByNode(ctx context.Context, nodeID string) error
// AutoReregister replaces a revoked registered account when the owner switched that on; reports whether it did.
AutoReregister(ctx context.Context, nodeID string) (bool, error)
// Summary is the badge of a node card; a is nil when the node has no account.
Summary(a *store.WarpAccountRow, online bool, now time.Time) *adminv1.WarpSummary
}
Warp is implemented by the WARP module (internal/panel/warp). The fleet asks it for the node's WarpSpec and hands it what the node reports; it never touches an account itself. Every method must be cheap or return quickly: Spec runs for every reconcile of a node, StoreHealth for every stats batch.