Documentation
¶
Overview ¶
Package bridge provides bridge mode functionality including user access integration.
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func CleanupSiteToSite(vpn VPNController, providers map[string]TunnelProvider) error
- func CleanupUserAccess(access AccessController, rewriter MeshSourceRewriter) error
- 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 SiteToSitePullHandler(mgr *SiteToSiteManager) reconcile.DispatchHandler
- func SiteToSiteReconcileHandler(mgr *SiteToSiteManager, logger *slog.Logger) reconcile.ReconcileHandler
- func UserAccessPullHandler(mgr *UserAccessManager) reconcile.DispatchHandler
- func UserAccessReconcileHandler(mgr *UserAccessManager, logger *slog.Logger) reconcile.ReconcileHandler
- func ValidACMEDirectoryURL(s string) bool
- func ValidateTunnelConfig(cfg TunnelConfig) 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) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
- func (p *IPsecProvider) Established(ctx context.Context, tunnelID string) (bool, error)
- func (p *IPsecProvider) Name() string
- func (p *IPsecProvider) RemoveTunnel(ctx context.Context, tunnelID string) error
- func (p *IPsecProvider) Reset(ctx context.Context) error
- 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 InterfaceKeyStore
- 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 MeshSourceRewriter
- type NATController
- type NetbirdProvider
- type NetlinkAccessController
- func (c *NetlinkAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
- func (c *NetlinkAccessController) CreateInterface(name string, privateKey []byte, listenPort int, address string) (err error)
- func (c *NetlinkAccessController) PeerHandshakes(iface string) (map[string]time.Time, error)
- func (c *NetlinkAccessController) RemoveInterface(name string) error
- func (c *NetlinkAccessController) RemoveInterfaces(prefix string) error
- func (c *NetlinkAccessController) RemovePeer(iface, publicKey string) error
- type NetlinkRouteController
- func (c *NetlinkRouteController) AddMeshSourceRewrite(fromIface, meshIface string) error
- 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) RemoveMeshSourceRewrite(fromIface, meshIface string) error
- func (c *NetlinkRouteController) RemoveNATMasquerade(iface string) error
- func (c *NetlinkRouteController) RemoveRoute(subnet, iface string) error
- func (c *NetlinkRouteController) ResetMeshSourceRewrite() error
- type NetlinkVPNController
- func (c *NetlinkVPNController) ConfigureTunnelPeer(iface, publicKey string, allowedIPs []string, endpoint, psk string) error
- func (c *NetlinkVPNController) CreateTunInterface(name string) (err error)
- func (c *NetlinkVPNController) CreateTunnelInterface(name string, privateKey []byte, listenPort int) (err error)
- func (c *NetlinkVPNController) CreateXfrmInterface(name string, ifID uint32) (err error)
- func (c *NetlinkVPNController) RemoveTunnelInterface(name string) error
- func (c *NetlinkVPNController) RemoveTunnelInterfaces(prefixes []string) error
- func (c *NetlinkVPNController) RemoveTunnelPeer(iface, publicKey string) error
- func (c *NetlinkVPNController) TunnelPeerHandshake(iface, publicKey string) (time.Time, error)
- type OpenVPNProvider
- func (p *OpenVPNProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
- func (p *OpenVPNProvider) Established(ctx context.Context, tunnelID string) (bool, error)
- func (p *OpenVPNProvider) Name() string
- func (p *OpenVPNProvider) RemoveTunnel(_ context.Context, tunnelID string) error
- func (p *OpenVPNProvider) Reset(_ context.Context) error
- type ProviderStatus
- type ReconcileTrigger
- type Relay
- type RelayStatus
- type RelayStatusClient
- type RelayStatusReporter
- type RelayStatusTracker
- type RouteController
- type SecretValueFetcher
- type SiteToSiteDeps
- type SiteToSiteManager
- func (m *SiteToSiteManager) Apply(ctx context.Context, block api.SiteToSiteConfig)
- func (m *SiteToSiteManager) ReportChanged() <-chan struct{}
- func (m *SiteToSiteManager) Retry(ctx context.Context)
- func (m *SiteToSiteManager) Setup() error
- func (m *SiteToSiteManager) SiteToSiteStatus() *api.SiteToSiteInfo
- func (m *SiteToSiteManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
- func (m *SiteToSiteManager) Teardown() error
- func (m *SiteToSiteManager) TunnelReports() []SiteToSiteTunnelReport
- type SiteToSiteStatusClient
- type SiteToSiteStatusReporter
- type SiteToSiteTunnelReport
- type SiteToSiteTunnelReportSource
- type StdCommandExecutor
- type StdIngressController
- type TailscaleProvider
- type TunnelConfig
- type TunnelProvider
- type UserAccessClient
- type UserAccessDeps
- type UserAccessManager
- func (m *UserAccessManager) Apply(ctx context.Context, block api.UserAccessConfig)
- func (m *UserAccessManager) ProviderReports() []UserAccessProviderReport
- func (m *UserAccessManager) ReportChanged() <-chan struct{}
- func (m *UserAccessManager) Retry(ctx context.Context)
- func (m *UserAccessManager) Setup() error
- func (m *UserAccessManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
- func (m *UserAccessManager) Teardown() error
- func (m *UserAccessManager) UserAccessStatus() *api.UserAccessInfo
- type UserAccessProviderReport
- type UserAccessProviderReportSource
- type UserAccessStatusClient
- type UserAccessStatusReporter
- type VPNController
- type WGAccessController
- func (c *WGAccessController) ConfigurePeer(iface, publicKey string, allowedIPs []string, psk string) error
- func (c *WGAccessController) CreateInterface(name string, privateKey []byte, listenPort int, address string) error
- func (c *WGAccessController) PeerHandshakes(iface string) (map[string]time.Time, error)
- func (c *WGAccessController) RemoveInterface(name string) error
- func (c *WGAccessController) RemoveInterfaces(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) CreateTunInterface(name string) error
- func (c *WGVPNController) CreateTunnelInterface(name string, privateKey []byte, listenPort int) error
- func (c *WGVPNController) CreateXfrmInterface(name string, _ uint32) error
- func (c *WGVPNController) OSInterfaceName(name string) (string, bool)
- func (c *WGVPNController) RemoveTunnelInterface(name string) error
- func (c *WGVPNController) RemoveTunnelInterfaces([]string) error
- func (c *WGVPNController) RemoveTunnelPeer(iface, publicKey string) error
- func (c *WGVPNController) TunnelPeerHandshake(iface, publicKey string) (time.Time, error)
Constants ¶
const ( DefaultMaxIngressRules = 20 DefaultMaxIngressUDPFlows = 1024 DefaultIngressDialTimeout = 10 * time.Second )
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 of the same protocol has the // same listen port and host, or one of the two has no host; Detail is the // holder's slug. Rules with request conditions share a port and host when // they all name the same mode and certificate_secret_name and no two have // the same conditions; a rule that breaks this conflicts with the host's // first held rule, or with the held rule whose conditions equal its own. // A udp rule has no host, so it conflicts with every held udp rule on its // port, and a tcp and a udp rule never conflict. 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 ( // SiteToSiteReasonInvalidTunnel: a member of the entry is missing or // malformed, or the entry clashes with an earlier one of the block. It is // not retried until the entry changes. SiteToSiteReasonInvalidTunnel = "invalid_tunnel" // SiteToSiteReasonKindNotServed: this plexd serves no tunnel of the kind, // because the platform has no mesh source rewrite, the kind is unknown, // or no provider of the kind is built in. It is not retried until the // entry changes. SiteToSiteReasonKindNotServed = "kind_not_served" // interface could not be read or created. SiteToSiteReasonKeyUnavailable = "key_unavailable" // SiteToSiteReasonBindFailed: the interface of a wireguard tunnel cannot // listen on its port, which another socket holds. SiteToSiteReasonBindFailed = "bind_failed" // SiteToSiteReasonSetupFailed: the tunnel's link, its peer, its // forwarding, its source rewrite, its routes or the daemon's side of it // could not be set up, the Secret of a wireguard tunnel holds no // preshared key, or an ipsec tunnel has no mesh CIDR as its local // traffic selector. SiteToSiteReasonSetupFailed = "setup_failed" // SiteToSiteReasonAuthSecretNotListed: the secret inventory does not list // the Secret the tunnel names. SiteToSiteReasonAuthSecretNotListed = "auth_secret_not_listed" // SiteToSiteReasonAuthSecretUnreadable: the inventory lists the Secret, // but it could not be fetched. SiteToSiteReasonAuthSecretUnreadable = "auth_secret_unreadable" // SiteToSiteReasonClientMissing: the host has no client of the kind, // swanctl for ipsec or openvpn for openvpn. SiteToSiteReasonClientMissing = "client_missing" // SiteToSiteReasonRemoteHostUnresolved: remote_host is a host name that // does not resolve. SiteToSiteReasonRemoteHostUnresolved = "remote_host_unresolved" )
The reasons a site-to-site tunnel is down for. Each is the reason of the tunnel's entry in the node API's status.site-to-site report and of its "site-to-site tunnel down" line. invalid_tunnel, setup_failed and key_unavailable are plexd's own; the control plane stores any token of the reason grammar.
const ( // UserAccessReasonInvalidProvider: a member of the entry is missing or // malformed, or the entry clashes with an earlier one of the block. It is // not retried until the entry changes. UserAccessReasonInvalidProvider = "invalid_provider" // UserAccessReasonKindNotServed: this plexd serves no provider of the // kind, because the platform has no mesh source rewrite, the kind is // unknown, or no client of the kind is built in. It is not retried until // the entry changes. UserAccessReasonKindNotServed = "kind_not_served" // interface could not be read or created. UserAccessReasonKeyUnavailable = "key_unavailable" // UserAccessReasonBindFailed: the interface of a wireguard provider // cannot listen on its port, which another socket holds. UserAccessReasonBindFailed = "bind_failed" // UserAccessReasonSetupFailed: the provider's interface, its forwarding // or its source rewrite could not be set up, or a tailscale provider has // no mesh CIDR to advertise. UserAccessReasonSetupFailed = "setup_failed" // UserAccessReasonAuthSecretNotListed: the secret inventory does not list // the Secret a vendor provider names. UserAccessReasonAuthSecretNotListed = "auth_secret_not_listed" // UserAccessReasonAuthSecretUnreadable: the inventory lists the Secret, // but it could not be fetched. UserAccessReasonAuthSecretUnreadable = "auth_secret_unreadable" // UserAccessReasonJoinFailed: the vendor client did not join its network // with the key, or reports no interface after it did. UserAccessReasonJoinFailed = "join_failed" // UserAccessReasonClientMissing: the host has no client of the kind. UserAccessReasonClientMissing = "client_missing" )
The reasons a user access provider is down for. Each is the reason of the provider's entry in a user access status report and of its "user access provider down" line. invalid_provider, setup_failed and key_unavailable are plexd's own; the control plane stores any token of the reason grammar.
const ( // SiteToSiteWireGuardPrefix begins the name of the WireGuard interface // of a wireguard tunnel. SiteToSiteWireGuardPrefix = "wg-s2s-" // SiteToSiteXfrmPrefix begins the name of the xfrm interface of an // ipsec tunnel. SiteToSiteXfrmPrefix = "xf-s2s-" // SiteToSiteTunPrefix begins the name of the tun device of an openvpn // tunnel. SiteToSiteTunPrefix = "ov-s2s-" )
The prefixes of the links plexd creates for site-to-site tunnels, one per kind. A tunnel's link is named by its prefix and the last 8 hex digits of the tunnel's id, which gives 15 characters, the kernel's limit. The prefixes are how a start finds the links a killed process left behind.
const DefaultTunnelConfigDir = "/run/plexd/tunnels"
DefaultTunnelConfigDir is the directory the OpenVPNProvider keeps the files of its tunnels in. It lies under the run directory, so it is gone after a reboot, and it is created with mode 0700, so no other user reads a key.
const UserAccessInterfacePrefix = "wg-ua-"
UserAccessInterfacePrefix begins the name of every kernel interface plexd creates for a wireguard user access provider, so that the interfaces a killed process left behind can be found by their name.
Variables ¶
var ErrListenPortInUse = errors.New("listen port in use")
ErrListenPortInUse reports that CreateInterface could not bind the listen port because another socket holds it. A caller tells a taken port from any other failure with errors.Is; the error that wraps it also wraps the cause the kernel reported.
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.
var SiteToSiteInterfacePrefixes = []string{ SiteToSiteWireGuardPrefix, SiteToSiteXfrmPrefix, SiteToSiteTunPrefix, }
SiteToSiteInterfacePrefixes lists the prefixes of every kind of site-to-site link, in the order wireguard, ipsec, openvpn. It is what a start hands to RemoveTunnelInterfaces.
Functions ¶
func CleanupSiteToSite ¶ added in v0.36.0
func CleanupSiteToSite(vpn VPNController, providers map[string]TunnelProvider) error
CleanupSiteToSite removes what a process that was killed left behind: every link whose name starts with one of SiteToSiteInterfacePrefixes, through vpn.RemoveTunnelInterfaces, and the files of every provider, through its Reset, all under a timeout of 30 s. A nil vpn is skipped. Every step runs; the errors are joined.
The source rewrites of a killed process are gone before it runs: plexd up runs CleanupUserAccess first, which resets the table both managers share. Without it a tunnel's next create fails on the name the killed process left, and a link of a bridge that opted out since keeps its port open.
func CleanupUserAccess ¶ added in v0.36.0
func CleanupUserAccess(access AccessController, rewriter MeshSourceRewriter) error
CleanupUserAccess removes what a process that was killed left behind: every interface whose name starts with UserAccessInterfacePrefix, through access.RemoveInterfaces, and with a rewriter every mesh source rewrite, through rewriter.ResetMeshSourceRewrite. A nil access or rewriter is skipped. Both run; their errors are joined.
Without it a provider's next CreateInterface fails on the name the killed process left, and an interface of a bridge that opted out since keeps its port open.
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 SiteToSitePullHandler ¶ added in v0.36.0
func SiteToSitePullHandler(mgr *SiteToSiteManager) reconcile.DispatchHandler
SiteToSitePullHandler returns a reconcile.DispatchHandler that runs on every successful pull. It hands the pull's secret inventory to the site-to-site manager, which rebuilds each tunnel whose Secret the inventory lists at a new version and brings up again each tunnel that is down for a reason a retry can cure and whose next attempt is due. A pull whose only change is the secrets block reports no drift, so no reconcile handler would see a rotated Secret, and a tunnel whose port was taken or whose remote host did not resolve needs a retry whatever drifted. A nil Secrets block, a control plane that did not say this time, keeps the inventory the manager holds and only retries. Dispatch handlers run before the reconcile handlers, so a cycle that brings a new tunnel and its Secret hands the inventory over first. A nil snapshot changes nothing.
func SiteToSiteReconcileHandler ¶
func SiteToSiteReconcileHandler(mgr *SiteToSiteManager, logger *slog.Logger) reconcile.ReconcileHandler
SiteToSiteReconcileHandler returns a reconcile.ReconcileHandler that serves the desired bridge.site_to_site block whole. mgr is nil when the node opts out of site-to-site tunnels, bridge.site_to_site_enabled: false. A nil snapshot changes nothing, and the handler returns nil in every case: a tunnel that is down is retried by SiteToSitePullHandler, so one broken tunnel never makes the reconciler apply the whole snapshot again.
With a manager, the pulled block is applied as it is, and a nil Bridge or nil SiteToSite child applies the zero block, which tears every tunnel down and deletes every key file. The manager serves tunnels only when the block's Enabled is true.
Without a manager the handler touches nothing. A block with Enabled true and at least one tunnel is logged as a Warn naming how many tunnels the local opt-out leaves unserved, only when diff.BridgeChanged is set: the reconciler invokes every handler on any drift, and an ungated Warn would repeat on each peer or policy change. It is logged once per change of the pulled bridge block, which includes the first pull after every start.
func UserAccessPullHandler ¶ added in v0.36.0
func UserAccessPullHandler(mgr *UserAccessManager) reconcile.DispatchHandler
UserAccessPullHandler returns a reconcile.DispatchHandler that runs on every successful pull. It hands the pull's secret inventory to the user access manager, which brings up again each provider that is down for a reason a retry can cure and whose next attempt is due. A pull whose only change is the secrets block reports no drift, so no reconcile handler would see a Secret the inventory newly lists, and a provider whose port was taken needs a retry whatever drifted. A nil Secrets block, a control plane that did not say this time, keeps the inventory the manager holds and only retries. Dispatch handlers run before the reconcile handlers, so a cycle that brings a new provider and its Secret hands the inventory over first. A nil snapshot changes nothing.
func UserAccessReconcileHandler ¶
func UserAccessReconcileHandler(mgr *UserAccessManager, logger *slog.Logger) reconcile.ReconcileHandler
UserAccessReconcileHandler returns a reconcile.ReconcileHandler that serves the desired bridge.user_access block whole. mgr is nil when the node opts out of user access, bridge.user_access_enabled: false. A nil snapshot changes nothing, and the handler returns nil in every case: a provider that is down is retried by UserAccessPullHandler, so one broken provider never makes the reconciler apply the whole snapshot again.
With a manager, the pulled block is applied as it is, and a nil Bridge or nil UserAccess child applies the zero block, which tears every provider down and deletes every key file. The manager serves providers only when the block's Enabled is true.
Without a manager the handler touches nothing. A block with Enabled true and at least one provider is logged as a Warn naming how many providers the local opt-out leaves unserved, only when diff.BridgeChanged is set: the reconciler invokes every handler on any drift, and an ungated Warn would repeat on each peer or policy change. It is logged once per change of the pulled bridge block, which includes the first pull after every start.
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 checks what a provider writes into a file before it writes it: TunnelID passes api.ValidSiteToSiteTunnelID, RemoteHost matches ^[A-Za-z0-9.:-]{1,253}$, RemotePort is 1 to 65535, every subnet parses as a prefix, and InterfaceName matches ^[a-z0-9-]{1,15}$. Key is not checked here: each provider checks it for its own form. An error never quotes Key.
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,
// configures privateKey (32 raw bytes) and listenPort on it, assigns
// address (a CIDR such as 10.98.0.1/24; empty leaves the interface
// unnumbered) and brings it up. The caller owns the key, so an interface
// created again under the same key keeps its public key.
//
// A failure after the interface exists removes it again. A listen port
// another socket holds fails with an error wrapping ErrListenPortInUse
// where the implementation can tell; NetlinkAccessController does.
//
// Not idempotent: a name that already exists fails with an error wrapping
// os.ErrExist, which is what EEXIST is on Linux.
CreateInterface(name string, privateKey []byte, listenPort int, address string) error
// RemoveInterface removes the WireGuard interface with the given name.
// Idempotent: removing a non-existent interface returns nil.
RemoveInterface(name string) error
// RemoveInterfaces removes every WireGuard interface whose name starts
// with prefix, which is how a start clears the interfaces a killed
// process left behind. Idempotent: with no such interface it returns nil.
RemoveInterfaces(prefix 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
// PeerHandshakes returns the time of the latest handshake of every peer
// on the given interface, keyed by the peer's public key in standard
// base64. A peer that never completed a handshake maps to the zero time.
PeerHandshakes(iface string) (map[string]time.Time, 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 is the local switch for user access. nil and true
// serve the providers the state pull's bridge.user_access block enables;
// false opts the node out: plexd builds no user access manager, creates
// no interface and starts no vendor client whatever the pull says.
// Default: nil, which serves. An explicit true requires Enabled=true.
UserAccessEnabled *bool `yaml:"user_access_enabled"`
// UserAccessInterfaceName is ignored.
UserAccessInterfaceName string `yaml:"user_access_interface_name"`
// UserAccessListenPort is ignored.
UserAccessListenPort int `yaml:"user_access_listen_port"`
// MaxAccessPeers is ignored.
MaxAccessPeers int `yaml:"max_access_peers"`
// UserAccessProviderType is ignored.
UserAccessProviderType string `yaml:"user_access_provider_type"`
// AuthKeyEnv is ignored.
AuthKeyEnv string `yaml:"auth_key_env"`
// SetupKeyEnv is ignored.
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"`
// MaxIngressUDPFlows is the most flows one udp ingress rule holds, a
// flow being the datagrams of one client address and port.
// Default: 1024
MaxIngressUDPFlows int `yaml:"max_ingress_udp_flows"`
// IngressDialTimeout is the timeout for dialing target mesh peers.
// Default: 10s. Minimum: 1s.
IngressDialTimeout time.Duration `yaml:"ingress_dial_timeout"`
// SiteToSiteEnabled is the local switch for site-to-site tunnels. nil and
// true serve the tunnels the state pull's bridge.site_to_site block
// enables; false opts the node out: plexd builds no site-to-site manager,
// creates no tunnel link and routes no network behind a tunnel into the
// mesh whatever the pull says.
// Default: nil, which serves. An explicit true requires Enabled=true.
SiteToSiteEnabled *bool `yaml:"site_to_site_enabled"`
// SiteToSiteInterfacePrefix is ignored.
SiteToSiteInterfacePrefix string `yaml:"site_to_site_interface_prefix"`
// SiteToSiteListenPort is ignored.
SiteToSiteListenPort int `yaml:"site_to_site_listen_port"`
// MaxSiteToSiteTunnels is ignored.
MaxSiteToSiteTunnels int `yaml:"max_site_to_site_tunnels"`
// TunnelProviders is ignored.
TunnelProviders []string `yaml:"tunnel_providers"`
// SwanctlConfDir is the directory plexd writes the strongSwan connection
// file of each ipsec tunnel into, which the host's
// /etc/swanctl/swanctl.conf includes as <dir>/*.conf. Empty means
// <run dir>/swanctl, which plexd up resolves. A value must be an
// absolute path.
SwanctlConfDir string `yaml:"swanctl_conf_dir"`
// 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.
func (*Config) ReplacedSiteToSiteKeys ¶ added in v0.36.0
ReplacedSiteToSiteKeys returns the YAML names of the ignored site-to-site keys that are set to a value other than the zero value, in the order site_to_site_interface_prefix, site_to_site_listen_port, max_site_to_site_tunnels, tunnel_providers, and nil when none is set.
func (*Config) ReplacedUserAccessKeys ¶ added in v0.36.0
ReplacedUserAccessKeys returns the YAML names of the ignored user access keys that are set to a value other than the zero value, in the order user_access_interface_name, user_access_listen_port, max_access_peers, user_access_provider_type, auth_key_env, setup_key_env, and nil when none is set.
func (*Config) SiteToSiteOptedOut ¶ added in v0.36.0
SiteToSiteOptedOut reports whether the node opts out of site-to-site tunnels: true exactly when SiteToSiteEnabled is set to false. An unset SiteToSiteEnabled serves.
func (*Config) UserAccessOptedOut ¶ added in v0.36.0
UserAccessOptedOut reports whether the node opts out of user access: true exactly when UserAccessEnabled is set to false. An unset UserAccessEnabled serves.
type IPsecProvider ¶
type IPsecProvider struct {
// contains filtered or unexported fields
}
IPsecProvider runs the strongSwan side of ipsec site-to-site tunnels. Each tunnel is a route-based IKEv2 connection bound to the xfrm interface the SiteToSiteManager created, written as <confDir>/plexd-<id>.conf and loaded with swanctl. The host runs the strongSwan daemon and includes <confDir>/*.conf in /etc/swanctl/swanctl.conf; swanctl --load-all reads that file, so a connection plexd writes loads beside the host's own and unloads when its file is gone.
All methods are safe for concurrent use.
func NewIPsecProvider ¶
func NewIPsecProvider(exec CommandExecutor, confDir string, logger *slog.Logger) *IPsecProvider
NewIPsecProvider returns an IPsecProvider that writes its connection files into confDir and runs swanctl through exec.
func (*IPsecProvider) CreateTunnel ¶
func (p *IPsecProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
CreateTunnel writes the tunnel's connection file with mode 0600 into confDir, which it creates with mode 0700, loads it with swanctl --load-all --clear --noprompt and checks with swanctl --list-conns that strongSwan holds the connection. The pre-shared key is written in its hex form, which carries any key without quoting.
An empty Key is refused before anything is written. A failed load removes the file and returns the error wrapped, so exec.ErrNotFound stays visible; unless swanctl is missing, it loads again without the file, since a load that failed on another part of the host's configuration may still have loaded the connection. When --list-conns does not list the connection, because the host's swanctl.conf does not include confDir, the file is removed and loaded away again, and the error names the include line; a failed --list-conns is undone the same way.
func (*IPsecProvider) Established ¶ added in v0.36.0
Established runs swanctl --list-sas --ike plexd-<id> --raw and reports whether the output holds both state=ESTABLISHED, the IKE security association, and state=INSTALLED, a child security association.
func (*IPsecProvider) Name ¶
func (p *IPsecProvider) Name() string
Name returns the kind the provider serves.
func (*IPsecProvider) RemoveTunnel ¶
func (p *IPsecProvider) RemoveTunnel(ctx context.Context, tunnelID string) error
RemoveTunnel removes the tunnel's connection file, loads again, which unloads the connection, and terminates its IKE security association with swanctl --terminate --ike plexd-<id>. The terminate's result is ignored: it fails once the unload has closed the connection. Without a file it runs nothing.
func (*IPsecProvider) Reset ¶ added in v0.36.0
func (p *IPsecProvider) Reset(ctx context.Context) error
Reset removes every plexd-*.conf file of confDir. When it removed one, it loads again and terminates the IKE security association of each removed connection, ignoring the terminates' results. A host without swanctl is no error, and neither is a confDir that does not exist.
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
// ListenUDP opens a UDP socket on the given address. The manager closes
// the socket itself.
ListenUDP(addr string) (*net.UDPConn, error)
}
IngressController abstracts the sockets of public ingress for testability: a TCP listener for each listen port of the tcp rules and a UDP socket for each listen port of the udp rules. All methods must be idempotent where applicable.
type IngressDialPolicy ¶ added in v0.35.0
type IngressDialPolicy interface {
// DialDenied reports whether the compiled policy blocks a dial of
// protocol, tcp or udp, to target.
DialDenied(protocol string, target netip.AddrPort) bool
}
IngressDialPolicy tells whether the node's compiled policy blocks a 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 tcp rules of the bridge.ingress block, routing each connection to the target of its rule, and one UDP socket per listen port of its udp rules, forwarding the datagrams of each client address and port on a flow of their own (see serveUDP). 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. On a host whose terminate or acme rules have request conditions, one HTTP server reads each request and forwards it to the target of the rule it matches (see serveHTTP). 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 TCP 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. It does the same for the UDP socket of each udp port, in ascending order, swapping the port's route in place. A route whose rule is unchanged keeps its context and its connections or flows, and a route with conditions its proxy and target connections; every other route of the last Apply is cancelled, which closes its connections, flows and requests in flight. A host whose rules have conditions keeps its client connections while the port's table holds the host under the same key with conditions, the same mode and the same certificate_secret_name; every other such host is cancelled, which closes them. A failed bind marks the rules of that port and protocol listen_failed and is retried by the next Apply; the other ports, and the other protocol on the same port number, 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 for its protocol, a TCP listener for a tcp rule and a UDP socket for a udp rule, and otherwise reads listen_failed. For a rule that listens, the certificate is not_required for passthrough, which every udp rule is; 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, for a udp rule the last send of a client's datagram that counted as one (see forwardUDP), 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 and starts the HTTP server that reads the requests of a host whose rules have conditions. 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 and host, which closes every connection and every udp flow, closes every listener and UDP socket and the HTTP server, and forgets the secret inventory and every certificate. It returns once every accept loop, read loop and reply loop has ended and the HTTP server's Serve has returned. 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 held rule it conflicts with, 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 InterfaceKeyStore ¶ added in v0.36.0
type InterfaceKeyStore struct {
// contains filtered or unexported fields
}
InterfaceKeyStore keeps the private keys of WireGuard interfaces in one directory, one file per id, so an interface built again for the same id carries the key it had before. A key is the standard base64 encoding of its 32 bytes, the form the node's own private_key is stored in.
The store is safe for concurrent use. Two stores over the same directory do not coordinate their writes.
func NewInterfaceKeyStore ¶ added in v0.36.0
func NewInterfaceKeyStore(dir string) *InterfaceKeyStore
NewInterfaceKeyStore returns a store over dir. Nothing is created on disk until LoadOrCreate needs it.
func (*InterfaceKeyStore) LoadOrCreate ¶ added in v0.36.0
func (s *InterfaceKeyStore) LoadOrCreate(id string) (wgtypes.Key, error)
LoadOrCreate returns the key stored for id. When the store has none, it generates one, writes it and returns it.
The directory is created with mode 0700 when it does not exist; one that exists keeps its mode. A key file is written with mode 0600. A file that does not hold the base64 encoding of 32 bytes is an error and is never replaced: a fresh key would invalidate every peer that knows the old one.
func (*InterfaceKeyStore) Prune ¶ added in v0.36.0
func (s *InterfaceKeyStore) Prune(keep map[string]struct{}) error
Prune deletes the key file of every id not in keep. It considers only regular files named <id>.key with an id LoadOrCreate accepts, and leaves every other entry of the directory alone, among them the temp files of an interrupted write. A directory that does not exist holds no key and is no error. A failed deletion does not stop the others; the errors are joined.
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 MeshSourceRewriter ¶ added in v0.36.0
type MeshSourceRewriter interface {
// AddMeshSourceRewrite rewrites the source of packets that arrive on
// fromIface and leave through meshIface. A rewrite that exists for
// fromIface is left alone.
AddMeshSourceRewrite(fromIface, meshIface string) error
// RemoveMeshSourceRewrite removes the rewrite for fromIface.
// Idempotent: removing a rewrite that does not exist returns nil.
RemoveMeshSourceRewrite(fromIface, meshIface string) error
// ResetMeshSourceRewrite removes every rewrite, also those a process
// that was killed left behind.
// Idempotent: resetting when no rewrite exists returns nil.
ResetMeshSourceRewrite() error
}
MeshSourceRewriter rewrites the source address of packets forwarded from a user access interface into the mesh to the address of the mesh interface, the bridge's mesh address. A mesh node accepts from the bridge only that address, so a packet that kept a device's address would be dropped by the first peer it meets. It is a dependency of its own rather than a method of NATController, so the pf and WinNAT backends that implement NATController on macOS and Windows do not implement it. NetlinkRouteController implements it through nftables. All methods must be idempotent.
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 UserAccessClient 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 ¶
Start joins the Netbird network by running `netbird up` with the setup key, then queries `netbird status --json` to discover the assigned IP and interface name. Both run under a timeout of vendorJoinTimeout derived from ctx. meshCIDR is ignored: a NetBird client cannot advertise a route, which NetBird's management service defines with the bridge as routing peer. The key is passed on netbird's command line and never logged.
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, privateKey []byte, listenPort int, address string) (err error)
CreateInterface creates a WireGuard interface for user access: it adds the link, configures privateKey and listenPort through wgctrl, assigns address when it is not empty and brings the link up.
The key and the address are checked before the link is added, so malformed input leaves nothing behind. A failure after the link exists deletes it before the error returns, so a retry does not fail on the name. A listen port another socket holds fails with an error wrapping ErrListenPortInUse, see listenPortErr.
func (*NetlinkAccessController) PeerHandshakes ¶ added in v0.36.0
PeerHandshakes reads the access interface through wgctrl and returns the latest handshake of every peer, keyed by its public key in standard base64. wgctrl gives a zero LastHandshakeTime for a peer that never completed a handshake, so it passes through unchanged.
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) RemoveInterfaces ¶ added in v0.36.0
func (c *NetlinkAccessController) RemoveInterfaces(prefix string) error
RemoveInterfaces deletes every link of type wireguard whose name starts with prefix. An empty prefix is refused, since it would match the mesh interface and every tunnel. removeLinks says how a link that is already gone and an interrupted link dump count.
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. It implements MeshSourceRewriter through nftables as well.
func NewNetlinkRouteController ¶
func NewNetlinkRouteController(logger *slog.Logger) *NetlinkRouteController
NewNetlinkRouteController returns a new NetlinkRouteController.
func (*NetlinkRouteController) AddMeshSourceRewrite ¶ added in v0.36.0
func (c *NetlinkRouteController) AddMeshSourceRewrite(fromIface, meshIface string) error
AddMeshSourceRewrite masquerades packets that arrive on fromIface and leave through meshIface, which gives them the address of meshIface. The rule lives in the IPv4 table plexd-mesh-nat, in the chain postrouting (type nat, hook postrouting, priority srcnat); both are added when they are missing. The rule carries fromIface as a comment in its user data, by which RemoveMeshSourceRewrite finds it again. Idempotent: a rule that carries fromIface is left alone, whatever meshIface it names.
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) RemoveMeshSourceRewrite ¶ added in v0.36.0
func (c *NetlinkRouteController) RemoveMeshSourceRewrite(fromIface, meshIface string) error
RemoveMeshSourceRewrite deletes the rule AddMeshSourceRewrite added for fromIface. meshIface is not needed to find it and is only logged. Idempotent: a missing rule, chain or table returns nil.
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.
func (*NetlinkRouteController) ResetMeshSourceRewrite ¶ added in v0.36.0
func (c *NetlinkRouteController) ResetMeshSourceRewrite() error
ResetMeshSourceRewrite deletes the table plexd-mesh-nat with every rewrite in it. It touches neither the table plexd-nat nor the policy table plexd. Idempotent: a missing table returns nil.
type NetlinkVPNController ¶
type NetlinkVPNController struct {
// contains filtered or unexported fields
}
NetlinkVPNController implements VPNController using Linux netlink and wgctrl for managing the links of site-to-site tunnels: WireGuard interfaces, xfrm interfaces and persistent tun devices.
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) CreateTunInterface ¶ added in v0.36.0
func (c *NetlinkVPNController) CreateTunInterface(name string) (err error)
CreateTunInterface creates the tun device of an openvpn tunnel, what ip tuntap add <name> mode tun creates, and brings it up. The device is persistent, so it outlives the descriptor that created it and the openvpn process attaches to it by name. It carries no packet information header and no address. A failure after the device exists deletes it before the error returns.
The kernel attaches to a tun device that already carries the name and that no process holds open, rather than refusing it, so such a device is taken over. A name that a link of another kind holds fails.
func (*NetlinkVPNController) CreateTunnelInterface ¶
func (c *NetlinkVPNController) CreateTunnelInterface(name string, privateKey []byte, listenPort int) (err error)
CreateTunnelInterface creates a WireGuard interface for a site-to-site tunnel: it adds the link, configures privateKey and listenPort through wgctrl and brings the link up. It works as NetlinkAccessController.CreateInterface does, without an address.
The key is checked before the link is added, so a malformed key leaves nothing behind. A failure after the link exists deletes it before the error returns, so a retry does not fail on the name. A listen port another socket holds fails with an error wrapping ErrListenPortInUse, see listenPortErr.
func (*NetlinkVPNController) CreateXfrmInterface ¶ added in v0.36.0
func (c *NetlinkVPNController) CreateXfrmInterface(name string, ifID uint32) (err error)
CreateXfrmInterface creates the xfrm interface of an ipsec tunnel, what ip link add <name> type xfrm dev lo if_id <ifID> creates, and brings it up. The loopback link is its parent, so the interface depends on no uplink. ifID 0 is refused before anything is added, since strongSwan binds a connection to the interface by a non-zero id. A failure after the link exists deletes it before the error returns.
func (*NetlinkVPNController) RemoveTunnelInterface ¶
func (c *NetlinkVPNController) RemoveTunnelInterface(name string) error
RemoveTunnelInterface deletes the named tunnel link, whatever its kind. It is idempotent: removing a non-existent interface returns nil.
func (*NetlinkVPNController) RemoveTunnelInterfaces ¶ added in v0.36.0
func (c *NetlinkVPNController) RemoveTunnelInterfaces(prefixes []string) error
RemoveTunnelInterfaces deletes every link of type wireguard, xfrm or tuntap whose name starts with one of prefixes. An empty list and an empty prefix are refused before any link is listed: an empty prefix would match the mesh interface and every user access interface. A link of another type is kept, whatever its name starts with. removeLinks says how a link that is already gone and an interrupted link dump count.
func (*NetlinkVPNController) RemoveTunnelPeer ¶
func (c *NetlinkVPNController) RemoveTunnelPeer(iface, publicKey string) error
RemoveTunnelPeer removes a peer from the tunnel interface by public key.
func (*NetlinkVPNController) TunnelPeerHandshake ¶ added in v0.36.0
func (c *NetlinkVPNController) TunnelPeerHandshake(iface, publicKey string) (time.Time, error)
TunnelPeerHandshake reads the tunnel interface through wgctrl and returns the latest handshake of the peer with the given public key. wgctrl gives a zero LastHandshakeTime for a peer that never completed a handshake, which passes through unchanged, and a peer the device does not hold gives the zero time as well. The key is checked before the device is read.
type OpenVPNProvider ¶
type OpenVPNProvider struct {
// contains filtered or unexported fields
}
OpenVPNProvider runs the OpenVPN side of openvpn site-to-site tunnels. Each tunnel is a point-to-point connection with a static key on the persistent tun device the SiteToSiteManager created, served by an openvpn process of its own with a management socket the provider reads the tunnel's state from. The remote site sets the same cipher and digest, AES-256-CBC and SHA256, and the same static key without a direction.
All methods are safe for concurrent use.
func NewOpenVPNProvider ¶
func NewOpenVPNProvider(exec CommandExecutor, configDir string, logger *slog.Logger) *OpenVPNProvider
NewOpenVPNProvider returns an OpenVPNProvider that keeps the files of its tunnels in configDir and starts openvpn through exec.
func (*OpenVPNProvider) CreateTunnel ¶
func (p *OpenVPNProvider) CreateTunnel(ctx context.Context, cfg TunnelConfig) error
CreateTunnel writes the tunnel's static key to plexd-openvpn-<id>.key and its configuration to plexd-openvpn-<id>.conf, both with mode 0600, in configDir, which it creates with mode 0700, and starts openvpn --config <that file> under ctx, which the process ends with. A Key without the lines that frame an OpenVPN static key is refused before anything is written, and a failed start removes both files.
func (*OpenVPNProvider) Established ¶ added in v0.36.0
Established asks the tunnel's openvpn process for its state over the management socket: it dials the socket, writes "state", reads the reply to the line END, and reports whether the second comma-separated field of the last state line is CONNECTED. The read is bounded by 2 s and by ctx.
func (*OpenVPNProvider) Name ¶
func (p *OpenVPNProvider) Name() string
Name returns the kind the provider serves.
func (*OpenVPNProvider) RemoveTunnel ¶
func (p *OpenVPNProvider) RemoveTunnel(_ context.Context, tunnelID string) error
RemoveTunnel stops the tunnel's openvpn process and removes its three files: the configuration, the key and the management socket. Idempotent: a tunnel without a process or files returns nil.
func (*OpenVPNProvider) Reset ¶ added in v0.36.0
func (p *OpenVPNProvider) Reset(_ context.Context) error
Reset removes every plexd-openvpn-* file of configDir. A configDir that does not exist is no error. A process of an earlier plexd is not this provider's to stop: it ends with the unit's control group, and its tun device is deleted with the tunnel links.
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 SecretValueFetcher ¶ added in v0.36.0
type SecretValueFetcher interface {
FetchSecretValue(ctx context.Context, name string, version int) ([]byte, error)
}
SecretValueFetcher reads the value of one version of a Secret the node may read: the key a vendor user access provider joins its network with.
type SiteToSiteDeps ¶ added in v0.36.0
type SiteToSiteDeps struct {
// VPN creates and removes the link of each tunnel: the WireGuard
// interface of a wireguard tunnel, the xfrm interface of an ipsec tunnel
// and the tun device of an openvpn tunnel.
VPN VPNController
// Routes switches forwarding on between a tunnel's link and the mesh
// interface and routes the tunnel's allowed_subnets into the link. The
// manager never switches forwarding off: a tunnel's link is deleted with
// the tunnel, and the mesh interface's forwarding belongs to the bridge
// manager.
Routes RouteController
// Rewriter rewrites the source of what a tunnel forwards into the mesh to
// the bridge's mesh address. nil: this platform serves no tunnel; one
// that passes its checks reads kind_not_served, one that fails them
// invalid_tunnel.
Rewriter MeshSourceRewriter
// Keys keeps the private key of each wireguard tunnel's interface. It
// must not be nil.
Keys *InterfaceKeyStore
// Secrets fetches the key a tunnel's Secret holds. It must not be nil
// while a tunnel names a Secret the inventory lists.
Secrets SecretValueFetcher
// Providers holds the provider of each kind other than wireguard this
// plexd serves, by kind: ipsec and openvpn. A kind without a provider
// reads kind_not_served.
Providers map[string]TunnelProvider
// Resolve resolves a remote_host that is no IP address. nil resolves
// with net.DefaultResolver.LookupNetIP(ctx, "ip", host).
Resolve func(ctx context.Context, host string) ([]netip.Addr, error)
// MeshInterface is the name of the mesh interface.
MeshInterface string
// MeshCIDR is the Domain mesh prefix: the local traffic selector of an
// ipsec tunnel, and the prefix no allowed subnet may overlap. Empty when
// the node has none, which leaves an ipsec tunnel down with
// setup_failed.
MeshCIDR string
Logger *slog.Logger
}
SiteToSiteDeps are what a SiteToSiteManager serves tunnels with.
type SiteToSiteManager ¶
type SiteToSiteManager struct {
// contains filtered or unexported fields
}
SiteToSiteManager serves the site-to-site tunnels of the state pull's bridge.site_to_site block: for each a link of its kind, a WireGuard interface with a kept key and the remote site as its peer, an xfrm interface that strongSwan binds an IKE connection to, or a tun device an openvpn process runs on. Each link forwards into the mesh with its source rewritten to the bridge's mesh address, and the tunnel's allowed_subnets are routed into it. Each tunnel is served on its own, so one that is down leaves the others up. SiteToSiteManager is concurrent-safe via mu.
Apply, SyncSecretInventory and Retry are called from the reconciler's goroutine alone. They resolve a tunnel's remote host and fetch its Secret outside mu, so Teardown and the status readers do not wait for either. The status readers, TunnelReports and SiteToSiteStatus, read whether a remote site answers outside mu as well, so neither the reconciler nor Teardown waits for a device read or a provider's command.
func NewSiteToSiteManager ¶
func NewSiteToSiteManager(deps SiteToSiteDeps) *SiteToSiteManager
NewSiteToSiteManager creates a SiteToSiteManager. It serves nothing until Setup.
func (*SiteToSiteManager) Apply ¶ added in v0.36.0
func (m *SiteToSiteManager) Apply(ctx context.Context, block api.SiteToSiteConfig)
Apply serves the block whole. It does nothing while the manager is not active.
- The key files of every tunnel the block lists are kept, whatever Enabled says, and every other key file is deleted; the zero block deletes them all.
- A block with Enabled false serves no tunnel.
- A held tunnel the block does not serve is torn down.
- A held tunnel whose entry is unchanged is kept: the same kind, remote_host, remote_port, allowed_subnets in order, listen_port, remote_public_key and auth_secret_name, and the same verdict of its checks. A changed slug is taken over in place. Any other change tears the tunnel down and brings it up again, a wireguard tunnel with its kept key.
- A new tunnel is brought up, in block order.
A tunnel that cannot be brought up is down with its reason, and Retry tries again when the reason allows it. Apply signals ReportChanged when it returns, after every attempt it started.
func (*SiteToSiteManager) ReportChanged ¶ added in v0.36.0
func (m *SiteToSiteManager) ReportChanged() <-chan struct{}
ReportChanged returns the channel the manager signals, without blocking, when what TunnelReports returns may have changed: at the end of every Apply, every Retry, and so every SyncSecretInventory, and Teardown. Several signals before the reader wakes collapse into one. The signals are liberal; the reader compares before it acts. A change of whether a remote site answers signals nothing.
func (*SiteToSiteManager) Retry ¶ added in v0.36.0
func (m *SiteToSiteManager) Retry(ctx context.Context)
Retry brings up again every tunnel that is down for bind_failed, setup_failed, key_unavailable, auth_secret_not_listed, auth_secret_unreadable, client_missing or remote_host_unresolved and whose next attempt is due on the manager's clock. The delay after a failed attempt is 5 s, doubling per consecutive failure to 60 s, or the Retry-After of an API error when that is longer. invalid_tunnel and kind_not_served are not retried until the entry changes. It does nothing while the manager is not active. It signals ReportChanged when it returns.
func (*SiteToSiteManager) Setup ¶
func (m *SiteToSiteManager) Setup() error
Setup removes what a process that was killed left behind, with CleanupSiteToSite, so that a tunnel's link can be created again under its name, creates the context the openvpn processes run under, and marks the manager active. A failed cleanup fails Setup and leaves the manager inactive.
func (*SiteToSiteManager) SiteToSiteStatus ¶
func (m *SiteToSiteManager) SiteToSiteStatus() *api.SiteToSiteInfo
SiteToSiteStatus returns the site-to-site status for the node API's status.site-to-site report: the Enabled of the last applied block and one entry per tunnel TunnelReports reports, in block order, with its health, the reason of a tunnel that is down, and the link of one that is up and whether its remote site answers, read as TunnelReports reads it. It returns nil while the manager is not active.
func (*SiteToSiteManager) SyncSecretInventory ¶ added in v0.36.0
func (m *SiteToSiteManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
SyncSecretInventory replaces the secret inventory the tunnels take their Secret's version from, rebuilds every tunnel that is up and whose Secret the inventory lists at another version than the one it was built with, and then calls Retry. A tunnel whose Secret the inventory no longer lists keeps running with the key it has. It does nothing while the manager is not active.
func (*SiteToSiteManager) Teardown ¶
func (m *SiteToSiteManager) Teardown() error
Teardown removes every tunnel: the provider's side of it, its routes, its source rewrite and its link. It cancels the context the openvpn processes run under and marks the manager inactive. It keeps the key files, so a wireguard tunnel comes back with its key after a restart. Errors are joined; the cleanup continues past a failure. Idempotent: calling Teardown when inactive returns nil. It signals ReportChanged when it returns.
func (*SiteToSiteManager) TunnelReports ¶ added in v0.36.0
func (m *SiteToSiteManager) TunnelReports() []SiteToSiteTunnelReport
TunnelReports returns one report per tunnel of the last applied block with a valid id no earlier entry carried, in block order, and nil while the manager is not active. A tunnel whose first attempt has no outcome yet, because its remote host is resolved or its Secret fetched outside mu, is left out until it has one.
A tunnel that is down reports its reason. A tunnel that is up reports whether its remote site answers, read outside mu with one device read or one provider command: for a wireguard tunnel its latest handshake with the remote peer is at most 180 s old on the manager's clock, and it reports the public key of its interface; for an ipsec or openvpn tunnel the provider's Established says so within 5 s. A failed read counts false.
type SiteToSiteStatusClient ¶ added in v0.36.0
type SiteToSiteStatusClient interface {
ReportSiteToSiteStatus(ctx context.Context, nodeID string, req api.SiteToSiteStatusRequest) (*api.SiteToSiteStatusResponse, error)
}
SiteToSiteStatusClient sends site-to-site status reports. *api.ControlPlane satisfies it.
type SiteToSiteStatusReporter ¶ added in v0.36.0
type SiteToSiteStatusReporter struct {
// contains filtered or unexported fields
}
SiteToSiteStatusReporter sends to PUT /v1/nodes/{node_id}/site-to-site-status whether the bridge's local configuration serves site-to-site tunnels, enabled or opted_out when bridge.site_to_site_enabled is false, and on an enabled bridge one entry per tunnel as the site-to-site manager reports it: whether it is up, why not, whether its remote site answers, and for a wireguard tunnel that is up the public key of its interface. 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 tunnel creates and updates on a bridge whose report reads opted_out; each report replaces the tunnel 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. 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 in an id, a health, a reason, a public key or established, and at most once per siteToSiteStatusChangeGap; a change inside the gap is sent when the gap ends, with the entries as they are then. established follows whether the remote site answers, and the manager raises no signal when it alone moves: the next signal, or the next tick, finds it changed and sends it, at most one interval late. An on-change send restarts the interval, as the ingress status reporter's does.
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 serves no tunnel 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 tunnel entries age 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 site-to-site manager; nothing it learns reaches the manager or the reconcile handlers.
func NewSiteToSiteStatusReporter ¶ added in v0.36.0
func NewSiteToSiteStatusReporter(interval time.Duration, nodeID string, client SiteToSiteStatusClient, optedOut bool, tunnels SiteToSiteTunnelReportSource, logger *slog.Logger) *SiteToSiteStatusReporter
NewSiteToSiteStatusReporter creates a SiteToSiteStatusReporter 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 tunnel entries tunnels reports. tunnels is nil on an opted-out bridge; a caller passes an untyped nil, since a nil *SiteToSiteManager 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 (*SiteToSiteStatusReporter) Run ¶ added in v0.36.0
func (r *SiteToSiteStatusReporter) Run(ctx context.Context) error
Run sends the report at once, on every change of the tunnel entries, bounded by siteToSiteStatusChangeGap, 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 SiteToSiteTunnelReport ¶ added in v0.36.0
type SiteToSiteTunnelReport struct {
TunnelID string
Kind string // the tunnel's kind as pulled, one of api.SiteToSiteKind* or one this plexd does not know
Health string // api.SiteToSiteHealth*
Reason string // a SiteToSiteReason* while Health is down; empty while it is up
// PublicKey is the public half of a wireguard tunnel's interface key, in
// standard base64, while the tunnel is up; empty otherwise.
PublicKey string
// Established tells whether the remote site answers while the tunnel is
// up: for a wireguard tunnel its latest handshake with the remote peer
// is at most 180 s old, for an ipsec or openvpn tunnel the provider says
// so. It is false while the tunnel is down.
Established bool
}
SiteToSiteTunnelReport is what the bridge says about one site-to-site tunnel in a site-to-site status report. It carries no slug, interface or error text: those stay in the bridge's log and its local status.
type SiteToSiteTunnelReportSource ¶ added in v0.36.0
type SiteToSiteTunnelReportSource interface {
TunnelReports() []SiteToSiteTunnelReport
ReportChanged() <-chan struct{}
}
SiteToSiteTunnelReportSource is the part of *SiteToSiteManager the reporter reads.
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. The process is waited for as soon as it exits, whether it ends by itself, through Stop or with ctx, so it leaves no zombie behind and the goroutine os/exec watches ctx with ends with 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.
func (*StdIngressController) Close ¶
func (c *StdIngressController) Close(listener net.Listener) error
Close closes the given listener.
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 ¶
Start launches tailscaled and joins the Tailscale network with the auth key, advertising meshCIDR as a route so the tailnet reaches the mesh through the bridge. tailscaled runs under ctx, which ends it; tailscale up and tailscale status run under a timeout of vendorJoinTimeout derived from ctx. The key is passed on tailscale's command line and never logged.
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 tunnel's id, lower case. It names the provider's files
// and its strongSwan connection.
TunnelID string
// InterfaceName is the link the manager created for the tunnel: the
// xfrm interface of an ipsec tunnel, the tun device of an openvpn one.
InterfaceName string
// InterfaceID is the id of an ipsec tunnel's xfrm interface, which
// strongSwan binds the connection to; 0 for openvpn.
InterfaceID uint32
// RemoteHost is the remote site's host name or IP address, as the pull
// carries it; the daemon resolves a name itself.
RemoteHost string
// RemotePort is the remote site's port.
RemotePort int
// LocalSubnets are the networks on the bridge's side of the tunnel: the
// Domain mesh CIDR.
LocalSubnets []string
// RemoteSubnets are the networks behind the remote site, the tunnel's
// allowed_subnets.
RemoteSubnets []string
// Key is the value of the tunnel's Secret, trimmed of surrounding white
// space: an IKE pre-shared key or an OpenVPN static key. It is never
// logged.
Key string
}
TunnelConfig is what a TunnelProvider needs to run the daemon's side of one site-to-site tunnel of the ipsec or openvpn kind. The SiteToSiteManager builds it from the tunnel's entry and owns everything else: the link, the routes, forwarding and the mesh source rewrite. Every member a provider writes into a file passes ValidateTunnelConfig first.
type TunnelProvider ¶
type TunnelProvider interface {
// Name returns the kind the provider serves: "ipsec" or "openvpn".
Name() string
// CreateTunnel brings up the daemon's side of the tunnel cfg describes.
// A failure leaves no file of the tunnel behind. A daemon the provider
// starts runs under ctx and ends with it.
CreateTunnel(ctx context.Context, cfg TunnelConfig) error
// RemoveTunnel tears down the tunnel with the given id and removes its
// files. Idempotent: a tunnel the provider holds no file of returns nil.
RemoveTunnel(ctx context.Context, tunnelID string) error
// Established reports whether the remote site of the tunnel answers: for
// ipsec the IKE and child security associations stand, for openvpn the
// peer is connected. A failed read returns the error.
Established(ctx context.Context, tunnelID string) (bool, error)
// Reset removes the files of every tunnel of the provider, also those a
// process that was killed left behind; the ipsec provider also unloads
// their connections from strongSwan. A provider without any file
// returns nil.
Reset(ctx context.Context) error
}
TunnelProvider runs the daemon's side of the site-to-site tunnels of one kind, ipsec or openvpn, each on a link the SiteToSiteManager created before. The manager owns the link, the routes, forwarding and the mesh source rewrite for every kind; a provider writes the daemon's files and runs its commands.
Every command a provider runs gets the caller's context, and an error from the executor stays wrapped, so a missing binary stays visible to errors.Is(err, exec.ErrNotFound). All methods are safe for concurrent use.
type UserAccessClient ¶ added in v0.36.0
type UserAccessClient interface {
// Name returns the client identifier (e.g. "tailscale", "netbird").
Name() string
// Start joins the vendor network with key, the vendor's auth key or setup
// key. An empty key is refused before any command runs. The key travels
// on the vendor CLI's command line and is never logged. meshCIDR is the
// mesh prefix a client advertises as a route, where its vendor lets a
// client advertise one; a client whose vendor defines routes elsewhere
// ignores it. A daemon the client starts runs under ctx and ends with
// it; the join commands run under a timeout of vendorJoinTimeout derived
// from ctx. An error from the executor stays wrapped, so
// errors.Is(err, exec.ErrNotFound) reports a missing binary.
Start(ctx context.Context, key string, meshCIDR string) 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
}
UserAccessClient abstracts lifecycle management of the vendor clients (Tailscale, Netbird) that serve user access into the mesh via a bridge node. A client is the local program behind a user access provider of the control plane, and is named apart from it.
Implementations invoke the vendor's CLI or daemon to join an overlay network, then report status so the bridge can route traffic between the client's interface and the mesh.
All methods must be safe for concurrent use.
type UserAccessDeps ¶ added in v0.36.0
type UserAccessDeps struct {
// Access creates and removes the interfaces of wireguard providers.
Access AccessController
// Routes switches forwarding on between a provider's interface and the
// mesh interface. The manager never switches it off: a provider's
// interface is deleted with the provider, and the mesh interface's
// forwarding belongs to the bridge manager.
Routes RouteController
// Rewriter rewrites the source of device traffic to the bridge's mesh
// address. nil: this platform serves no provider; one that passes its
// checks reads kind_not_served, one that fails them invalid_provider.
Rewriter MeshSourceRewriter
// Keys keeps the private key of each wireguard provider's interface. It
// must not be nil.
Keys *InterfaceKeyStore
// Secrets fetches a vendor provider's join key. It must not be nil while
// Clients holds a client.
Secrets SecretValueFetcher
// Clients holds the vendor client of each vendor kind this plexd serves,
// by kind. A kind without a client reads kind_not_served.
Clients map[string]UserAccessClient
// MeshInterface is the name of the mesh interface.
MeshInterface string
// MeshCIDR is the Domain mesh prefix a tailscale provider advertises as
// a route; empty when the node has none, which leaves a tailscale
// provider down with setup_failed.
MeshCIDR string
Logger *slog.Logger
}
UserAccessDeps are what a UserAccessManager serves providers with.
type UserAccessManager ¶
type UserAccessManager struct {
// contains filtered or unexported fields
}
UserAccessManager serves the user access providers of the state pull's bridge.user_access block: a WireGuard interface for each wireguard provider, and a joined vendor client for each tailscale or netbird provider, each forwarding into the mesh with its source rewritten to the bridge's mesh address. Each provider is served on its own, so one that is down leaves the others up. UserAccessManager is concurrent-safe via mu.
Apply, SyncSecretInventory and Retry are called from the reconciler's goroutine alone. They fetch a Secret and start a vendor client outside mu, so Teardown and the status readers do not wait for a join.
func NewUserAccessManager ¶
func NewUserAccessManager(deps UserAccessDeps) *UserAccessManager
NewUserAccessManager creates a UserAccessManager. It serves nothing until Setup.
func (*UserAccessManager) Apply ¶ added in v0.36.0
func (m *UserAccessManager) Apply(ctx context.Context, block api.UserAccessConfig)
Apply serves the block whole. It does nothing while the manager is not active.
- The key files of every provider the block lists are kept, whatever Enabled says, and every other key file is deleted; the zero block deletes them all.
- A block with Enabled false serves no provider.
- A held provider the block does not serve is torn down.
- A held provider whose entry is unchanged is kept: a wireguard provider unchanged in its listen_port and address_pool, a vendor provider unchanged in its auth_secret_name. The devices of a running wireguard interface are brought in line with the entry by public key. Any other change tears the provider down and brings it up again, with its kept key.
- A new provider is brought up, in block order.
A provider that cannot be brought up is down with its reason, and Retry tries again when the reason allows it. Apply signals ReportChanged when it returns, after every join it started.
func (*UserAccessManager) ProviderReports ¶ added in v0.36.0
func (m *UserAccessManager) ProviderReports() []UserAccessProviderReport
ProviderReports returns one report per provider of the last applied block with a valid id no earlier entry carried, in block order, and nil while the manager is not active. A provider whose first attempt has no outcome yet, a vendor provider joining for the first time, is left out until it has one.
A provider that is down reports its reason. A wireguard provider that is up reports the public key of its interface and how many of the devices configured on it completed a handshake at most 180 s ago on the manager's clock, read with one PeerHandshakes call per such provider; a failed read counts none.
func (*UserAccessManager) ReportChanged ¶ added in v0.36.0
func (m *UserAccessManager) ReportChanged() <-chan struct{}
ReportChanged returns the channel the manager signals, without blocking, when what ProviderReports returns may have changed: at the end of every Apply, every Retry, and so every SyncSecretInventory, and Teardown. Several signals before the reader wakes collapse into one. The signals are liberal; the reader compares before it acts. A change of connected devices alone signals nothing.
func (*UserAccessManager) Retry ¶ added in v0.36.0
func (m *UserAccessManager) Retry(ctx context.Context)
Retry brings up again every provider that is down for bind_failed, setup_failed, key_unavailable, auth_secret_not_listed, auth_secret_unreadable, join_failed or client_missing and whose next attempt is due on the manager's clock. The delay after a failed attempt is 5 s, doubling per consecutive failure to 60 s, or the Retry-After of an API error when that is longer. invalid_provider and kind_not_served are not retried until the entry changes. It does nothing while the manager is not active. It signals ReportChanged when it returns.
func (*UserAccessManager) Setup ¶
func (m *UserAccessManager) Setup() error
Setup removes what a process that was killed left behind, with CleanupUserAccess, so that a provider's interface can be created again under its name, creates the context the vendor clients run under, and marks the manager active. A failed cleanup fails Setup and leaves the manager inactive.
func (*UserAccessManager) SyncSecretInventory ¶ added in v0.36.0
func (m *UserAccessManager) SyncSecretInventory(ctx context.Context, inventory []api.NodeStateSecret)
SyncSecretInventory replaces the secret inventory the vendor providers take their Secret's version from, then calls Retry. A provider that is up keeps its join when the inventory lists a new version of its Secret or none; the version the inventory lists is used at the next join. It does nothing while the manager is not active.
func (*UserAccessManager) Teardown ¶
func (m *UserAccessManager) Teardown() error
Teardown stops every vendor client, removes every source rewrite and every interface, cancels the context the clients run under and marks the manager inactive. It keeps the key files, so a provider comes back with its key after a restart. Errors are joined; the cleanup continues past a failure. Idempotent: calling Teardown when inactive returns nil. It signals ReportChanged when it returns.
func (*UserAccessManager) UserAccessStatus ¶
func (m *UserAccessManager) UserAccessStatus() *api.UserAccessInfo
UserAccessStatus returns the user access status for the node API's status.user-access report: the Enabled of the last applied block and one entry per provider the manager holds, in block order, with the count of connected devices ProviderReports reports. It returns nil while the manager is not active.
type UserAccessProviderReport ¶ added in v0.36.0
type UserAccessProviderReport struct {
ProviderID string
Kind string // the provider's kind as pulled, one of api.UserAccessKind* or one this plexd does not know
Health string // api.UserAccessHealth*
Reason string // a UserAccessReason* while Health is down; empty while it is up
// PublicKey is the public half of a wireguard provider's interface key,
// in standard base64, while the provider is up; empty otherwise.
PublicKey string
// ConnectedDevices counts a wireguard provider's devices whose latest
// handshake is at most 180 s old, while the provider is up; 0 otherwise.
ConnectedDevices int
}
UserAccessProviderReport is what the bridge says about one user access provider in a user access status report. It carries no slug, interface or error text: those stay in the bridge's log and its local status.
type UserAccessProviderReportSource ¶ added in v0.36.0
type UserAccessProviderReportSource interface {
ProviderReports() []UserAccessProviderReport
ReportChanged() <-chan struct{}
}
UserAccessProviderReportSource is the part of *UserAccessManager the reporter reads.
type UserAccessStatusClient ¶ added in v0.36.0
type UserAccessStatusClient interface {
ReportUserAccessStatus(ctx context.Context, nodeID string, req api.UserAccessStatusRequest) (*api.UserAccessStatusResponse, error)
}
UserAccessStatusClient sends user access status reports. *api.ControlPlane satisfies it.
type UserAccessStatusReporter ¶ added in v0.36.0
type UserAccessStatusReporter struct {
// contains filtered or unexported fields
}
UserAccessStatusReporter sends to PUT /v1/nodes/{node_id}/user-access-status whether the bridge's local configuration serves user access, enabled or opted_out when bridge.user_access_enabled is false, and on an enabled bridge one entry per user access provider as the user access manager reports it: whether it is up, why not, and for a wireguard provider that is up the public key of its interface and how many devices reach it. 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 provider writes and device admissions on a bridge whose report reads opted_out; each report replaces the provider 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. 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 in an id, a health, a reason or a public key, and at most once per userAccessStatusChangeGap; a change inside the gap is sent when the gap ends, with the entries as they are then. connected_devices follows the devices' handshakes, so it is left out of the comparison, as the contract asks: a moving count alone sends nothing, and the tick carries it. An on-change send restarts the interval, as the ingress status reporter's does.
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 serves no provider 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 provider 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 user access manager; nothing it learns reaches the manager or the reconcile handler.
func NewUserAccessStatusReporter ¶ added in v0.36.0
func NewUserAccessStatusReporter(interval time.Duration, nodeID string, client UserAccessStatusClient, optedOut bool, providers UserAccessProviderReportSource, logger *slog.Logger) *UserAccessStatusReporter
NewUserAccessStatusReporter creates a UserAccessStatusReporter 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 provider entries providers reports. providers is nil on an opted-out bridge; a caller passes an untyped nil, since a nil *UserAccessManager 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 (*UserAccessStatusReporter) Run ¶ added in v0.36.0
func (r *UserAccessStatusReporter) Run(ctx context.Context) error
Run sends the report at once, on every change of the provider entries, bounded by userAccessStatusChangeGap, 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 VPNController ¶
type VPNController interface {
// CreateTunnelInterface creates a WireGuard interface for a site-to-site
// tunnel with the given name, configures privateKey (32 raw bytes) and
// listenPort (the UDP port) on it and brings it up. The caller owns the
// key, so an interface created again under the same key keeps its public
// key.
//
// A failure after the interface exists removes it again. A listen port
// another socket holds fails with an error wrapping ErrListenPortInUse
// where the implementation can tell; NetlinkVPNController does.
//
// 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, privateKey []byte, listenPort int) error
// CreateXfrmInterface creates the xfrm interface of an ipsec tunnel with
// the given name and the interface id ifID, which strongSwan binds the
// connection to, and brings it up. ifID 0 is refused, since it binds
// nothing. A failure after the interface exists removes it again.
//
// Not idempotent: a name that already exists fails with an error wrapping
// os.ErrExist on Linux. A platform without xfrm interfaces fails with an
// error wrapping errors.ErrUnsupported.
CreateXfrmInterface(name string, ifID uint32) error
// CreateTunInterface creates the persistent tun device of an openvpn
// tunnel with the given name, without packet information and without an
// address, and brings it up. A failure after the device exists removes it
// again.
//
// Not idempotent: a name that a link of another kind holds fails. On
// Linux a tun device that already carries the name and that no process
// holds open is taken over rather than refused, as the kernel attaches
// to it. A platform without persistent tun devices fails with an error
// wrapping errors.ErrUnsupported.
CreateTunInterface(name string) error
// RemoveTunnelInterface removes the tunnel link with the given name,
// whatever its kind.
// Idempotent: removing a non-existent interface returns nil.
RemoveTunnelInterface(name string) error
// RemoveTunnelInterfaces removes every site-to-site link whose name
// starts with one of prefixes, which is how a start clears the links a
// killed process left behind. An empty list and an empty prefix are
// refused, since either would match links plexd does not own.
// Idempotent: with no such link it returns nil.
RemoveTunnelInterfaces(prefixes []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
// TunnelPeerHandshake returns the time of the latest handshake of the
// peer with the given public key (standard base64) on the given tunnel
// interface. A peer that never completed a handshake, and a peer the
// interface does not hold, give the zero time and no error.
TunnelPeerHandshake(iface string, publicKey string) (time.Time, error)
}
VPNController abstracts the OS-level links of site-to-site tunnels for testability: the WireGuard interface of a wireguard tunnel, the xfrm interface of an ipsec tunnel and the tun device of an openvpn tunnel. Every method except the three Create methods 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 carries the private key and the address its caller passes.
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, RemoveInterfaces 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.
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, privateKey []byte, listenPort int, address string) error
CreateInterface creates a WireGuard interface for user access with the given private key and listen port, and assigns address when it is not empty.
func (*WGAccessController) PeerHandshakes ¶ added in v0.36.0
PeerHandshakes reads the access interface through the wrapped controller's wireguard.PeerStatsReader and returns the latest handshake of every peer, keyed by its public key in standard base64. A controller that cannot read peer stats fails with an error wrapping wireguard.ErrPeerStatsUnsupported.
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) RemoveInterfaces ¶ added in v0.36.0
func (c *WGAccessController) RemoveInterfaces(string) error
RemoveInterfaces returns nil without touching anything. A userspace device lives in the process that created it and ends with it, so a killed process leaves no interface behind for a start to clear.
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 carries the private key its caller passes. It creates WireGuard interfaces only: the xfrm interface and the tun device the other tunnel kinds need exist on Linux alone.
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, RemoveTunnelInterfaces 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) CreateTunInterface ¶ added in v0.36.0
func (c *WGVPNController) CreateTunInterface(name string) error
CreateTunInterface creates nothing and returns an error wrapping errors.ErrUnsupported: the persistent tun device an openvpn tunnel runs on is a Linux kernel feature, so such a tunnel has no link on macOS and Windows.
func (*WGVPNController) CreateTunnelInterface ¶ added in v0.8.0
func (c *WGVPNController) CreateTunnelInterface(name string, privateKey []byte, listenPort int) error
CreateTunnelInterface creates a WireGuard interface for a site-to-site tunnel with the given private key and listen port, carrying the address the controller was built with. The key is checked before anything is created.
func (*WGVPNController) CreateXfrmInterface ¶ added in v0.36.0
func (c *WGVPNController) CreateXfrmInterface(name string, _ uint32) error
CreateXfrmInterface creates nothing and returns an error wrapping errors.ErrUnsupported: xfrm interfaces are a Linux kernel feature, so an ipsec tunnel has no link on macOS and Windows.
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) RemoveTunnelInterfaces ¶ added in v0.36.0
func (c *WGVPNController) RemoveTunnelInterfaces([]string) error
RemoveTunnelInterfaces returns nil without touching anything. A userspace device lives in the process that created it and ends with it, so a killed process leaves no interface behind for a start to clear.
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.
func (*WGVPNController) TunnelPeerHandshake ¶ added in v0.36.0
func (c *WGVPNController) TunnelPeerHandshake(iface, publicKey string) (time.Time, error)
TunnelPeerHandshake reads the tunnel interface through the wrapped controller's wireguard.PeerStatsReader and returns the latest handshake of the peer with the given public key: the zero time for a peer that never completed one and for a peer the device does not hold. The key is checked before the device is read. A controller that cannot read peer stats fails with an error wrapping wireguard.ErrPeerStatsUnsupported.
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_http.go
- ingress_plan.go
- ingress_report.go
- ingress_status.go
- ingress_udp.go
- ipsec.go
- keystore.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
- site_to_site_status.go
- sni.go
- tailscale.go
- tunnel_provider.go
- user_access.go
- user_access_provider.go
- user_access_status.go
- vpn_controller.go
- vpn_controller_linux.go
- vpn_controller_wg.go
- wg_controller.go