Documentation
¶
Overview ¶
Package bridge provides bridge mode functionality including user access integration.
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func HandleBridgeConfigUpdated(trigger ReconcileTrigger) api.EventHandler
- func IngressReconcileHandler(mgr *IngressManager, logger *slog.Logger) reconcile.ReconcileHandler
- func IngressSecretInventoryHandler(mgr *IngressManager) reconcile.DispatchHandler
- func RelayReconcileHandler(relay *Relay, status *RelayStatusTracker, logger *slog.Logger) reconcile.ReconcileHandler
- func SiteToSiteReconcileHandler(mgr *SiteToSiteManager, logger *slog.Logger) reconcile.ReconcileHandler
- func UserAccessReconcileHandler(mgr *UserAccessManager, logger *slog.Logger) reconcile.ReconcileHandler
- func ValidACMEDirectoryURL(s string) bool
- func ValidateTunnelConfig(cfg TunnelConfig) error
- func ValidateTunnelID(id string) error
- type ACMEConfig
- type ACMEManager
- func (m *ACMEManager) Active() bool
- func (m *ACMEManager) Configure(settings *api.IngressACME, hosts []string)
- func (m *ACMEManager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
- func (m *ACMEManager) HasHost(serverName string) bool
- func (m *ACMEManager) Issued(host string) bool
- func (m *ACMEManager) OnIssuedChange(fn func())
- func (m *ACMEManager) Teardown() error
- type AccessController
- type CertificateSecretFetcher
- type CommandExecutor
- type CommandHandle
- type Config
- type IPsecProvider
- func (p *IPsecProvider) ActiveTunnels() []string
- func (p *IPsecProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
- func (p *IPsecProvider) Name() string
- func (p *IPsecProvider) RemoveTunnel(tunnelID string) error
- func (p *IPsecProvider) Stop() error
- func (p *IPsecProvider) TunnelStatus(tunnelID string) TunnelStatus
- type IngressController
- type IngressDialPolicy
- type IngressManager
- func (m *IngressManager) Apply(ctx context.Context, block api.IngressConfig) error
- func (m *IngressManager) IngressCapabilities() map[string]string
- func (m *IngressManager) IngressStatus() *api.IngressInfo
- func (m *IngressManager) ReportChanged() <-chan struct{}
- func (m *IngressManager) RuleReports() []IngressRuleReport
- func (m *IngressManager) RuleStates() []IngressRuleState
- func (m *IngressManager) SetDialPolicy(p IngressDialPolicy)
- func (m *IngressManager) Setup() error
- func (m *IngressManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
- func (m *IngressManager) Teardown() error
- type IngressRuleReport
- type IngressRuleReportSource
- type IngressRuleState
- type IngressStatusClient
- type IngressStatusReporter
- type Manager
- func (m *Manager) BridgeCapabilities() map[string]string
- func (m *Manager) BridgeStatus() *api.BridgeInfo
- func (m *Manager) Relay() *Relay
- func (m *Manager) RelayStatusTracker() *RelayStatusTracker
- func (m *Manager) Setup(meshIface string) error
- func (m *Manager) Teardown() error
- func (m *Manager) UpdateRoutes(subnets []string) error
- type NATController
- type NetbirdProvider
- type NetlinkAccessController
- func (c *NetlinkAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
- func (c *NetlinkAccessController) CreateInterface(name string, listenPort int) error
- func (c *NetlinkAccessController) RemoveInterface(name string) error
- func (c *NetlinkAccessController) RemovePeer(iface, publicKey string) error
- type NetlinkRouteController
- func (c *NetlinkRouteController) AddNATMasquerade(iface string) error
- func (c *NetlinkRouteController) AddRoute(subnet, iface string) error
- func (c *NetlinkRouteController) DisableForwarding(meshIface, accessIface string) error
- func (c *NetlinkRouteController) EnableForwarding(meshIface, accessIface string) error
- func (c *NetlinkRouteController) RemoveNATMasquerade(iface string) error
- func (c *NetlinkRouteController) RemoveRoute(subnet, iface string) error
- type NetlinkVPNController
- func (c *NetlinkVPNController) ConfigureTunnelPeer(iface, publicKey string, allowedIPs []string, endpoint, psk string) error
- func (c *NetlinkVPNController) CreateTunnelInterface(name string, listenPort int) error
- func (c *NetlinkVPNController) RemoveTunnelInterface(name string) error
- func (c *NetlinkVPNController) RemoveTunnelPeer(iface, publicKey string) error
- type OpenVPNProvider
- func (p *OpenVPNProvider) ActiveTunnels() []string
- func (p *OpenVPNProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
- func (p *OpenVPNProvider) Name() string
- func (p *OpenVPNProvider) RemoveTunnel(tunnelID string) error
- func (p *OpenVPNProvider) Stop() error
- func (p *OpenVPNProvider) TunnelStatus(tunnelID string) TunnelStatus
- type ProviderStatus
- type ReconcileTrigger
- type Relay
- type RelayStatus
- type RelayStatusClient
- type RelayStatusReporter
- type RelayStatusTracker
- type RouteController
- type SiteToSiteManager
- func (m *SiteToSiteManager) AddTunnel(tunnel api.SiteToSiteTunnel) error
- func (m *SiteToSiteManager) GetTunnel(tunnelID string) (api.SiteToSiteTunnel, bool)
- func (m *SiteToSiteManager) RemoveTunnel(tunnelID string)
- func (m *SiteToSiteManager) Setup(meshIface string) error
- func (m *SiteToSiteManager) SiteToSiteCapabilities() map[string]string
- func (m *SiteToSiteManager) SiteToSiteStatus() *api.SiteToSiteInfo
- func (m *SiteToSiteManager) Teardown() error
- func (m *SiteToSiteManager) TunnelIDs() []string
- type StdCommandExecutor
- type StdIngressController
- type TailscaleProvider
- type TunnelConfig
- type TunnelProvider
- type TunnelStatus
- type UserAccessManager
- func (m *UserAccessManager) AddPeer(peer api.UserAccessPeer) error
- func (m *UserAccessManager) PeerPublicKeys() []string
- func (m *UserAccessManager) RemovePeer(publicKey string)
- func (m *UserAccessManager) Setup() error
- func (m *UserAccessManager) Teardown() error
- func (m *UserAccessManager) UserAccessCapabilities() map[string]string
- func (m *UserAccessManager) UserAccessStatus() *api.UserAccessInfo
- type UserAccessProvider
- type VPNController
- type WGAccessController
- func (c *WGAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
- func (c *WGAccessController) CreateInterface(name string, listenPort int) error
- func (c *WGAccessController) RemoveInterface(name string) error
- func (c *WGAccessController) RemovePeer(iface, publicKey string) error
- type WGVPNController
- func (c *WGVPNController) ConfigureTunnelPeer(iface, publicKey string, allowedIPs []string, endpoint, psk string) error
- func (c *WGVPNController) CreateTunnelInterface(name string, listenPort int) error
- func (c *WGVPNController) OSInterfaceName(name string) (string, bool)
- func (c *WGVPNController) RemoveTunnelInterface(name string) error
- func (c *WGVPNController) RemoveTunnelPeer(iface, publicKey string) error
Constants ¶
const ( DefaultUserAccessInterfaceName = "wg-access" DefaultUserAccessListenPort = 51822 DefaultMaxAccessPeers = 50 DefaultMaxIngressRules = 20 DefaultIngressDialTimeout = 10 * time.Second DefaultSiteToSiteInterfacePrefix = "wg-s2s-" DefaultSiteToSiteListenPort = 51823 DefaultMaxSiteToSiteTunnels = 10 )
const ( // IngressDialReasonPolicyDenied: the node's compiled policy blocks the // dial, as the dial policy answers after the dial failed. IngressDialReasonPolicyDenied = "policy_denied" // IngressDialReasonTimeout: the dial did not complete within // bridge.ingress_dial_timeout. IngressDialReasonTimeout = "timeout" // IngressDialReasonRefused: the target's host answered that nothing // listens on the port. IngressDialReasonRefused = "refused" // IngressDialReasonUnreachable: no route reaches the target's host or // network. IngressDialReasonUnreachable = "unreachable" // IngressDialReasonOther: any other failure. IngressDialReasonOther = "other" )
The reasons of a failed dial in an ingress status report, in the order they are checked: the first that applies names the dial.
const ( // IngressReasonInvalid: a field of the rule is missing or malformed; the // state's Detail names the field. IngressReasonInvalid = "invalid_rule" // IngressReasonDuplicateID: an earlier rule of the block has the same id. IngressReasonDuplicateID = "duplicate_id" // IngressReasonListenerConflict: a held rule has the same listen port and // host, or one of the two has no host; Detail is the holder's slug. IngressReasonListenerConflict = "listener_conflict" // IngressReasonMaxRules: bridge.max_ingress_rules rules are held already. IngressReasonMaxRules = "max_rules" // IngressReasonListenFailed: the listener for the rule's port could not // be opened; every later Apply tries again. IngressReasonListenFailed = "listen_failed" // IngressReasonACMEDirectoryInvalid: the block's acme member is missing, // or its directory_url is not an absolute https URL; Detail is the URL. IngressReasonACMEDirectoryInvalid = "acme_directory_invalid" // IngressReasonACMEDirectoryNotAllowed: bridge.acme_directory_urls does // not list the block's directory_url; Detail is the URL. IngressReasonACMEDirectoryNotAllowed = "acme_directory_not_allowed" // IngressReasonACMEChallengePortTaken: a rule of another mode on port 443 // would take the CA's challenge connection for the acme rule's host; // Detail is that rule's slug. IngressReasonACMEChallengePortTaken = "acme_challenge_port_taken" // IngressReasonACMENotIssued: a served acme rule whose host's last // certificate request did not succeed, or was not made yet. Only the // ingress status report carries it; the rule is served, and the next // client handshake asks autocert again. IngressReasonACMENotIssued = "acme_not_issued" // IngressReasonCertificateSecretNotListed: the secret inventory does not // list the Secret a terminate rule names; Detail is the Secret name. IngressReasonCertificateSecretNotListed = "certificate_secret_not_listed" // IngressReasonCertificateFetchFailed: the listed version of a terminate // rule's Secret could not be fetched yet; Detail is the Secret name. IngressReasonCertificateFetchFailed = "certificate_fetch_failed" // IngressReasonCertificateInvalid: the listed version of a terminate // rule's Secret holds no certificate chain with a matching key; Detail is // the Secret name. IngressReasonCertificateInvalid = "certificate_invalid" )
The reasons a rule of the bridge.ingress block is not served.
const DefaultTunnelConfigDir = "/run/plexd/tunnels"
DefaultTunnelConfigDir is the default directory used for tunnel config files. It is isolated from /tmp to prevent other users from reading PSK material.
Variables ¶
ErrNATUnavailable is returned by AddNATMasquerade on a platform whose route controller was built without a NAT backend. Bridge mode still runs without NAT when bridge.enable_nat is false.
Functions ¶
func HandleBridgeConfigUpdated ¶
func HandleBridgeConfigUpdated(trigger ReconcileTrigger) api.EventHandler
HandleBridgeConfigUpdated returns an api.EventHandler that triggers reconciliation when a bridge_config_updated SSE event is received. Follows the HandlePolicyUpdated pattern: payload is ignored, reconcile cycle will fetch the full desired state.
func IngressReconcileHandler ¶
func IngressReconcileHandler(mgr *IngressManager, logger *slog.Logger) reconcile.ReconcileHandler
IngressReconcileHandler returns a reconcile.ReconcileHandler that serves the desired bridge.ingress block whole, its acme member included, when the block enables public ingress. mgr is nil when the node opts out of public ingress, bridge.ingress_enabled: false. A nil snapshot changes nothing.
With a manager, a block with Enabled true is applied. A nil Bridge or nil Ingress child applies the zero block, which closes every listener, and so does a block with Enabled false, which is also what a block without the member decodes to. A block with Enabled false that carries rules is logged as a Warn naming how many before the zero block is applied. A failed bind fails the reconcile cycle, so the reconciler keeps its snapshot and the next pull tries the bind again.
Without a manager the handler touches nothing and returns nil. A block with Enabled true and at least one rule is logged as a Warn naming how many rules the local opt-out leaves unserved.
Both Warn lines are logged only when diff.BridgeChanged is set: the reconciler invokes every handler on any drift, peers and policy included, and an ungated Warn would repeat on each such cycle. Each is logged once per change of the pulled bridge block, which includes the first pull after every start, since the reconciler's snapshot starts empty. A cycle that fails keeps the old snapshot, so the next pull logs it again. Applying the zero block is not gated.
func IngressSecretInventoryHandler ¶ added in v0.35.0
func IngressSecretInventoryHandler(mgr *IngressManager) reconcile.DispatchHandler
IngressSecretInventoryHandler returns a reconcile.DispatchHandler that hands the secret inventory of every successful pull to the ingress manager, which loads, replaces or drops the certificates of its terminate rules. A pull whose only change is the secrets block reports no drift, so no reconcile handler would see a rotation. A nil Secrets block, a control plane that did not say this time, keeps the inventory the manager holds. Dispatch handlers run before the reconcile handlers, so a cycle that brings a new rule and its Secret hands the inventory over first.
func RelayReconcileHandler ¶
func RelayReconcileHandler(relay *Relay, status *RelayStatusTracker, logger *slog.Logger) reconcile.ReconcileHandler
RelayReconcileHandler returns a reconcile.ReconcileHandler that runs the relay the desired bridge.relay block asks for and records on status the state each snapshot leaves the relay in, for the RelayStatusReporter to send. relay is nil when local consent, bridge.relay_enabled, is off. status must not be nil.
A nil Bridge or Relay child, or Enabled false, stops a running relay and records stopped, also when relay is nil or not running, so a relay whose last bind failed reads stopped once the pull disables it. With Enabled true the relay is configured on ListenPort with the snapshot's peers, so a bind failure fails the reconcile cycle and the next pull retries it. The status then comes from Relay.Bound: running on the bound port while the relay runs, bind_failed on ListenPort when Configure failed on a valid port, and stopped otherwise. With Enabled true and no relay, the handler only warns and records not_consented. A nil snapshot records nothing.
func SiteToSiteReconcileHandler ¶
func SiteToSiteReconcileHandler(mgr *SiteToSiteManager, logger *slog.Logger) reconcile.ReconcileHandler
SiteToSiteReconcileHandler returns a reconcile.ReconcileHandler that updates site-to-site tunnels when the desired bridge site-to-site subtree changes. It diffs the desired tunnels against the currently active tunnels: adding missing tunnels, removing stale tunnels, and restarting changed tunnels (same ID, different config). The handler is presence-aware: a nil Bridge or nil SiteToSite child means "not populated", so it reconciles against an empty desired set and tears down stale tunnels.
func UserAccessReconcileHandler ¶
func UserAccessReconcileHandler(mgr *UserAccessManager, logger *slog.Logger) reconcile.ReconcileHandler
UserAccessReconcileHandler returns a reconcile.ReconcileHandler that updates user access peers when the desired bridge user-access subtree changes. It diffs the desired peers against the currently active peers, adding missing and removing stale peers. The handler is presence-aware: a nil Bridge or nil UserAccess child means "not populated", so it reconciles against an empty desired set and tears down stale peers.
func ValidACMEDirectoryURL ¶ added in v0.35.0
ValidACMEDirectoryURL reports whether s is an absolute https URL with a host and without user information, a directory the bridge can register at.
func ValidateTunnelConfig ¶
func ValidateTunnelConfig(cfg TunnelConfig) error
ValidateTunnelConfig validates all fields of a TunnelConfig before they are interpolated into config files. This prevents newline injection and config injection in strongSwan/OpenVPN configurations.
func ValidateTunnelID ¶
ValidateTunnelID checks that a tunnel ID is safe for use in file paths and shell arguments. Returns an error if the ID is invalid.
Types ¶
type ACMEConfig ¶
type ACMEConfig struct {
// CacheDir holds the account key and the certificates, as autocert.DirCache
// lays them out. Empty keeps them in memory only.
CacheDir string
// HTTPTransport carries the ACME requests; nil means http.DefaultTransport.
HTTPTransport http.RoundTripper
}
ACMEConfig holds the local settings of the ACME account the bridge's acme rules share. The directory and the contact come from the state pull.
type ACMEManager ¶
type ACMEManager struct {
// contains filtered or unexported fields
}
ACMEManager obtains and renews the certificates of the bridge's acme rules through one autocert.Manager at a time.
autocert cannot change its directory or stop a renewal, so Configure builds a new autocert.Manager when the account settings change or a host leaves, and retires the one it replaces: every request of the retired manager fails at its gate transport with errACMERetired, so its renewal timers, which stay armed, never reach the network. The certificates and the account key stay in CacheDir across a replacement, so a cached certificate keeps serving until its renewal.
ACMEManager is concurrent-safe via mu. It never holds mu while it calls autocert.
func NewACMEManager ¶
func NewACMEManager(cfg ACMEConfig, logger *slog.Logger) *ACMEManager
NewACMEManager creates an ACMEManager without an account.
func (*ACMEManager) Active ¶
func (m *ACMEManager) Active() bool
Active reports whether an account is configured.
func (*ACMEManager) Configure ¶ added in v0.35.0
func (m *ACMEManager) Configure(settings *api.IngressACME, hosts []string)
Configure sets the account and the hosts certificates may be requested for. nil settings or no hosts retire the account.
It builds an autocert.Manager when none is active, when DirectoryURL or ContactEmail differ from the active one's, or when a host of the active one left the set; a host that only joins keeps the manager. For each host new to the active manager, a goroutine obtains the certificate ahead of the first client.
func (*ACMEManager) GetCertificate ¶
func (m *ACMEManager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
GetCertificate returns the certificate of the active account for hello: the host's certificate, or for a TLS-ALPN-01 challenge hello the challenge certificate. It fits tls.Config.GetCertificate.
func (*ACMEManager) HasHost ¶ added in v0.35.0
func (m *ACMEManager) HasHost(serverName string) bool
HasHost reports whether serverName, in any case, is the sni_host of a served acme rule while an account is configured.
func (*ACMEManager) Issued ¶ added in v0.35.0
func (m *ACMEManager) Issued(host string) bool
Issued reports whether an account is configured and the last certificate request for host, in any case, succeeded: the obtain ahead of the first client or a client handshake, not a TLS-ALPN-01 challenge. A new account starts with no host issued.
func (*ACMEManager) OnIssuedChange ¶ added in v0.35.0
func (m *ACMEManager) OnIssuedChange(fn func())
OnIssuedChange registers fn, which is called whenever a request changes whether a host of the active account is issued. fn runs on the goroutine that made the request, outside the manager's lock, and must not block.
func (*ACMEManager) Teardown ¶
func (m *ACMEManager) Teardown() error
Teardown retires the active account and waits at most acmeTeardownWait for the goroutines that obtain a certificate ahead of the first client. The retired gate fails their next request and acmeRetryBackoff keeps every wait between two requests within acmeMaxRetryWait, so they normally end within the bound. When they do not, Teardown logs a warning and returns; they end on their own later. It is idempotent and returns nil.
type AccessController ¶
type AccessController interface {
// CreateInterface creates a WireGuard interface with the given name and listen port.
// Not idempotent: a name that already exists fails with an error wrapping
// os.ErrExist, which is what EEXIST is on Linux.
CreateInterface(name string, listenPort int) error
// RemoveInterface removes the WireGuard interface with the given name.
// Idempotent: removing a non-existent interface returns nil.
RemoveInterface(name string) error
// ConfigurePeer adds or updates a peer on the given WireGuard interface.
// Idempotent: re-applying the same peer config returns nil.
ConfigurePeer(iface string, publicKey string, allowedIPs []string, psk string) error
// RemovePeer removes a peer from the given WireGuard interface by public key.
// Idempotent: removing a non-existent peer returns nil.
RemovePeer(iface string, publicKey string) error
}
AccessController abstracts WireGuard interface operations for user access testability. Every method except CreateInterface must be idempotent: repeating an operation that is already applied returns nil.
type CertificateSecretFetcher ¶ added in v0.35.0
type CertificateSecretFetcher interface {
FetchCertificateSecret(ctx context.Context, name string, version int) ([]byte, error)
}
CertificateSecretFetcher reads the value of one version of a Secret the node may read: the PEM document of a terminate rule's certificate.
type CommandExecutor ¶
type CommandExecutor interface {
// Run executes a command and returns its combined output.
Run(ctx context.Context, name string, args ...string) ([]byte, error)
// Start starts a command without waiting for it to complete.
// Returns a CommandHandle that can be used to stop the process.
Start(ctx context.Context, name string, args ...string) (CommandHandle, error)
}
CommandExecutor abstracts command execution for testability.
type CommandHandle ¶
type CommandHandle interface {
// Stop terminates the process.
Stop() error
}
CommandHandle represents a running process.
type Config ¶
type Config struct {
// Enabled controls whether bridge mode is active.
// Default: false
Enabled bool `yaml:"enabled"`
// AccessInterface is the name of the access-side network interface.
AccessInterface string `yaml:"access_interface"`
// AccessSubnets are the CIDR subnets reachable via the access-side interface.
AccessSubnets []string `yaml:"access_subnets"`
// EnableNAT controls whether NAT masquerading is applied on the access-side interface.
// nil means use default (true); explicit false disables NAT.
EnableNAT *bool `yaml:"enable_nat"`
// RelayEnabled is the local consent to serve as a relay: the relay runs
// only while this is true and the state pull's bridge.relay block is
// enabled, on the port that block names.
// Default: false. Requires Enabled=true.
RelayEnabled bool `yaml:"relay_enabled"`
// UserAccessEnabled controls whether user access integration is active.
// Default: false. Requires Enabled=true.
UserAccessEnabled bool `yaml:"user_access_enabled"`
// UserAccessInterfaceName is the name of the WireGuard interface for user access.
// Default: "wg-access"
UserAccessInterfaceName string `yaml:"user_access_interface_name"`
// UserAccessListenPort is the UDP port for the user access WireGuard interface.
// Default: 51822
UserAccessListenPort int `yaml:"user_access_listen_port"`
// MaxAccessPeers is the maximum number of concurrent user access peers.
// Default: 50
MaxAccessPeers int `yaml:"max_access_peers"`
// UserAccessProviderType selects the external VPN provider for user access.
// Supported values: "tailscale", "netbird", or "" (disabled).
UserAccessProviderType string `yaml:"user_access_provider_type"`
// AuthKeyEnv is the environment variable name containing the auth key
// for the user access provider (e.g. "PLEXD_TAILSCALE_AUTH_KEY").
AuthKeyEnv string `yaml:"auth_key_env"`
// SetupKeyEnv is the environment variable name containing the setup key
// for the user access provider (e.g. "PLEXD_NETBIRD_SETUP_KEY").
SetupKeyEnv string `yaml:"setup_key_env"`
// IngressEnabled is the local switch for public ingress. nil and true serve
// the rules the state pull's bridge.ingress block enables; false opts the
// node out: plexd builds no ingress manager, opens no public listener
// whatever the pull says, and reports opted_out to the control plane.
// Default: nil, which serves. An explicit true requires Enabled=true.
IngressEnabled *bool `yaml:"ingress_enabled"`
// MaxIngressRules is the maximum number of concurrent ingress rules.
// Default: 20
MaxIngressRules int `yaml:"max_ingress_rules"`
// IngressDialTimeout is the timeout for dialing target mesh peers.
// Default: 10s. Minimum: 1s.
IngressDialTimeout time.Duration `yaml:"ingress_dial_timeout"`
// SiteToSiteEnabled controls whether site-to-site VPN connectivity is active.
// Default: false. Requires Enabled=true.
SiteToSiteEnabled bool `yaml:"site_to_site_enabled"`
// SiteToSiteInterfacePrefix is the prefix for WireGuard interfaces used by site-to-site tunnels.
// Each tunnel gets an interface named {prefix}{index}.
// Default: "wg-s2s-"
SiteToSiteInterfacePrefix string `yaml:"site_to_site_interface_prefix"`
// SiteToSiteListenPort is the base UDP port for site-to-site WireGuard interfaces.
// Each tunnel uses this port + tunnel index offset.
// Default: 51823
SiteToSiteListenPort int `yaml:"site_to_site_listen_port"`
// MaxSiteToSiteTunnels is the maximum number of concurrent site-to-site tunnels.
// Default: 10
MaxSiteToSiteTunnels int `yaml:"max_site_to_site_tunnels"`
// TunnelProviders lists the tunnel provider types to enable for site-to-site connectivity.
// Supported values: "ipsec", "openvpn". Empty means WireGuard-only.
TunnelProviders []string `yaml:"tunnel_providers"`
// ACMECacheDir is the directory that holds the ACME account key and the
// certificates of the acme rules. Empty means <data_dir>/acme.
ACMECacheDir string `yaml:"acme_cache_dir"`
// ACMEDirectoryURLs bounds the ACME directories the bridge accepts from the
// state pull's bridge.ingress.acme member. Empty accepts any https directory.
ACMEDirectoryURLs []string `yaml:"acme_directory_urls"`
}
Config holds the configuration for bridge mode. Config is passed as a constructor argument — no file I/O in this package.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for zero-valued fields.
func (*Config) IngressOptedOut ¶ added in v0.35.0
IngressOptedOut reports whether the node opts out of public ingress: true exactly when IngressEnabled is set to false. An unset IngressEnabled serves.
type IPsecProvider ¶
type IPsecProvider struct {
// contains filtered or unexported fields
}
IPsecProvider wraps strongSwan (swanctl) to manage IPsec tunnels for site-to-site connectivity. All methods are safe for concurrent use.
func NewIPsecProvider ¶
func NewIPsecProvider(exec CommandExecutor, routes RouteController, logger *slog.Logger) *IPsecProvider
NewIPsecProvider creates a new IPsecProvider.
func (*IPsecProvider) ActiveTunnels ¶
func (p *IPsecProvider) ActiveTunnels() []string
ActiveTunnels returns the IDs of all active tunnels.
func (*IPsecProvider) CreateTunnel ¶
func (p *IPsecProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
CreateTunnel establishes an IPsec tunnel via swanctl.
func (*IPsecProvider) Name ¶
func (p *IPsecProvider) Name() string
Name returns the provider identifier.
func (*IPsecProvider) RemoveTunnel ¶
func (p *IPsecProvider) RemoveTunnel(tunnelID string) error
RemoveTunnel tears down an IPsec tunnel. Idempotent.
func (*IPsecProvider) Stop ¶
func (p *IPsecProvider) Stop() error
Stop gracefully shuts down all managed IPsec tunnels. Idempotent.
func (*IPsecProvider) TunnelStatus ¶
func (p *IPsecProvider) TunnelStatus(tunnelID string) TunnelStatus
TunnelStatus returns the status of the given tunnel.
type IngressController ¶
type IngressController interface {
// Listen creates a TCP listener on the given address.
// If tlsCfg is non-nil, the listener will accept TLS connections.
// Returns the listener and any error.
Listen(addr string, tlsCfg *tls.Config) (net.Listener, error)
// Close closes the given listener.
// Idempotent: closing an already-closed listener returns nil.
Close(listener net.Listener) error
}
IngressController abstracts TCP listener operations for ingress testability. All methods must be idempotent where applicable.
type IngressDialPolicy ¶ added in v0.35.0
IngressDialPolicy tells whether the node's compiled policy blocks a TCP dial to target.
type IngressManager ¶
type IngressManager struct {
// contains filtered or unexported fields
}
IngressManager serves public ingress: one TCP listener per listen port of the bridge.ingress block, routing each connection to the target of its rule. A passthrough rule's connection is forwarded unread; a terminate or acme rule's connection ends TLS at the bridge, and the plaintext goes to the target. IngressManager is concurrent-safe via mu.
func NewIngressManager ¶
func NewIngressManager(ctrl IngressController, cfg Config, logger *slog.Logger, acme *ACMEManager, certs CertificateSecretFetcher) *IngressManager
NewIngressManager creates a new IngressManager. acme holds the account of the block's acme rules and certs fetches the certificates of its terminate rules; neither may be nil. The manager registers with acme to signal ReportChanged when a host's certificate is issued or lost.
func (*IngressManager) Apply ¶ added in v0.34.0
func (m *IngressManager) Apply(ctx context.Context, block api.IngressConfig) error
Apply makes the manager serve exactly the rules of block.
It checks the block's acme member against bridge.acme_directory_urls, plans the block, and forgets the certificates of Secrets no held rule names any more. It then opens a listener for each port in the plan that has none, swaps the routing table of every other port in place, and closes the listeners of ports the plan no longer names. A route whose rule is unchanged keeps its context and its connections; every other route of the last Apply is cancelled, which closes its connections. A failed bind marks the port's rules listen_failed and is retried by the next Apply; the other ports are served. After the binds it configures the ACME account with the hosts of the acme rules that have no reason, which retires it when there are none, so an acme rule whose port failed to bind asks the CA for nothing. Last, it loads the certificates of the held terminate rules. The result joins the bind errors and is nil when there are none.
func (*IngressManager) IngressCapabilities ¶
func (m *IngressManager) IngressCapabilities() map[string]string
IngressCapabilities returns capability metadata for registration. Returns nil when the node opts out of public ingress.
func (*IngressManager) IngressStatus ¶
func (m *IngressManager) IngressStatus() *api.IngressInfo
IngressStatus returns ingress status for heartbeat reporting. Returns nil when ingress is not active.
func (*IngressManager) ReportChanged ¶ added in v0.35.0
func (m *IngressManager) ReportChanged() <-chan struct{}
ReportChanged returns the channel the manager signals, without blocking, when what RuleReports returns may have changed: at the end of every Apply, every certificate load and Teardown, when the ACME manager reports a change of its issued hosts, and when a dial record changes its outcome or reason. Several signals before the reader wakes collapse into one. The signals are liberal; the reader compares before it acts.
func (*IngressManager) RuleReports ¶ added in v0.35.0
func (m *IngressManager) RuleReports() []IngressRuleReport
RuleReports returns one report per rule of the last Apply, in block order, and nil while the manager is not active. It skips a rule whose id is no UUID in canonical form or the zero UUID, and a rule whose id an earlier rule carried, compared without case, since the control plane refuses a whole report for one such entry; the Warn "ingress rule not served" names both.
A rule that is not held does not listen, for its reason: invalid_rule, listener_conflict or max_rules. A held rule listens when its port is bound, and otherwise reads listen_failed. For a rule that listens, the certificate is not_required for passthrough; ready or not_ready with the overlay's reason for terminate; and for acme, not_ready with the plan's reason when it has one, ready once the ACME manager reports the host issued, and acme_not_issued until then. The dial is the last one a client connection caused to the rule's current target, and none without one.
func (*IngressManager) RuleStates ¶ added in v0.34.0
func (m *IngressManager) RuleStates() []IngressRuleState
RuleStates returns the outcome of the last Apply, one entry per rule. A held terminate rule reads Served exactly when its Secret's certificate is loaded.
func (*IngressManager) SetDialPolicy ¶ added in v0.35.0
func (m *IngressManager) SetDialPolicy(p IngressDialPolicy)
SetDialPolicy sets the policy that names a failed dial policy_denied. It is called before Setup and never afterwards; without one, no dial reads policy_denied.
The policy only names the reason of a dial that already failed: the bridge dials every target as before, and the kernel stays the only place that enforces.
func (*IngressManager) Setup ¶
func (m *IngressManager) Setup() error
Setup initializes the ingress manager. It is a no-op when the node opts out of public ingress.
func (*IngressManager) SyncSecretInventory ¶ added in v0.35.0
func (m *IngressManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
SyncSecretInventory takes the secret inventory of a pull and loads, replaces or drops the certificates of the held terminate rules. It does nothing while the manager is not active.
func (*IngressManager) Teardown ¶
func (m *IngressManager) Teardown() error
Teardown cancels every route, which closes every connection, closes every listener, and forgets the secret inventory and every certificate. Errors are aggregated; cleanup continues past a failed close. Idempotent: calling Teardown when inactive returns nil.
type IngressRuleReport ¶ added in v0.35.0
type IngressRuleReport struct {
RuleID string
Listener string // api.IngressListener*
ListenerReason string
Certificate string // api.IngressCertificate*; empty when the rule does not listen
CertificateReason string
Dial string // api.IngressDial*; empty when the rule does not listen
DialReason string
DialAt time.Time // zero unless Dial is succeeded or failed
}
IngressRuleReport is what the bridge says about one rule in an ingress status report. It carries no Detail: a Secret name, a directory URL, a slug and an error text stay in the bridge's log.
type IngressRuleReportSource ¶ added in v0.35.0
type IngressRuleReportSource interface {
RuleReports() []IngressRuleReport
ReportChanged() <-chan struct{}
}
IngressRuleReportSource is the part of *IngressManager the reporter reads.
type IngressRuleState ¶ added in v0.34.0
type IngressRuleState struct {
Rule api.IngressRule
Served bool
Reason string // empty when served
Detail string // the field of an invalid rule, the slug of the rule that holds the listener, a directory URL or a Secret name
// contains filtered or unexported fields
}
IngressRuleState is the outcome of one rule of the last Apply.
type IngressStatusClient ¶ added in v0.35.0
type IngressStatusClient interface {
ReportIngressStatus(ctx context.Context, nodeID string, req api.IngressStatusRequest) (*api.IngressStatusResponse, error)
}
IngressStatusClient sends ingress status reports. *api.ControlPlane satisfies it.
type IngressStatusReporter ¶ added in v0.35.0
type IngressStatusReporter struct {
// contains filtered or unexported fields
}
IngressStatusReporter sends to PUT /v1/nodes/{node_id}/ingress-status whether the bridge's local configuration serves public ingress, enabled or opted_out when bridge.ingress_enabled is false, and on an enabled bridge one entry per ingress rule as the ingress manager reports it: its listener, its certificate and the last dial to its target. It sends once when it starts, again when the entries change, and once per interval. The control plane keeps the latest state per node and refuses ingress rule creates and updates on a bridge whose report reads opted_out; each report replaces the rule entries of the one before.
DECISION: the reporter sends at once when it starts, without waiting for a pull. The state comes from the local configuration and is known before the first pull, unlike the relay's, which only the relay handler knows. plexd reads its configuration once per start, so the send after each start covers every change of the setting. That send carries no entries, because no pull is applied yet; the first Apply signals a change, and the entries follow at once.
DECISION: a change sends only when its entries differ from those of the last accepted report, the dial age ignored, and at most once per ingressStatusChangeGap; a change inside the gap is sent when the gap ends, with the entries as they are then. Dial outcomes follow public connections, so without the bound a target that alternates between failing and answering would cost one request per flip. An on-change send restarts the interval, as the relay status reporter's does. A moving dial age alone sends nothing; the tick carries it.
DECISION: a failed send is never retried within its tick. The last accepted report stays what it was, so the next tick, or the next change, sends the state and the entries as they are then, at most one interval later. An opt-out whose first send fails reaches the control plane at most one interval late, and the bridge opens no public listener the whole time.
DECISION: nothing is sent at shutdown. The control plane keeps the state and never ages it, and a stopped bridge keeps the state its configuration gives it, so there is nothing to withdraw; its rule entries read stale once its reports stop.
DECISION: the report never gates serving. A bridge serves as the pull says while the report fails or the control plane does not serve the operation, as the contract, plexsphere/plexsphere docs/reference/api/plexd-agent-contract.md, requires. The reporter only reads the ingress manager; nothing it learns reaches the manager or the reconcile handler.
func NewIngressStatusReporter ¶ added in v0.35.0
func NewIngressStatusReporter(interval time.Duration, nodeID string, client IngressStatusClient, optedOut bool, rules IngressRuleReportSource, logger *slog.Logger) *IngressStatusReporter
NewIngressStatusReporter creates an IngressStatusReporter that reports for nodeID through client the state optedOut gives, opted_out when it is true and enabled otherwise, and on an enabled bridge the rule entries rules reports. rules is nil on an opted-out bridge; a caller passes an untyped nil, since a nil *IngressManager in the interface does not compare equal to nil. A non-positive interval becomes 30 s, the value of agent.DefaultHeartbeatInterval, because the report's cadence is the heartbeat interval.
func (*IngressStatusReporter) Run ¶ added in v0.35.0
func (r *IngressStatusReporter) Run(ctx context.Context) error
Run sends the report at once, on every change of the rule entries, bounded by ingressStatusChangeGap, and on every tick of the interval until ctx is done, and returns nil without a last send. No answer ends the loop: a control plane that does not serve the operation yet is asked again every interval, so an upgrade is picked up without a restart.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages bridge mode routing between the mesh and access-side interfaces. Manager is not concurrent-safe; it relies on serial invocation from the reconcile loop.
func NewManager ¶
func NewManager(ctrl RouteController, cfg Config, logger *slog.Logger) *Manager
NewManager creates a new Manager. Config defaults are applied automatically.
func (*Manager) BridgeCapabilities ¶
BridgeCapabilities returns bridge capability metadata for registration. Returns nil when bridge mode is disabled.
func (*Manager) BridgeStatus ¶
func (m *Manager) BridgeStatus() *api.BridgeInfo
BridgeStatus returns bridge status for heartbeat reporting. Returns nil when bridge mode is not active.
func (*Manager) Relay ¶
Relay returns the relay, or nil when local consent (Config.RelayEnabled) is off. The relay runs only while the state pull enables it; see RelayReconcileHandler.
func (*Manager) RelayStatusTracker ¶ added in v0.23.0
func (m *Manager) RelayStatusTracker() *RelayStatusTracker
RelayStatusTracker returns the tracker RelayReconcileHandler records the relay's state on and the RelayStatusReporter reads. It is never nil, with or without local consent, and Teardown leaves it as it is: the reporter sends its own stopped report when plexd shuts down.
func (*Manager) Setup ¶
Setup configures bridge mode routing: enables forwarding, adds routes, and optionally configures NAT masquerading. When bridge mode is disabled this is a no-op. On partial route failure, previously added routes in this call are rolled back.
func (*Manager) Teardown ¶
Teardown removes all bridge-specific routing rules, NAT masquerading, and disables forwarding. Idempotent: calling Teardown when inactive returns nil. Errors are aggregated via errors.Join; cleanup continues even on failure.
func (*Manager) UpdateRoutes ¶
UpdateRoutes computes the diff between current active routes and the desired subnets, adding new and removing stale routes.
type NATController ¶ added in v0.8.0
type NATController interface {
// AddNATMasquerade configures NAT masquerading for bridge egress.
// Linux and macOS scope the translation to iface. Windows scopes it by
// mesh source prefix through WinNAT, which cannot bind to an interface,
// and ignores iface: mesh-sourced traffic is translated on its way out of
// whichever adapter carries the route.
AddNATMasquerade(iface string) error
// RemoveNATMasquerade removes NAT masquerading from the given interface.
// Idempotent: removing non-existent masquerade returns nil.
RemoveNATMasquerade(iface string) error
}
NATController programs NAT masquerade for bridge egress. NetlinkRouteController implements it itself through nftables. The macOS and Windows route controllers delegate to one handed to their constructor, because on those platforms the firewall backend owns the NAT rules: PFController on macOS and WFPController on Windows. A controller built without one — which is what the tests do — fails AddNATMasquerade with ErrNATUnavailable. All methods must be idempotent: repeating an operation that is already applied returns nil.
type NetbirdProvider ¶
type NetbirdProvider struct {
// contains filtered or unexported fields
}
NetbirdProvider implements UserAccessProvider by wrapping the Netbird CLI. It joins a Netbird network using a setup key, enabling Netbird users to access mesh resources through the bridge node.
func NewNetbirdProvider ¶
func NewNetbirdProvider(exec CommandExecutor, logger *slog.Logger) *NetbirdProvider
NewNetbirdProvider returns a new NetbirdProvider that uses the given CommandExecutor to invoke the netbird CLI.
func (*NetbirdProvider) Name ¶
func (n *NetbirdProvider) Name() string
Name returns the provider identifier.
func (*NetbirdProvider) Start ¶
func (n *NetbirdProvider) Start(ctx context.Context) error
Start launches the Netbird daemon by running `netbird up` with the setup key from the PLEXD_NETBIRD_SETUP_KEY environment variable, then queries `netbird status --json` to discover the assigned IP and interface name.
func (*NetbirdProvider) Status ¶
func (n *NetbirdProvider) Status() ProviderStatus
Status returns the current provider status.
func (*NetbirdProvider) Stop ¶
func (n *NetbirdProvider) Stop() error
Stop gracefully shuts down Netbird by running `netbird down`. Idempotent: calling Stop when not running returns nil.
type NetlinkAccessController ¶
type NetlinkAccessController struct {
// contains filtered or unexported fields
}
NetlinkAccessController implements AccessController using Linux netlink and wgctrl for managing WireGuard user-access interfaces.
func NewNetlinkAccessController ¶
func NewNetlinkAccessController(logger *slog.Logger) *NetlinkAccessController
NewNetlinkAccessController returns a new NetlinkAccessController.
func (*NetlinkAccessController) ConfigurePeer ¶
func (c *NetlinkAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
ConfigurePeer adds or updates a peer on the access interface.
func (*NetlinkAccessController) CreateInterface ¶
func (c *NetlinkAccessController) CreateInterface(name string, listenPort int) error
CreateInterface creates a WireGuard interface for user access.
func (*NetlinkAccessController) RemoveInterface ¶
func (c *NetlinkAccessController) RemoveInterface(name string) error
RemoveInterface deletes the named WireGuard access interface. It is idempotent: removing a non-existent interface returns nil.
func (*NetlinkAccessController) RemovePeer ¶
func (c *NetlinkAccessController) RemovePeer(iface, publicKey string) error
RemovePeer removes a peer from the access interface by public key.
type NetlinkRouteController ¶
type NetlinkRouteController struct {
// contains filtered or unexported fields
}
NetlinkRouteController implements RouteController using Linux netlink for route management, sysctl for IP forwarding, and nftables for NAT masquerade.
func NewNetlinkRouteController ¶
func NewNetlinkRouteController(logger *slog.Logger) *NetlinkRouteController
NewNetlinkRouteController returns a new NetlinkRouteController.
func (*NetlinkRouteController) AddNATMasquerade ¶
func (c *NetlinkRouteController) AddNATMasquerade(iface string) error
AddNATMasquerade configures NAT masquerading on the given interface using nftables. Creates a postrouting chain with a masquerade rule matching traffic on the interface. Idempotent: re-adding an existing masquerade is a no-op (table/chain are re-added atomically).
func (*NetlinkRouteController) AddRoute ¶
func (c *NetlinkRouteController) AddRoute(subnet, iface string) error
AddRoute adds a route for the given CIDR subnet via the given interface. Idempotent: adding an existing route returns nil.
func (*NetlinkRouteController) DisableForwarding ¶
func (c *NetlinkRouteController) DisableForwarding(meshIface, accessIface string) error
DisableForwarding disables IPv4 forwarding for the given interfaces via sysctl.
func (*NetlinkRouteController) EnableForwarding ¶
func (c *NetlinkRouteController) EnableForwarding(meshIface, accessIface string) error
EnableForwarding enables IPv4 forwarding for the given interfaces via sysctl.
func (*NetlinkRouteController) RemoveNATMasquerade ¶
func (c *NetlinkRouteController) RemoveNATMasquerade(iface string) error
RemoveNATMasquerade removes NAT masquerading from the given interface by deleting the plexd-nat nftables table. Idempotent: removing a non-existent table returns nil.
func (*NetlinkRouteController) RemoveRoute ¶
func (c *NetlinkRouteController) RemoveRoute(subnet, iface string) error
RemoveRoute removes the route for the given CIDR subnet via the given interface. Idempotent: removing a non-existent route returns nil.
type NetlinkVPNController ¶
type NetlinkVPNController struct {
// contains filtered or unexported fields
}
NetlinkVPNController implements VPNController using Linux netlink and wgctrl for managing WireGuard site-to-site tunnel interfaces.
func NewNetlinkVPNController ¶
func NewNetlinkVPNController(logger *slog.Logger) *NetlinkVPNController
NewNetlinkVPNController returns a new NetlinkVPNController.
func (*NetlinkVPNController) ConfigureTunnelPeer ¶
func (c *NetlinkVPNController) ConfigureTunnelPeer(iface, publicKey string, allowedIPs []string, endpoint, psk string) error
ConfigureTunnelPeer adds or updates a peer on the tunnel interface.
func (*NetlinkVPNController) CreateTunnelInterface ¶
func (c *NetlinkVPNController) CreateTunnelInterface(name string, listenPort int) error
CreateTunnelInterface creates a WireGuard interface for a site-to-site tunnel.
func (*NetlinkVPNController) RemoveTunnelInterface ¶
func (c *NetlinkVPNController) RemoveTunnelInterface(name string) error
RemoveTunnelInterface deletes the named WireGuard tunnel interface. It is idempotent: removing a non-existent interface returns nil.
func (*NetlinkVPNController) RemoveTunnelPeer ¶
func (c *NetlinkVPNController) RemoveTunnelPeer(iface, publicKey string) error
RemoveTunnelPeer removes a peer from the tunnel interface by public key.
type OpenVPNProvider ¶
type OpenVPNProvider struct {
// contains filtered or unexported fields
}
OpenVPNProvider wraps the OpenVPN CLI to manage OpenVPN tunnels for site-to-site connectivity. All methods are safe for concurrent use.
func NewOpenVPNProvider ¶
func NewOpenVPNProvider(exec CommandExecutor, routes RouteController, logger *slog.Logger) *OpenVPNProvider
NewOpenVPNProvider creates a new OpenVPNProvider.
func (*OpenVPNProvider) ActiveTunnels ¶
func (p *OpenVPNProvider) ActiveTunnels() []string
ActiveTunnels returns the IDs of all active tunnels.
func (*OpenVPNProvider) CreateTunnel ¶
func (p *OpenVPNProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
CreateTunnel establishes an OpenVPN tunnel.
func (*OpenVPNProvider) Name ¶
func (p *OpenVPNProvider) Name() string
Name returns the provider identifier.
func (*OpenVPNProvider) RemoveTunnel ¶
func (p *OpenVPNProvider) RemoveTunnel(tunnelID string) error
RemoveTunnel tears down an OpenVPN tunnel. Idempotent.
func (*OpenVPNProvider) Stop ¶
func (p *OpenVPNProvider) Stop() error
Stop gracefully shuts down all managed OpenVPN tunnels. Idempotent.
func (*OpenVPNProvider) TunnelStatus ¶
func (p *OpenVPNProvider) TunnelStatus(tunnelID string) TunnelStatus
TunnelStatus returns the status of the given tunnel.
type ProviderStatus ¶
type ProviderStatus struct {
// Running indicates whether the provider process is active.
Running bool `json:"running"`
// InterfaceName is the network interface created by the provider.
InterfaceName string `json:"interface_name,omitempty"`
// IP is the IP address assigned by the provider.
IP string `json:"ip,omitempty"`
// Error holds the last error message, if any.
Error string `json:"error,omitempty"`
}
ProviderStatus represents the current status of a user access VPN provider.
type ReconcileTrigger ¶
type ReconcileTrigger interface {
TriggerReconcile()
}
ReconcileTrigger is satisfied by *reconcile.Reconciler.
type Relay ¶
type Relay struct {
// contains filtered or unexported fields
}
Relay forwards WireGuard between the peers of a state pull through one UDP socket. It works out each datagram's destination from the WireGuard message header: an initiation goes to the peer whose public key verifies its mac1, every other message by its receiver index. An initiation between two peers that hold a session waits for its retry, so a backlog that queued while the relay was frozen cannot move them to it (see holdInitiation). It holds no private or preshared key, decrypts nothing, and never answers a datagram.
func NewRelay ¶
NewRelay returns a relay that is not running. It opens no socket; Configure starts it.
func (*Relay) ActiveCount ¶
ActiveCount returns the number of distinct unordered peer pairs among the session indices used within relayIndexTTL.
func (*Relay) Bound ¶ added in v0.23.0
Bound returns the port the relay socket is bound on and when it was bound. ok is false while the relay is not running.
func (*Relay) Configure ¶ added in v0.19.0
func (r *Relay) Configure(listenPort int, peers []api.SnapshotPeer) error
Configure runs the relay on UDP listenPort and forwards among peers. A relay running on another port is stopped first; a relay not running is started. The peer set is then replaced: a peer whose node ID and public key are unchanged keeps its learned address, a new or re-keyed peer starts fresh, and a peer no longer listed is deleted with every index that names it. A peer with an invalid or a repeated public key is skipped with a Warn. A repeated call with the same port and peers changes nothing.
func (*Relay) ListenAddr ¶
ListenAddr returns the local address of the relay socket, or nil while the relay is not running.
type RelayStatus ¶ added in v0.23.0
type RelayStatus struct {
State string // one of the api.RelayState* constants
ListenPort int // running and bind_failed; 0 otherwise
BoundAt time.Time // running; zero otherwise
}
RelayStatus is the relay's state as plexd reports it.
type RelayStatusClient ¶ added in v0.23.0
type RelayStatusClient interface {
ReportRelayStatus(ctx context.Context, nodeID string, req api.RelayStatusRequest) (*api.RelayStatusResponse, error)
}
RelayStatusClient sends relay status reports. *api.ControlPlane satisfies it.
type RelayStatusReporter ¶ added in v0.23.0
type RelayStatusReporter struct {
// contains filtered or unexported fields
}
RelayStatusReporter sends the relay's state, as RelayReconcileHandler records it on a RelayStatusTracker, to PUT /v1/nodes/{node_id}/relay-status: when it changes, again once per interval, and a last stopped when plexd shuts down. The control plane takes a relay whose report in force is not running on its configured port out of the bridge candidates, and keeps a report in force only while it is repeated within three heartbeat intervals.
DECISION: the reporter sends from a goroutine of its own, never from inside the reconcile handler, so a slow control plane never delays a reconcile cycle. This follows the DECISION on agent.HandshakeReporter.
DECISION: a failed send is never retried within its tick. The control plane anchors bound_seconds on its own receive time, so the next send builds a fresh body with fresh seconds instead. A lost on-change report reaches the control plane at the next tick, at most one interval later.
DECISION: nothing is sent before the handler first ran. Until then plexd does not know the relay's state, and a stopped report at start, followed a moment later by running from the first reconcile, could land in a control plane sweep and move the relayed pairs away and back on every start. A bridge whose first pull carries no drift never runs the handler and sends nothing, which is harmless: the control plane reads the report only for an enabled relay, and enabling one is bridge drift.
DECISION (per the author): the reporter sends one last stopped report when plexd shuts down, so a bridge stopped for good gives up its pairs within about 15 s instead of waiting about 100 s for its heartbeat to read stale. The accepted cost is that every restart and self-upgrade of a bridge moves its pairs away and back, and in a Domain with one bridge the pairs lose their fallback_endpoint until the restarted agent reports running.
func NewRelayStatusReporter ¶ added in v0.23.0
func NewRelayStatusReporter(interval time.Duration, nodeID string, client RelayStatusClient, status *RelayStatusTracker, logger *slog.Logger) *RelayStatusReporter
NewRelayStatusReporter creates a RelayStatusReporter that reports the status tracker holds for nodeID through client. A non-positive interval becomes 30 s, the value of agent.DefaultHeartbeatInterval, because the report's cadence is the heartbeat interval.
func (*RelayStatusReporter) Run ¶ added in v0.23.0
func (r *RelayStatusReporter) Run(ctx context.Context) error
Run sends the status on every change and on every tick of the interval until ctx is done. It then sends the shutdown report and returns nil. No answer ends the loop and none touches the relay: a control plane that does not serve the operation yet is asked again every interval, so an upgrade is picked up without a restart.
type RelayStatusTracker ¶ added in v0.23.0
type RelayStatusTracker struct {
// contains filtered or unexported fields
}
RelayStatusTracker holds the latest RelayStatus and signals each change. RelayReconcileHandler sets it and the RelayStatusReporter reads it. It is safe for concurrent use.
func NewRelayStatusTracker ¶ added in v0.23.0
func NewRelayStatusTracker() *RelayStatusTracker
NewRelayStatusTracker returns a tracker that holds no status yet.
func (*RelayStatusTracker) Changed ¶ added in v0.23.0
func (t *RelayStatusTracker) Changed() <-chan struct{}
Changed returns the channel Set signals a change on.
func (*RelayStatusTracker) Get ¶ added in v0.23.0
func (t *RelayStatusTracker) Get() (RelayStatus, bool)
Get returns the held status and whether one was ever set.
func (*RelayStatusTracker) Set ¶ added in v0.23.0
func (t *RelayStatusTracker) Set(s RelayStatus)
Set stores s. When no status was held, or s differs from the held one, it signals Changed without blocking: a full channel already carries the signal. Several Set calls before the reader wakes collapse into one signal, and the reader then sees the latest status.
type RouteController ¶
type RouteController interface {
// EnableForwarding enables IP forwarding between the mesh and access interfaces.
EnableForwarding(meshIface, accessIface string) error
// DisableForwarding reverses the forwarding setup.
DisableForwarding(meshIface, accessIface string) error
// AddRoute adds a route for the given CIDR subnet via the given interface.
// Idempotent: adding an existing route returns nil.
AddRoute(subnet, iface string) error
// RemoveRoute removes the route for the given CIDR subnet via the given interface.
// Idempotent: removing a non-existent route returns nil.
RemoveRoute(subnet, iface string) error
NATController
}
RouteController abstracts OS-level routing and forwarding operations for testability. All methods must be idempotent: repeating an operation that is already applied returns nil.
type SiteToSiteManager ¶
type SiteToSiteManager struct {
// contains filtered or unexported fields
}
SiteToSiteManager manages site-to-site VPN tunnels — WireGuard interfaces that establish VPN connections to external networks via a bridge node. SiteToSiteManager is concurrent-safe via mu.
func NewSiteToSiteManager ¶
func NewSiteToSiteManager(ctrl VPNController, routes RouteController, cfg Config, logger *slog.Logger, tunnelProviders map[string]TunnelProvider) *SiteToSiteManager
NewSiteToSiteManager creates a new SiteToSiteManager. tunnelProviders can be nil (meaning WireGuard-only mode).
func (*SiteToSiteManager) AddTunnel ¶
func (m *SiteToSiteManager) AddTunnel(tunnel api.SiteToSiteTunnel) error
AddTunnel establishes a site-to-site tunnel: creates a WireGuard interface, configures the remote peer, enables forwarding, and adds routes for remote subnets. Returns an error if the manager is inactive, the tunnel ID already exists, or the maximum tunnel count is reached.
func (*SiteToSiteManager) GetTunnel ¶
func (m *SiteToSiteManager) GetTunnel(tunnelID string) (api.SiteToSiteTunnel, bool)
GetTunnel returns the SiteToSiteTunnel for the given ID and true if it exists, or a zero value and false otherwise.
func (*SiteToSiteManager) RemoveTunnel ¶
func (m *SiteToSiteManager) RemoveTunnel(tunnelID string)
RemoveTunnel removes a site-to-site tunnel: removes routes, disables forwarding, removes the peer, and removes the interface. Removing a non-existent tunnel or calling on an inactive manager is a no-op.
func (*SiteToSiteManager) Setup ¶
func (m *SiteToSiteManager) Setup(meshIface string) error
Setup initializes the site-to-site manager with the given mesh interface. When site-to-site is disabled this is a no-op.
func (*SiteToSiteManager) SiteToSiteCapabilities ¶
func (m *SiteToSiteManager) SiteToSiteCapabilities() map[string]string
SiteToSiteCapabilities returns capability metadata for registration. Returns nil when site-to-site is not enabled.
func (*SiteToSiteManager) SiteToSiteStatus ¶
func (m *SiteToSiteManager) SiteToSiteStatus() *api.SiteToSiteInfo
SiteToSiteStatus returns site-to-site status for heartbeat reporting. Returns nil when site-to-site is not active.
func (*SiteToSiteManager) Teardown ¶
func (m *SiteToSiteManager) Teardown() error
Teardown removes all active tunnels, their routes, forwarding, and interfaces. Errors are aggregated — cleanup continues even when individual operations fail. Idempotent: calling Teardown when inactive returns nil.
func (*SiteToSiteManager) TunnelIDs ¶
func (m *SiteToSiteManager) TunnelIDs() []string
TunnelIDs returns the IDs of all active tunnels.
type StdCommandExecutor ¶
type StdCommandExecutor struct{}
StdCommandExecutor implements CommandExecutor using os/exec.
func NewStdCommandExecutor ¶
func NewStdCommandExecutor() *StdCommandExecutor
NewStdCommandExecutor returns a new StdCommandExecutor.
func (*StdCommandExecutor) Run ¶
Run executes the named command with the given arguments and returns its combined stdout/stderr output.
func (*StdCommandExecutor) Start ¶
func (e *StdCommandExecutor) Start(ctx context.Context, name string, args ...string) (CommandHandle, error)
Start launches the named command asynchronously and returns a handle that can be used to stop it.
type StdIngressController ¶
type StdIngressController struct {
// contains filtered or unexported fields
}
StdIngressController implements IngressController using the standard library net and crypto/tls packages. It is cross-platform.
func NewStdIngressController ¶
func NewStdIngressController(logger *slog.Logger) *StdIngressController
NewStdIngressController returns a new StdIngressController.
type TailscaleProvider ¶
type TailscaleProvider struct {
// contains filtered or unexported fields
}
TailscaleProvider wraps the Tailscale CLI (tailscale/tailscaled) to join a Tailscale network on a bridge node, enabling Tailscale users to access mesh resources. TailscaleProvider is concurrent-safe via mu.
func NewTailscaleProvider ¶
func NewTailscaleProvider(exec CommandExecutor, logger *slog.Logger) *TailscaleProvider
NewTailscaleProvider creates a new TailscaleProvider.
func (*TailscaleProvider) Name ¶
func (p *TailscaleProvider) Name() string
Name returns the provider identifier.
func (*TailscaleProvider) Start ¶
func (p *TailscaleProvider) Start(ctx context.Context) error
Start launches tailscaled and joins the Tailscale network using an auth key read from the PLEXD_TAILSCALE_AUTH_KEY environment variable.
func (*TailscaleProvider) Status ¶
func (p *TailscaleProvider) Status() ProviderStatus
Status returns the current provider status.
func (*TailscaleProvider) Stop ¶
func (p *TailscaleProvider) Stop() error
Stop gracefully shuts down Tailscale and the daemon process. Idempotent: calling Stop when not running returns nil.
type TunnelConfig ¶
type TunnelConfig struct {
// TunnelID is the unique identifier for this tunnel.
TunnelID string `json:"tunnel_id"`
// LocalSubnets are the local CIDR subnets to expose through the tunnel.
LocalSubnets []string `json:"local_subnets"`
// RemoteSubnets are the remote CIDR subnets reachable through the tunnel.
RemoteSubnets []string `json:"remote_subnets"`
// RemoteEndpoint is the remote tunnel peer address (host:port or IP).
RemoteEndpoint string `json:"remote_endpoint"`
// PSK is the pre-shared key for tunnel authentication.
PSK string `json:"psk"`
// Extra holds provider-specific configuration parameters.
Extra map[string]string `json:"extra,omitempty"`
}
TunnelConfig holds the configuration for creating a tunnel via a TunnelProvider.
type TunnelProvider ¶
type TunnelProvider interface {
// Name returns the provider identifier (e.g. "ipsec", "openvpn").
Name() string
// CreateTunnel establishes a tunnel with the given configuration.
// The context controls the tunnel lifetime.
// Returns an error if the tunnel cannot be created or already exists.
CreateTunnel(ctx context.Context, cfg TunnelConfig) error
// RemoveTunnel tears down the tunnel with the given ID.
// Idempotent: removing a non-existent tunnel returns nil.
RemoveTunnel(tunnelID string) error
// TunnelStatus returns the status of the tunnel with the given ID.
// Returns a zero-value TunnelStatus with Running=false if the tunnel
// does not exist.
TunnelStatus(tunnelID string) TunnelStatus
// ActiveTunnels returns the IDs of all active tunnels.
ActiveTunnels() []string
// Stop gracefully shuts down all tunnels managed by this provider.
// Idempotent: calling Stop when no tunnels are active returns nil.
Stop() error
}
TunnelProvider abstracts lifecycle management of non-WireGuard tunnel technologies (IPsec, OpenVPN, etc.) used for site-to-site connectivity via a bridge node.
Implementations invoke the tunnel daemon/CLI to establish encrypted tunnels to external networks. The bridge manager uses TunnelProvider alongside the existing VPNController (WireGuard) to support heterogeneous site-to-site connectivity.
All methods must be safe for concurrent use.
type TunnelStatus ¶
type TunnelStatus struct {
// TunnelID is the unique identifier for this tunnel.
TunnelID string `json:"tunnel_id"`
// Running indicates whether the tunnel is active.
Running bool `json:"running"`
// InterfaceName is the network interface used by the tunnel.
InterfaceName string `json:"interface_name,omitempty"`
// Error holds the last error message, if any.
Error string `json:"error,omitempty"`
}
TunnelStatus represents the current status of a tunnel managed by a TunnelProvider.
type UserAccessManager ¶
type UserAccessManager struct {
// contains filtered or unexported fields
}
UserAccessManager manages user access integration — a WireGuard interface that allows external VPN clients to reach the mesh via a bridge node. UserAccessManager is concurrent-safe via mu.
func NewUserAccessManager ¶
func NewUserAccessManager(ctrl AccessController, routes RouteController, cfg Config, logger *slog.Logger, provider UserAccessProvider) *UserAccessManager
NewUserAccessManager creates a new UserAccessManager. The provider parameter is optional — pass nil when no external VPN provider is used.
func (*UserAccessManager) AddPeer ¶
func (m *UserAccessManager) AddPeer(peer api.UserAccessPeer) error
AddPeer adds a single user access peer. Returns an error if the maximum number of peers has been reached or the peer is already tracked.
func (*UserAccessManager) PeerPublicKeys ¶
func (m *UserAccessManager) PeerPublicKeys() []string
PeerPublicKeys returns the public keys of all active peers.
func (*UserAccessManager) RemovePeer ¶
func (m *UserAccessManager) RemovePeer(publicKey string)
RemovePeer removes a single user access peer by public key. Removing a non-existent peer is a no-op.
func (*UserAccessManager) Setup ¶
func (m *UserAccessManager) Setup() error
Setup creates the WireGuard interface for user access and enables forwarding. When user access is disabled this is a no-op.
func (*UserAccessManager) Teardown ¶
func (m *UserAccessManager) Teardown() error
Teardown removes all tracked peers, disables forwarding, and removes the WireGuard interface. Errors are aggregated — cleanup continues even when individual operations fail. Idempotent: calling Teardown when inactive returns nil.
func (*UserAccessManager) UserAccessCapabilities ¶
func (m *UserAccessManager) UserAccessCapabilities() map[string]string
UserAccessCapabilities returns capability metadata for registration. Returns nil when user access is not enabled.
func (*UserAccessManager) UserAccessStatus ¶
func (m *UserAccessManager) UserAccessStatus() *api.UserAccessInfo
UserAccessStatus returns user access status for heartbeat reporting. Returns nil when user access is not active.
type UserAccessProvider ¶
type UserAccessProvider interface {
// Name returns the provider identifier (e.g. "tailscale", "netbird").
Name() string
// Start launches the provider daemon/process. The auth credential
// (auth key, setup key) is read from the environment by the implementation.
// The context controls the provider lifetime — cancelling it should trigger
// a graceful stop.
Start(ctx context.Context) error
// Stop gracefully shuts down the provider and removes its network interface.
// Idempotent: calling Stop when not running returns nil.
Stop() error
// Status returns the current provider status.
Status() ProviderStatus
}
UserAccessProvider abstracts lifecycle management of external VPN providers (Tailscale, Netbird, etc.) used for user access into the mesh via a bridge node.
Implementations invoke the provider's CLI or daemon to join an overlay network, then report status so the bridge can route traffic between the provider's interface and the mesh.
All methods must be safe for concurrent use.
type VPNController ¶
type VPNController interface {
// CreateTunnelInterface creates a WireGuard interface for a site-to-site tunnel.
// name is the interface name, listenPort is the UDP port.
// Not idempotent: a name that already exists fails with an error wrapping
// os.ErrExist, which is what EEXIST is on Linux. The caller owns the
// interface names it hands in, so a collision is a bug, not a state to
// converge on.
CreateTunnelInterface(name string, listenPort int) error
// RemoveTunnelInterface removes the WireGuard interface with the given name.
// Idempotent: removing a non-existent interface returns nil.
RemoveTunnelInterface(name string) error
// ConfigureTunnelPeer configures the remote peer on the given tunnel interface.
// publicKey is base64-encoded, allowedIPs are the remote subnets, endpoint is host:port.
// psk may be empty if not used.
// Idempotent: re-applying the same config returns nil.
ConfigureTunnelPeer(iface string, publicKey string, allowedIPs []string, endpoint string, psk string) error
// RemoveTunnelPeer removes the remote peer from the given tunnel interface.
// Idempotent: removing a non-existent peer returns nil.
RemoveTunnelPeer(iface string, publicKey string) error
}
VPNController abstracts OS-level WireGuard tunnel operations for site-to-site testability. Every method except CreateTunnelInterface must be idempotent: repeating an operation that is already applied returns nil.
type WGAccessController ¶ added in v0.8.0
type WGAccessController struct {
// contains filtered or unexported fields
}
WGAccessController implements AccessController on top of the platform WGController: DarwinController on a utun device, WindowsController on a Wintun adapter, both running on UserspaceBackend. Every interface gets a fresh private key.
A repeated CreateInterface for the same name fails with an error wrapping os.ErrExist, which is what EEXIST is for the Linux netlink controller. RemoveInterface and RemovePeer are idempotent.
func NewWGAccessController ¶ added in v0.8.0
func NewWGAccessController(wg wireguard.WGController, logger *slog.Logger) *WGAccessController
NewWGAccessController returns a WGAccessController over wg. The access interface stays unnumbered on every platform, as it is on Linux.
func (*WGAccessController) ConfigurePeer ¶ added in v0.8.0
func (c *WGAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
ConfigurePeer adds or updates a peer on the access interface. User-access peers dial the node, so they carry no endpoint.
func (*WGAccessController) CreateInterface ¶ added in v0.8.0
func (c *WGAccessController) CreateInterface(name string, listenPort int) error
CreateInterface creates a WireGuard interface for user access.
func (*WGAccessController) RemoveInterface ¶ added in v0.8.0
func (c *WGAccessController) RemoveInterface(name string) error
RemoveInterface deletes the named WireGuard access interface. It is idempotent: removing a non-existent interface returns nil.
func (*WGAccessController) RemovePeer ¶ added in v0.8.0
func (c *WGAccessController) RemovePeer(iface, publicKey string) error
RemovePeer removes a peer from the access interface by public key. It is idempotent: removing an unknown peer returns nil.
type WGVPNController ¶ added in v0.8.0
type WGVPNController struct {
// contains filtered or unexported fields
}
WGVPNController implements VPNController on top of the platform WGController: DarwinController on a utun device, WindowsController on a Wintun adapter, both running on UserspaceBackend. Every tunnel interface gets a fresh private key.
A repeated CreateTunnelInterface for the same name fails with an error wrapping os.ErrExist, which is what EEXIST is for the Linux netlink controller. RemoveTunnelInterface and RemoveTunnelPeer are idempotent.
func NewWGVPNController ¶ added in v0.8.0
func NewWGVPNController(wg wireguard.WGController, address string, logger *slog.Logger) *WGVPNController
NewWGVPNController returns a WGVPNController over wg. address is the CIDR the tunnel interface carries.
macOS needs it: route(8) refuses a route over a utun without an IPv4 address with "Network is unreachable", so plexd up passes the node's mesh IP as a /32 there. An empty address leaves the interface unnumbered, which is what Linux and Windows use.
func (*WGVPNController) ConfigureTunnelPeer ¶ added in v0.8.0
func (c *WGVPNController) ConfigureTunnelPeer(iface, publicKey string, allowedIPs []string, endpoint, psk string) error
ConfigureTunnelPeer adds or updates the remote peer on the tunnel interface.
func (*WGVPNController) CreateTunnelInterface ¶ added in v0.8.0
func (c *WGVPNController) CreateTunnelInterface(name string, listenPort int) error
CreateTunnelInterface creates a WireGuard interface for a site-to-site tunnel.
func (*WGVPNController) OSInterfaceName ¶ added in v0.8.0
func (c *WGVPNController) OSInterfaceName(name string) (string, bool)
OSInterfaceName returns the kernel's name for the tunnel interface created under name, and false when there is no such interface. A platform that keeps the configured name, as Windows does, reports that name.
func (*WGVPNController) RemoveTunnelInterface ¶ added in v0.8.0
func (c *WGVPNController) RemoveTunnelInterface(name string) error
RemoveTunnelInterface deletes the named WireGuard tunnel interface. It is idempotent: removing a non-existent interface returns nil.
func (*WGVPNController) RemoveTunnelPeer ¶ added in v0.8.0
func (c *WGVPNController) RemoveTunnelPeer(iface, publicKey string) error
RemoveTunnelPeer removes the remote peer from the tunnel interface by public key. It is idempotent: removing an unknown peer returns nil.
Source Files
¶
- access_controller.go
- access_controller_linux.go
- access_controller_wg.go
- acme.go
- config.go
- exec.go
- exec_std.go
- handler.go
- ingress.go
- ingress_certs.go
- ingress_controller.go
- ingress_controller_std.go
- ingress_dial.go
- ingress_dial_unix.go
- ingress_plan.go
- ingress_report.go
- ingress_status.go
- ipsec.go
- manager.go
- netbird.go
- openvpn.go
- reconcile_handler.go
- relay.go
- relay_status.go
- relay_wire.go
- route.go
- route_forwarding.go
- route_linux.go
- site_to_site.go
- sni.go
- tailscale.go
- tunnel_provider.go
- user_access.go
- user_access_provider.go
- vpn_controller.go
- vpn_controller_linux.go
- vpn_controller_wg.go
- wg_controller.go