mirror of
https://github.com/netbirdio/netbird.git
synced 2026-09-15 03:09:06 +02:00
Merge branch 'main' into file-share
# Conflicts: # client/ios/NetBirdSDK/client.go
This commit is contained in:
@@ -368,6 +368,7 @@ func (a *Auth) setSystemInfoFlags(info *system.Info) {
|
||||
a.config.EnableSSHLocalPortForwarding,
|
||||
a.config.EnableSSHRemotePortForwarding,
|
||||
a.config.DisableSSHAuth,
|
||||
a.config.RemoteJobsAllowed,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -304,6 +304,16 @@ func (d *DeviceAuthorizationFlow) WaitToken(ctx context.Context, info AuthFlowIn
|
||||
return TokenInfo{}, fmt.Errorf("validate access token failed with error: %v", err)
|
||||
}
|
||||
|
||||
// Same as the PKCE flow: the account the token belongs to is what
|
||||
// callers store to send back as the login_hint. Without it a client
|
||||
// driven through the device flow — Android TV and tvOS — never binds
|
||||
// an account to its profile and every later login goes out blind.
|
||||
if email, err := parseEmailFromIDToken(tokenInfo.IDToken); err != nil {
|
||||
log.Warnf("failed to parse email from ID token: %v", err)
|
||||
} else {
|
||||
tokenInfo.Email = email
|
||||
}
|
||||
|
||||
log.Infof("device flow: user authorization confirmed after %d polls in %s", polls, time.Since(start).Round(time.Second))
|
||||
return tokenInfo, err
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ func (c *ConnectClient) run(mobileDependency MobileDependency, runningChan chan
|
||||
wrapErr := state.Wrap
|
||||
myPrivateKey, err := wgtypes.ParseKey(c.config.PrivateKey)
|
||||
if err != nil {
|
||||
log.Errorf("failed parsing Wireguard key %s: [%s]", c.config.PrivateKey, err.Error())
|
||||
log.Errorf("failed parsing Wireguard key: %s", err)
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
@@ -661,6 +661,7 @@ func createEngineConfig(key wgtypes.Key, config *profilemanager.Config, peerConf
|
||||
RosenpassEnabled: config.RosenpassEnabled,
|
||||
RosenpassPermissive: config.RosenpassPermissive,
|
||||
ServerSSHAllowed: util.ReturnBoolWithDefaultTrue(config.ServerSSHAllowed),
|
||||
RemoteJobsAllowed: util.ReturnBoolWithDefaultFalse(config.RemoteJobsAllowed),
|
||||
EnableSSHRoot: config.EnableSSHRoot,
|
||||
EnableSSHSFTP: config.EnableSSHSFTP,
|
||||
EnableSSHLocalPortForwarding: config.EnableSSHLocalPortForwarding,
|
||||
@@ -758,6 +759,7 @@ func loginToManagement(ctx context.Context, client mgm.Client, pubSSHKey []byte,
|
||||
config.EnableSSHLocalPortForwarding,
|
||||
config.EnableSSHRemotePortForwarding,
|
||||
config.DisableSSHAuth,
|
||||
config.RemoteJobsAllowed,
|
||||
)
|
||||
return client.Login(sysInfo, pubSSHKey, config.DNSLabels)
|
||||
}
|
||||
|
||||
@@ -711,6 +711,9 @@ func (g *BundleGenerator) addCommonConfigFields(configContent *strings.Builder)
|
||||
if g.internalConfig.ServerSSHAllowed != nil {
|
||||
configContent.WriteString(fmt.Sprintf("ServerSSHAllowed: %v\n", *g.internalConfig.ServerSSHAllowed))
|
||||
}
|
||||
if g.internalConfig.RemoteJobsAllowed != nil {
|
||||
configContent.WriteString(fmt.Sprintf("RemoteJobsAllowed: %v\n", *g.internalConfig.RemoteJobsAllowed))
|
||||
}
|
||||
if g.internalConfig.EnableSSHRoot != nil {
|
||||
configContent.WriteString(fmt.Sprintf("EnableSSHRoot: %v\n", *g.internalConfig.EnableSSHRoot))
|
||||
}
|
||||
@@ -737,6 +740,8 @@ func (g *BundleGenerator) addCommonConfigFields(configContent *strings.Builder)
|
||||
configContent.WriteString(fmt.Sprintf("BlockLANAccess: %v\n", g.internalConfig.BlockLANAccess))
|
||||
configContent.WriteString(fmt.Sprintf("BlockInbound: %v\n", g.internalConfig.BlockInbound))
|
||||
configContent.WriteString(fmt.Sprintf("DisableIPv6: %v\n", g.internalConfig.DisableIPv6))
|
||||
configContent.WriteString(fmt.Sprintf("LocalMetricsEnabled: %v\n", g.internalConfig.LocalMetricsEnabled))
|
||||
configContent.WriteString(fmt.Sprintf("LocalMetricsAddress: %s\n", g.internalConfig.LocalMetricsAddress))
|
||||
configContent.WriteString(fmt.Sprintf("SyncMessageVersion: %v\n", g.internalConfig.SyncMessageVersion))
|
||||
|
||||
if g.internalConfig.DisableNotifications != nil {
|
||||
|
||||
@@ -839,12 +839,13 @@ COMMIT`
|
||||
// the excluded set with a justification.
|
||||
func TestAddConfig_AllFieldsCovered(t *testing.T) {
|
||||
excluded := map[string]string{
|
||||
"PrivateKey": "sensitive: WireGuard private key",
|
||||
"PreSharedKey": "sensitive: WireGuard pre-shared key",
|
||||
"SSHKey": "sensitive: SSH private key",
|
||||
"ClientCertKeyPair": "non-config: parsed cert pair, not serialized",
|
||||
"Name": "non-config: profile name is not needed for debug purposes",
|
||||
"policy": "non-config: in-memory MDM policy snapshot, surfaced via Config.Policy() / GetConfigResponse.MDMManagedFields",
|
||||
"PrivateKey": "sensitive: WireGuard private key",
|
||||
"PreSharedKey": "sensitive: WireGuard pre-shared key",
|
||||
"SSHKey": "sensitive: SSH private key",
|
||||
"ClientCertKeyPair": "non-config: parsed cert pair, not serialized",
|
||||
"Name": "non-config: profile name is not needed for debug purposes",
|
||||
"policy": "non-config: in-memory MDM policy snapshot, surfaced via Config.Policy() / GetConfigResponse.MDMManagedFields",
|
||||
"DebugBundleUploadURL": "sensitive: MDM-provided upload URL may carry credentials or query tokens; kept out of the shared bundle",
|
||||
}
|
||||
|
||||
mURL, _ := url.Parse("https://api.example.com:443")
|
||||
@@ -864,6 +865,7 @@ func TestAddConfig_AllFieldsCovered(t *testing.T) {
|
||||
RosenpassEnabled: true,
|
||||
RosenpassPermissive: true,
|
||||
ServerSSHAllowed: &bTrue,
|
||||
RemoteJobsAllowed: &bTrue,
|
||||
EnableSSHRoot: &bTrue,
|
||||
EnableSSHSFTP: &bTrue,
|
||||
EnableSSHLocalPortForwarding: &bTrue,
|
||||
@@ -886,6 +888,7 @@ func TestAddConfig_AllFieldsCovered(t *testing.T) {
|
||||
ClientCertPath: "/tmp/cert",
|
||||
ClientCertKeyPath: "/tmp/key",
|
||||
LazyConnection: "on",
|
||||
DebugBundleUploadURL: "https://upload.example.test/bundle?token=secret",
|
||||
MTU: 1280,
|
||||
DisableIPv6: true,
|
||||
SyncMessageVersion: func(v int) *int { return &v }(1),
|
||||
@@ -903,6 +906,13 @@ func TestAddConfig_AllFieldsCovered(t *testing.T) {
|
||||
g.addCommonConfigFields(&sb)
|
||||
rendered := sb.String() + renderAddConfigSpecific(g)
|
||||
|
||||
// DebugBundleUploadURL is an MDM-provided value that can carry
|
||||
// credentials or signed query tokens. It is deliberately excluded
|
||||
// above; assert it never reaches the rendered bundle — neither the
|
||||
// field name nor the token — in either anonymize mode.
|
||||
assert.NotContains(t, rendered, "DebugBundleUploadURL:", "MDM upload URL field must not be serialized into the debug bundle")
|
||||
assert.NotContains(t, rendered, "token=secret", "MDM upload URL value must not leak into the debug bundle")
|
||||
|
||||
val := reflect.ValueOf(cfg).Elem()
|
||||
typ := val.Type()
|
||||
var missing []string
|
||||
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
@@ -34,10 +36,16 @@ var (
|
||||
// Registry locations of the host DNS configuration this package programs,
|
||||
// exported so a diagnostic reader reports the same locations that are written.
|
||||
const (
|
||||
// NRPTKeyPrefix starts the name of every NRPT rule key this client creates.
|
||||
// Older versions used different layouts under the same prefix: a single
|
||||
// unsuffixed key, then one key per domain, now one key per batch of domains.
|
||||
NRPTKeyPrefix = "NetBird-Match"
|
||||
// NRPTKeyPrefix starts the name of every NRPT rule key this client creates:
|
||||
// the match rules, the catch-all, and the .local exemption. Cleanup
|
||||
// enumerates by this prefix, so a new kind of rule is removed by existing
|
||||
// code as long as its key starts here.
|
||||
NRPTKeyPrefix = "NetBird-"
|
||||
|
||||
// nrptMatchKeyName names the match-domain rules. Older versions used
|
||||
// different layouts under the same name: a single unsuffixed key, then one
|
||||
// key per domain, now one key per batch of domains.
|
||||
nrptMatchKeyName = NRPTKeyPrefix + "Match"
|
||||
|
||||
// DNSPolicyConfigRoot holds the NRPT rules of the local policy store.
|
||||
DNSPolicyConfigRoot = `SYSTEM\CurrentControlSet\Services\Dnscache\Parameters\DnsPolicyConfig`
|
||||
@@ -53,8 +61,24 @@ const (
|
||||
)
|
||||
|
||||
const (
|
||||
dnsPolicyConfigMatchPath = DNSPolicyConfigRoot + `\` + NRPTKeyPrefix
|
||||
gpoDnsPolicyConfigMatchPath = GPODNSPolicyConfigRoot + `\` + NRPTKeyPrefix
|
||||
dnsPolicyConfigMatchPath = DNSPolicyConfigRoot + `\` + nrptMatchKeyName
|
||||
gpoDnsPolicyConfigMatchPath = GPODNSPolicyConfigRoot + `\` + nrptMatchKeyName
|
||||
|
||||
dnsPolicyConfigExemptLocalPath = DNSPolicyConfigRoot + `\` + NRPTKeyPrefix + `ExemptLocal`
|
||||
gpoDnsPolicyConfigExemptLocalPath = GPODNSPolicyConfigRoot + `\` + NRPTKeyPrefix + `ExemptLocal`
|
||||
|
||||
nrptCatchAllNamespace = "."
|
||||
// nrptLocalNamespace is reserved for multicast DNS by RFC 6762: a unicast
|
||||
// resolver must not answer for it. The catch-all rule would hand it to us
|
||||
// anyway, so it gets an exemption rule of its own.
|
||||
nrptLocalNamespace = ".local"
|
||||
|
||||
// envLegacyDNSResolution restores the pre-catch-all behaviour: the adapter's
|
||||
// NameServer alone, leaving the OS free to query other adapters' resolvers in
|
||||
// parallel. An escape hatch for setups that depend on a resolver of theirs
|
||||
// still being reachable while connected, at the cost of the leak and of the
|
||||
// race the catch-all rule exists to close.
|
||||
envLegacyDNSResolution = "NB_USE_LEGACY_DNS_RESOLUTION"
|
||||
|
||||
dnsPolicyConfigVersionKey = "Version"
|
||||
dnsPolicyConfigVersionValue = 2
|
||||
@@ -293,6 +317,13 @@ func (r *registryConfigurator) disableWINSForInterface() error {
|
||||
}
|
||||
|
||||
func (r *registryConfigurator) applyDNSConfig(config HostDNSConfig, stateManager *statemanager.Manager) error {
|
||||
// Clear every rule the previous apply installed before installing any new
|
||||
// one, including a leftover catch-all: removal is unconditional so a rule
|
||||
// from an earlier run cannot survive into a config that no longer wants it.
|
||||
if err := r.removeDNSMatchPolicies(); err != nil {
|
||||
log.Errorf("cleanup old dns match policies: %s", err)
|
||||
}
|
||||
|
||||
if config.RouteAll {
|
||||
if err := r.addDNSSetupForAll(config.ServerIP); err != nil {
|
||||
return fmt.Errorf("add dns setup: %w", err)
|
||||
@@ -318,8 +349,22 @@ func (r *registryConfigurator) applyDNSConfig(config HostDNSConfig, stateManager
|
||||
matchDomains = append(matchDomains, "."+strings.TrimSuffix(dConf.Domain, "."))
|
||||
}
|
||||
|
||||
if err := r.removeDNSMatchPolicies(); err != nil {
|
||||
log.Errorf("cleanup old dns match policies: %s", err)
|
||||
// The root namespace is a match domain like any other: it just happens to
|
||||
// match every name. Without it the adapter's NameServer only adds one more
|
||||
// resolver to the set Windows queries in parallel, keeping whichever answer
|
||||
// comes back first — which leaks every query to the local network and lets a
|
||||
// resolver other than ours answer for a name we are authoritative for.
|
||||
if config.RouteAll {
|
||||
if parseBoolEnv(envLegacyDNSResolution) {
|
||||
log.Infof("%s is set, leaving DNS resolution shared with the other adapters' resolvers instead of forcing it through %s", envLegacyDNSResolution, config.ServerIP)
|
||||
} else {
|
||||
matchDomains = append(matchDomains, nrptCatchAllNamespace)
|
||||
log.Infof("routing every namespace through %s: DNS resolution is now exclusive to NetBird", config.ServerIP)
|
||||
|
||||
if err := r.addDNSExemptLocalPolicy(); err != nil {
|
||||
return fmt.Errorf("add dns exempt policy: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(matchDomains) != 0 {
|
||||
@@ -397,6 +442,42 @@ func (r *registryConfigurator) addDNSMatchPolicy(domains []string, ip netip.Addr
|
||||
return nil
|
||||
}
|
||||
|
||||
// addDNSExemptLocalPolicy carves .local back out of the catch-all. RFC 6762
|
||||
// reserves it for multicast DNS, so forwarding those names to a unicast
|
||||
// upstream answers NXDOMAIN for hosts that do exist - printers, NAS boxes, and
|
||||
// anything else announcing itself on the link - and the answer is authoritative
|
||||
// enough that Windows stops looking. A rule naming the namespace with no
|
||||
// servers hands it back to the DNS client untouched. A more specific rule still
|
||||
// wins, so a match domain under .local keeps going through us.
|
||||
func (r *registryConfigurator) addDNSExemptLocalPolicy() error {
|
||||
var noServers netip.Addr
|
||||
|
||||
if err := r.configureDNSPolicy(dnsPolicyConfigExemptLocalPath, []string{nrptLocalNamespace}, noServers); err != nil {
|
||||
return fmt.Errorf("configure exempt policy for %s: %w", nrptLocalNamespace, err)
|
||||
}
|
||||
|
||||
if r.gpo {
|
||||
if err := r.configureDNSPolicy(gpoDnsPolicyConfigExemptLocalPath, []string{nrptLocalNamespace}, noServers); err != nil {
|
||||
return fmt.Errorf("configure gpo exempt policy for %s: %w", nrptLocalNamespace, err)
|
||||
}
|
||||
if err := refreshGroupPolicy(); err != nil {
|
||||
log.Warnf("failed to refresh group policy: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Infof("added NRPT exemption for %s, leaving it to the OS resolver", nrptLocalNamespace)
|
||||
return nil
|
||||
}
|
||||
|
||||
// configureDNSPolicy writes one NRPT rule. An invalid ip writes an exemption
|
||||
// rule: the namespace with an empty server list, which tells the DNS client to
|
||||
// resolve those names the way it would without any rule at all.
|
||||
//
|
||||
// The empty string is the whole difference, and it has to be written: dropping
|
||||
// the value and clearing ConfigOptions instead produces a rule Windows treats
|
||||
// as a no-op, keeps out of Get-DnsClientNrptPolicy -Effective, and ignores in
|
||||
// favour of the catch-all. 0x8 says the server list is the meaningful part of
|
||||
// the rule, and an empty list then means "no server, resolve normally".
|
||||
func (r *registryConfigurator) configureDNSPolicy(policyPath string, domains []string, ip netip.Addr) error {
|
||||
if err := removeRegistryKeyFromDNSPolicyConfig(policyPath); err != nil {
|
||||
return fmt.Errorf("remove existing dns policy: %w", err)
|
||||
@@ -416,7 +497,11 @@ func (r *registryConfigurator) configureDNSPolicy(policyPath string, domains []s
|
||||
return fmt.Errorf("set %s: %w", dnsPolicyConfigNameKey, err)
|
||||
}
|
||||
|
||||
if err := regKey.SetStringValue(dnsPolicyConfigGenericDNSServersKey, ip.String()); err != nil {
|
||||
var servers string
|
||||
if ip.IsValid() {
|
||||
servers = ip.String()
|
||||
}
|
||||
if err := regKey.SetStringValue(dnsPolicyConfigGenericDNSServersKey, servers); err != nil {
|
||||
return fmt.Errorf("set %s: %w", dnsPolicyConfigGenericDNSServersKey, err)
|
||||
}
|
||||
|
||||
@@ -514,8 +599,11 @@ func (r *registryConfigurator) getInterfaceRegistryKey() (registry.Key, error) {
|
||||
}
|
||||
|
||||
func (r *registryConfigurator) restoreHostDNS() error {
|
||||
// Propagated, unlike in applyDNSConfig: there we are about to write fresh
|
||||
// rules over whatever survived, here we are leaving, and a rule left behind
|
||||
// keeps sending every query to an address that is about to disappear.
|
||||
if err := r.removeDNSMatchPolicies(); err != nil {
|
||||
log.Errorf("remove dns match policies: %s", err)
|
||||
return fmt.Errorf("remove dns match policies: %w", err)
|
||||
}
|
||||
|
||||
if err := r.deleteInterfaceRegistryKeyProperty(interfaceConfigSearchListKey); err != nil {
|
||||
@@ -598,9 +686,17 @@ func listNRPTRuleKeys(root string) ([]string, error) {
|
||||
|
||||
func removeRegistryKeyFromDNSPolicyConfig(regKeyPath string) error {
|
||||
k, err := registry.OpenKey(registry.LOCAL_MACHINE, regKeyPath, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
log.Debugf("failed to open HKEY_LOCAL_MACHINE\\%s: %v", regKeyPath, err)
|
||||
switch {
|
||||
case errors.Is(err, registry.ErrNotExist), errors.Is(err, syscall.ERROR_PATH_NOT_FOUND):
|
||||
// nothing to remove, which is the normal case for a rule this config
|
||||
// never installed
|
||||
log.Debugf("HKEY_LOCAL_MACHINE\\%s does not exist", regKeyPath)
|
||||
return nil
|
||||
case err != nil:
|
||||
// anything else has to reach the caller: reporting success here would
|
||||
// leave the rule in force while claiming it was removed, which is how a
|
||||
// stale rule outlives the interface it points at
|
||||
return fmt.Errorf("open HKEY_LOCAL_MACHINE\\%s: %w", regKeyPath, err)
|
||||
}
|
||||
|
||||
closer(k)
|
||||
@@ -636,6 +732,20 @@ func refreshGroupPolicy() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseBoolEnv(key string) bool {
|
||||
val := os.Getenv(key)
|
||||
if val == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseBool(val)
|
||||
if err != nil {
|
||||
log.Warnf("failed to parse %s=%q: %v", key, val, err)
|
||||
return false
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func closer(closer io.Closer) {
|
||||
if err := closer.Close(); err != nil {
|
||||
log.Errorf("failed to close: %s", err)
|
||||
|
||||
@@ -94,6 +94,145 @@ func TestNRPTEntriesCleanupOnConfigChange(t *testing.T) {
|
||||
assert.False(t, exists, "NRPT rule 2 should NOT exist after reducing to 75 domains")
|
||||
}
|
||||
|
||||
// TestNRPTCatchAllRule verifies that RouteAll adds the root namespace to the
|
||||
// match rule instead of a rule of its own, that .local is carved back out with
|
||||
// an empty server list, and that both go away when RouteAll is cleared or the
|
||||
// host DNS is restored.
|
||||
func TestNRPTCatchAllRule(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping registry integration test in short mode")
|
||||
}
|
||||
|
||||
defer cleanupRegistryKeys(t)
|
||||
cleanupRegistryKeys(t)
|
||||
|
||||
testIP := netip.MustParseAddr("100.64.0.1")
|
||||
testGUID := "{12345678-1234-1234-1234-123456789ABC}"
|
||||
interfacePath := InterfaceConfigPath + `\` + testGUID
|
||||
testKey, _, err := registry.CreateKey(registry.LOCAL_MACHINE, interfacePath, registry.SET_VALUE)
|
||||
require.NoError(t, err, "Should create test interface registry key")
|
||||
require.NoError(t, testKey.Close(), "close test interface registry key")
|
||||
defer func() {
|
||||
assert.NoError(t, registry.DeleteKey(registry.LOCAL_MACHINE, interfacePath), "delete test interface registry key")
|
||||
}()
|
||||
|
||||
cfg := ®istryConfigurator{guid: testGUID}
|
||||
|
||||
matchOnly := HostDNSConfig{
|
||||
ServerIP: testIP,
|
||||
Domains: []DomainConfig{{Domain: "example.com", MatchOnly: true}},
|
||||
}
|
||||
primary := HostDNSConfig{
|
||||
ServerIP: testIP,
|
||||
RouteAll: true,
|
||||
Domains: []DomainConfig{{Domain: "example.com", MatchOnly: true}},
|
||||
}
|
||||
firstRule := fmt.Sprintf("%s-0", dnsPolicyConfigMatchPath)
|
||||
|
||||
// The root namespace is not a rule of its own: it rides in the match rule,
|
||||
// which is the point of it not being a special case.
|
||||
require.NoError(t, cfg.applyDNSConfig(matchOnly, nil))
|
||||
names := ruleNamespaces(t, firstRule)
|
||||
assert.Contains(t, names, ".example.com")
|
||||
assert.NotContains(t, names, nrptCatchAllNamespace, "a match-only config must not claim every namespace")
|
||||
|
||||
require.NoError(t, cfg.applyDNSConfig(primary, nil))
|
||||
names = ruleNamespaces(t, firstRule)
|
||||
assert.Contains(t, names, ".example.com")
|
||||
assert.Contains(t, names, nrptCatchAllNamespace, "RouteAll should add the root namespace to the match rule")
|
||||
|
||||
k, err := registry.OpenKey(registry.LOCAL_MACHINE, firstRule, registry.QUERY_VALUE)
|
||||
require.NoError(t, err)
|
||||
servers, _, err := k.GetStringValue(dnsPolicyConfigGenericDNSServersKey)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testIP.String(), servers, "every namespace in the rule resolves through our resolver")
|
||||
require.NoError(t, k.Close(), "close match rule key")
|
||||
|
||||
// .local is carved back out: RFC 6762 reserves it for mDNS, so it needs a
|
||||
// rule of its own — it is the one rule with a different server list.
|
||||
ek, err := registry.OpenKey(registry.LOCAL_MACHINE, dnsPolicyConfigExemptLocalPath, registry.QUERY_VALUE)
|
||||
require.NoError(t, err, "exemption rule should exist once the root namespace is claimed")
|
||||
|
||||
exemptNames, _, err := ek.GetStringsValue(dnsPolicyConfigNameKey)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{nrptLocalNamespace}, exemptNames, "the exemption should name only the mDNS namespace")
|
||||
|
||||
exemptServers, _, err := ek.GetStringValue(dnsPolicyConfigGenericDNSServersKey)
|
||||
require.NoError(t, err, "the value has to be present, empty: without it Windows drops the rule")
|
||||
assert.Empty(t, exemptServers, "an exemption rule lists no servers")
|
||||
|
||||
exemptOpts, _, err := ek.GetIntegerValue(dnsPolicyConfigConfigOptionsKey)
|
||||
require.NoError(t, err)
|
||||
assert.EqualValues(t, dnsPolicyConfigConfigOptionsValue, exemptOpts, "same options as a normal rule; the empty server list is what makes it an exemption")
|
||||
require.NoError(t, ek.Close(), "close exemption rule key")
|
||||
|
||||
require.NoError(t, cfg.applyDNSConfig(matchOnly, nil))
|
||||
names = ruleNamespaces(t, firstRule)
|
||||
assert.NotContains(t, names, nrptCatchAllNamespace, "clearing RouteAll should drop the root namespace")
|
||||
|
||||
exists, err := registryKeyExists(dnsPolicyConfigExemptLocalPath)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "exemption rule should go with the namespace it carves out of")
|
||||
|
||||
require.NoError(t, cfg.applyDNSConfig(primary, nil))
|
||||
require.NoError(t, cfg.restoreHostDNS())
|
||||
exists, err = registryKeyExists(firstRule)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "restore should leave no rule behind")
|
||||
}
|
||||
|
||||
// ruleNamespaces returns the namespaces an NRPT rule key claims.
|
||||
func ruleNamespaces(t *testing.T, path string) []string {
|
||||
t.Helper()
|
||||
k, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
|
||||
require.NoError(t, err, "rule key %s should exist", path)
|
||||
defer k.Close()
|
||||
|
||||
names, _, err := k.GetStringsValue(dnsPolicyConfigNameKey)
|
||||
require.NoError(t, err)
|
||||
return names
|
||||
}
|
||||
|
||||
// TestNRPTCatchAllRuleLegacyEnv verifies that NB_USE_LEGACY_DNS_RESOLUTION
|
||||
// leaves the root namespace unclaimed, so no rule is written for a RouteAll
|
||||
// config that carries no match domains.
|
||||
func TestNRPTCatchAllRuleLegacyEnv(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping registry integration test in short mode")
|
||||
}
|
||||
|
||||
defer cleanupRegistryKeys(t)
|
||||
cleanupRegistryKeys(t)
|
||||
|
||||
t.Setenv(envLegacyDNSResolution, "true")
|
||||
|
||||
testGUID := "{12345678-1234-1234-1234-123456789ABC}"
|
||||
interfacePath := InterfaceConfigPath + `\` + testGUID
|
||||
testKey, _, err := registry.CreateKey(registry.LOCAL_MACHINE, interfacePath, registry.SET_VALUE)
|
||||
require.NoError(t, err, "Should create test interface registry key")
|
||||
require.NoError(t, testKey.Close(), "close test interface registry key")
|
||||
defer func() {
|
||||
assert.NoError(t, registry.DeleteKey(registry.LOCAL_MACHINE, interfacePath), "delete test interface registry key")
|
||||
}()
|
||||
|
||||
cfg := ®istryConfigurator{guid: testGUID}
|
||||
config := HostDNSConfig{
|
||||
ServerIP: netip.MustParseAddr("100.64.0.1"),
|
||||
RouteAll: true,
|
||||
}
|
||||
|
||||
require.NoError(t, cfg.applyDNSConfig(config, nil))
|
||||
|
||||
// RouteAll with no match domains and the switch set leaves nothing to write.
|
||||
exists, err := registryKeyExists(fmt.Sprintf("%s-0", dnsPolicyConfigMatchPath))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "no rule should be written when the legacy env var is set")
|
||||
|
||||
exists, err = registryKeyExists(dnsPolicyConfigExemptLocalPath)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, exists, "no exemption without a claimed root namespace")
|
||||
}
|
||||
|
||||
func registryKeyExists(path string) (bool, error) {
|
||||
k, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/client/iface/wgaddr"
|
||||
nbdns "github.com/netbirdio/netbird/dns"
|
||||
mgmProto "github.com/netbirdio/netbird/shared/management/proto"
|
||||
)
|
||||
|
||||
func TestCreatePTRRecord_IPv4(t *testing.T) {
|
||||
@@ -136,3 +138,88 @@ func TestAddReverseZone_IPv6(t *testing.T) {
|
||||
assert.Len(t, reverseZone.Records, 1)
|
||||
assert.Equal(t, int(dns.TypePTR), reverseZone.Records[0].Type)
|
||||
}
|
||||
|
||||
// TestToDNSConfig_ZoneFlagsPreserved pins the per-zone NonAuthoritative flag
|
||||
// through the legacy DNSConfig path. A non-authoritative zone is match-only:
|
||||
// the local resolver falls through to the upstream for an in-zone name it does
|
||||
// not define. The built-in peer zone is the authoritative one and must stay
|
||||
// that way, so the flag has to travel per zone rather than be derived.
|
||||
func TestToDNSConfig_ZoneFlagsPreserved(t *testing.T) {
|
||||
config := toDNSConfig(&mgmProto.DNSConfig{
|
||||
ServiceEnable: true,
|
||||
CustomZones: []*mgmProto.CustomZone{
|
||||
{
|
||||
Domain: "netbird.cloud.",
|
||||
Records: []*mgmProto.SimpleRecord{
|
||||
{Name: "peer1.netbird.cloud.", Type: int64(dns.TypeA), Class: nbdns.DefaultClass, TTL: 300, RData: "100.64.0.1"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Domain: "corp.internal.",
|
||||
NonAuthoritative: true,
|
||||
SearchDomainDisabled: true,
|
||||
Records: []*mgmProto.SimpleRecord{
|
||||
{Name: "db.corp.internal.", Type: int64(dns.TypeA), Class: nbdns.DefaultClass, TTL: 300, RData: "10.10.0.5"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, wgaddr.Address{
|
||||
IP: netip.MustParseAddr("100.64.0.1"),
|
||||
Network: netip.MustParsePrefix("100.64.0.0/16"),
|
||||
})
|
||||
|
||||
zones := make(map[string]nbdns.CustomZone, len(config.CustomZones))
|
||||
for _, zone := range config.CustomZones {
|
||||
zones[zone.Domain] = zone
|
||||
}
|
||||
|
||||
peerZone, ok := zones["netbird.cloud."]
|
||||
require.True(t, ok, "peer zone must survive")
|
||||
assert.False(t, peerZone.NonAuthoritative, "the built-in peer zone owns the account domain and stays authoritative")
|
||||
|
||||
accountZone, ok := zones["corp.internal."]
|
||||
require.True(t, ok, "account zone must survive")
|
||||
assert.True(t, accountZone.NonAuthoritative, "an account zone stays match-only, else undefined in-zone names get black-holed")
|
||||
assert.True(t, accountZone.SearchDomainDisabled)
|
||||
}
|
||||
|
||||
// TestToDNSConfig_SingleZoneForcedAuthoritative pins the compatibility clause
|
||||
// in toDNSConfig: a config carrying exactly one zone is treated as
|
||||
// authoritative no matter what the server said, because servers that predate
|
||||
// the NonAuthoritative field send only the peer FQDN zone.
|
||||
//
|
||||
// The clause can only ever downgrade an explicit true to false, so a server
|
||||
// that legitimately sends a single non-authoritative zone — an account whose
|
||||
// only zone is a custom one, with no peer records to build the built-in zone
|
||||
// from — gets that zone's whole apex black-holed on the client. Real accounts
|
||||
// always carry the peer zone alongside, which is why this is latent. Narrowing
|
||||
// it needs a way to tell "unset" from "false" on the wire, or the account
|
||||
// domain passed down here; until then this test states the contract so a
|
||||
// change to it is deliberate.
|
||||
func TestToDNSConfig_SingleZoneForcedAuthoritative(t *testing.T) {
|
||||
config := toDNSConfig(&mgmProto.DNSConfig{
|
||||
ServiceEnable: true,
|
||||
CustomZones: []*mgmProto.CustomZone{
|
||||
{
|
||||
Domain: "corp.internal.",
|
||||
NonAuthoritative: true,
|
||||
Records: []*mgmProto.SimpleRecord{
|
||||
{Name: "db.corp.internal.", Type: int64(dns.TypeA), Class: nbdns.DefaultClass, TTL: 300, RData: "10.10.0.5"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, wgaddr.Address{
|
||||
IP: netip.MustParseAddr("100.64.0.1"),
|
||||
Network: netip.MustParsePrefix("100.64.0.0/16"),
|
||||
})
|
||||
|
||||
require.NotEmpty(t, config.CustomZones)
|
||||
assert.Equal(t, "corp.internal.", config.CustomZones[0].Domain)
|
||||
assert.False(t, config.CustomZones[0].NonAuthoritative,
|
||||
"a lone zone is forced authoritative for pre-NonAuthoritative servers")
|
||||
|
||||
// The reverse zone the config gains afterwards must not feed back into the
|
||||
// decision: the compat gate counts the zones the server sent.
|
||||
require.Len(t, config.CustomZones, 2, "a reverse zone is appended for the overlay prefix")
|
||||
assert.Equal(t, "64.100.in-addr.arpa.", config.CustomZones[1].Domain)
|
||||
}
|
||||
|
||||
@@ -138,6 +138,7 @@ type EngineConfig struct {
|
||||
RosenpassPermissive bool
|
||||
|
||||
ServerSSHAllowed bool
|
||||
RemoteJobsAllowed bool
|
||||
EnableSSHRoot *bool
|
||||
EnableSSHSFTP *bool
|
||||
EnableSSHLocalPortForwarding *bool
|
||||
@@ -1268,6 +1269,7 @@ func (e *Engine) applyInfoFlags(info *system.Info) {
|
||||
e.config.EnableSSHLocalPortForwarding,
|
||||
e.config.EnableSSHRemotePortForwarding,
|
||||
e.config.DisableSSHAuth,
|
||||
&e.config.RemoteJobsAllowed,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1355,6 +1357,13 @@ func (e *Engine) receiveJobEvents() {
|
||||
ID: msg.ID,
|
||||
Status: mgmProto.JobStatus_failed,
|
||||
}
|
||||
// Remote jobs are an explicit opt-in. When not enabled on this
|
||||
// peer, every job is refused before any work is done.
|
||||
if !e.config.RemoteJobsAllowed {
|
||||
log.Warnf("refusing remote job: remote jobs are not enabled on this peer (enable with --allow-remote-jobs)")
|
||||
resp.Reason = []byte("remote jobs are not enabled on this peer")
|
||||
return &resp
|
||||
}
|
||||
switch params := msg.WorkloadParameters.(type) {
|
||||
case *mgmProto.JobRequest_Bundle:
|
||||
bundleResult, err := e.handleBundle(params.Bundle)
|
||||
@@ -1384,7 +1393,25 @@ func (e *Engine) receiveJobEvents() {
|
||||
}
|
||||
|
||||
func (e *Engine) handleBundle(params *mgmProto.BundleParameters) (*mgmProto.JobResponse_Bundle, error) {
|
||||
log.Infof("handle remote debug bundle request: %s", params.String())
|
||||
// The upload URL can carry a host, credentials, or query tokens, so it is
|
||||
// kept out of the info-level line; the full parameters stay available at
|
||||
// debug level for troubleshooting.
|
||||
log.Infof("handle remote debug bundle request: anonymize=%v anonymize_level=%q log_file_count=%d bundle_for=%v bundle_for_time=%d",
|
||||
params.GetAnonymize(), params.GetAnonymizeLevel(), params.GetLogFileCount(), params.GetBundleFor(), params.GetBundleForTime())
|
||||
log.Debugf("remote debug bundle request parameters: %s", params.String())
|
||||
|
||||
// Resolve the upload destination: an MDM override, when set, takes
|
||||
// precedence over the management-supplied URL. Both are validated the same
|
||||
// way; an empty result falls back to the default upload server downstream.
|
||||
uploadURL := params.GetUploadUrl()
|
||||
if override := e.config.ProfileConfig.DebugBundleUploadURL; override != "" {
|
||||
log.Infof("using MDM debug bundle upload URL override instead of the management-supplied value")
|
||||
uploadURL = override
|
||||
}
|
||||
if err := validateBundleUploadURL(uploadURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
syncResponse, err := e.GetLatestSyncResponse()
|
||||
if err != nil {
|
||||
log.Warnf("get latest sync response: %v", err)
|
||||
@@ -1412,7 +1439,7 @@ func (e *Engine) handleBundle(params *mgmProto.BundleParameters) (*mgmProto.JobR
|
||||
|
||||
waitFor := time.Duration(params.BundleForTime) * time.Minute
|
||||
|
||||
uploadKey, err := e.jobExecutor.BundleJob(e.ctx, bundleDeps, bundleJobParams, waitFor, e.config.ProfileConfig.ManagementURL.String())
|
||||
uploadKey, err := e.jobExecutor.BundleJob(e.ctx, bundleDeps, bundleJobParams, waitFor, e.config.ProfileConfig.ManagementURL.String(), uploadURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1425,6 +1452,16 @@ func (e *Engine) handleBundle(params *mgmProto.BundleParameters) (*mgmProto.JobR
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// validateBundleUploadURL sanity-checks a management-supplied upload URL for a
|
||||
// remote debug bundle job. It delegates to profilemanager.ValidateBundleUploadURL
|
||||
// so the executor and the MDM policy override share one definition of the rule
|
||||
// (empty accepted; otherwise a well-formed https URL with a host) and cannot
|
||||
// drift. The host is deliberately left unconstrained pending a decision on
|
||||
// management-directed uploads.
|
||||
func validateBundleUploadURL(raw string) error {
|
||||
return profilemanager.ValidateBundleUploadURL(raw)
|
||||
}
|
||||
|
||||
// receiveManagementEvents connects to the Management Service event stream to receive updates from the management service
|
||||
// E.g. when a new peer has been registered and we are allowed to connect to it.
|
||||
func (e *Engine) receiveManagementEvents() {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestValidateBundleUploadURL covers the sanity check applied to a
|
||||
// management-supplied upload URL before a remote debug bundle is generated.
|
||||
func TestValidateBundleUploadURL(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
raw string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "empty falls back to default", raw: ""},
|
||||
{name: "https with host", raw: "https://upload.debug.netbird.io/upload"},
|
||||
{name: "https self-hosted host", raw: "https://upload.example.com"},
|
||||
{name: "plaintext rejected", raw: "http://upload.example.com", wantErr: true},
|
||||
{name: "missing host rejected", raw: "https:///upload", wantErr: true},
|
||||
{name: "port-only authority rejected", raw: "https://:443", wantErr: true},
|
||||
{name: "non-url scheme rejected", raw: "ftp://upload.example.com", wantErr: true},
|
||||
{name: "garbage rejected", raw: "://not a url", wantErr: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := validateBundleUploadURL(tc.raw)
|
||||
if tc.wantErr {
|
||||
require.Error(t, err, "an invalid upload URL must be rejected")
|
||||
return
|
||||
}
|
||||
assert.NoError(t, err, "a valid or empty upload URL must be accepted")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -519,7 +519,7 @@ func startManagement(t *testing.T, dataDir, testFile string) (*grpc.Server, stri
|
||||
|
||||
updateManager := update_channel.NewPeersUpdateManager(metrics)
|
||||
requestBuffer := server.NewAccountRequestBuffer(context.Background(), store)
|
||||
networkMapController := controller.NewController(context.Background(), store, metrics, updateManager, requestBuffer, server.MockIntegratedValidator{}, settingsMockManager, "netbird.selfhosted", port_forwarding.NewControllerMock(), manager.NewEphemeralManager(store, peersManager), config)
|
||||
networkMapController := controller.NewController(context.Background(), store, metrics, updateManager, requestBuffer, server.MockIntegratedValidator{}, settingsMockManager, "netbird.selfhosted", port_forwarding.NewControllerMock(), manager.NewEphemeralManager(store, peersManager), config, nil)
|
||||
accountManager, err := server.BuildManager(context.Background(), config, store, networkMapController, jobManager, nil, "", eventStore, nil, false, ia, metrics, port_forwarding.NewControllerMock(), settingsMockManager, permissionsManager, false, cacheStore)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
// Package localmetrics exposes client connection state as a local
|
||||
// Prometheus /metrics endpoint.
|
||||
package localmetrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
)
|
||||
|
||||
// DefaultListenAddress is used when local metrics are enabled without an explicit address.
|
||||
const DefaultListenAddress = "127.0.0.1:9191"
|
||||
|
||||
const (
|
||||
shutdownTimeout = 3 * time.Second
|
||||
readHeaderTimeout = 5 * time.Second
|
||||
readTimeout = 10 * time.Second
|
||||
writeTimeout = 30 * time.Second
|
||||
idleTimeout = time.Minute
|
||||
)
|
||||
|
||||
// statusSource provides the connection state snapshots the collector reads on scrape.
|
||||
type statusSource interface {
|
||||
GetPeerStates() []peer.State
|
||||
GetManagementState() peer.ManagementState
|
||||
GetSignalState() peer.SignalState
|
||||
}
|
||||
|
||||
// GathererProvider returns the current client metrics gatherer, or nil when
|
||||
// no engine is running. It is called on every scrape.
|
||||
type GathererProvider func() prometheus.Gatherer
|
||||
|
||||
// Manager runs the local /metrics HTTP endpoint according to the active
|
||||
// client configuration. Reconcile is safe to call on every config change.
|
||||
type Manager struct {
|
||||
status statusSource
|
||||
clientMetrics GathererProvider
|
||||
|
||||
mu sync.Mutex
|
||||
srv *http.Server
|
||||
addr string
|
||||
}
|
||||
|
||||
// NewManager creates a manager that serves metrics from status and
|
||||
// clientMetrics and shuts down when ctx is canceled.
|
||||
func NewManager(ctx context.Context, status statusSource, clientMetrics GathererProvider) *Manager {
|
||||
m := &Manager{status: status, clientMetrics: clientMetrics}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
m.Stop()
|
||||
}()
|
||||
return m
|
||||
}
|
||||
|
||||
// Reconcile starts, stops, or restarts the metrics endpoint to match the
|
||||
// desired state. An empty addr falls back to DefaultListenAddress.
|
||||
func (m *Manager) Reconcile(enabled bool, addr string) {
|
||||
if addr == "" {
|
||||
addr = DefaultListenAddress
|
||||
}
|
||||
warnIfNotLoopback(addr)
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if !enabled {
|
||||
m.stop()
|
||||
return
|
||||
}
|
||||
if m.srv != nil && m.addr == addr {
|
||||
return
|
||||
}
|
||||
m.stop()
|
||||
|
||||
registry := prometheus.NewRegistry()
|
||||
registry.MustRegister(newCollector(m.status))
|
||||
|
||||
gatherers := prometheus.Gatherers{registry, prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) {
|
||||
if m.clientMetrics == nil {
|
||||
return nil, nil
|
||||
}
|
||||
g := m.clientMetrics()
|
||||
if g == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return g.Gather()
|
||||
})}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.HandlerFor(gatherers, promhttp.HandlerOpts{}))
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: mux,
|
||||
ReadHeaderTimeout: readHeaderTimeout,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
IdleTimeout: idleTimeout,
|
||||
}
|
||||
m.srv = srv
|
||||
m.addr = addr
|
||||
|
||||
log.Infof("serving local metrics on http://%s/metrics", addr)
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Errorf("failed to serve local metrics on %s: %v", addr, err)
|
||||
m.clear(srv)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// clear drops the reference to srv so a later Reconcile with the same
|
||||
// address restarts it. A newer server may already have replaced it, in
|
||||
// which case the reference must stay.
|
||||
func (m *Manager) clear(srv *http.Server) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.srv != srv {
|
||||
return
|
||||
}
|
||||
m.srv = nil
|
||||
m.addr = ""
|
||||
}
|
||||
|
||||
// Stop shuts down the metrics endpoint if it is running.
|
||||
func (m *Manager) Stop() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.stop()
|
||||
}
|
||||
|
||||
// stop shuts down the running server. Callers must hold m.mu.
|
||||
func (m *Manager) stop() {
|
||||
if m.srv == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := m.srv.Shutdown(ctx); err != nil {
|
||||
log.Debugf("failed to shut down local metrics server: %v", err)
|
||||
}
|
||||
m.srv = nil
|
||||
m.addr = ""
|
||||
}
|
||||
|
||||
// collector converts status recorder snapshots into Prometheus metrics at scrape time.
|
||||
type collector struct {
|
||||
status statusSource
|
||||
|
||||
managementConnected *prometheus.Desc
|
||||
signalConnected *prometheus.Desc
|
||||
peersTotal *prometheus.Desc
|
||||
peersConnected *prometheus.Desc
|
||||
peerLatency *prometheus.Desc
|
||||
}
|
||||
|
||||
func newCollector(status statusSource) *collector {
|
||||
return &collector{
|
||||
status: status,
|
||||
managementConnected: prometheus.NewDesc(
|
||||
"netbird_management_connected",
|
||||
"Whether the client is connected to the management service (1 connected, 0 disconnected).",
|
||||
nil, nil,
|
||||
),
|
||||
signalConnected: prometheus.NewDesc(
|
||||
"netbird_signal_connected",
|
||||
"Whether the client is connected to the signal service (1 connected, 0 disconnected).",
|
||||
nil, nil,
|
||||
),
|
||||
peersTotal: prometheus.NewDesc(
|
||||
"netbird_peers",
|
||||
"Number of peers known to this client.",
|
||||
nil, nil,
|
||||
),
|
||||
peersConnected: prometheus.NewDesc(
|
||||
"netbird_peers_connected",
|
||||
"Number of connected peers by connection type.",
|
||||
[]string{"connection_type"}, nil,
|
||||
),
|
||||
peerLatency: prometheus.NewDesc(
|
||||
"netbird_peer_latency_seconds",
|
||||
"Round-trip latency per directly connected peer; relayed connections have no latency measurement.",
|
||||
[]string{"peer"}, nil,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Describe implements prometheus.Collector.
|
||||
func (c *collector) Describe(ch chan<- *prometheus.Desc) {
|
||||
ch <- c.managementConnected
|
||||
ch <- c.signalConnected
|
||||
ch <- c.peersTotal
|
||||
ch <- c.peersConnected
|
||||
ch <- c.peerLatency
|
||||
}
|
||||
|
||||
// Collect implements prometheus.Collector.
|
||||
func (c *collector) Collect(ch chan<- prometheus.Metric) {
|
||||
ch <- prometheus.MustNewConstMetric(c.managementConnected, prometheus.GaugeValue, boolToFloat(c.status.GetManagementState().Connected))
|
||||
ch <- prometheus.MustNewConstMetric(c.signalConnected, prometheus.GaugeValue, boolToFloat(c.status.GetSignalState().Connected))
|
||||
|
||||
peers := c.status.GetPeerStates()
|
||||
ch <- prometheus.MustNewConstMetric(c.peersTotal, prometheus.GaugeValue, float64(len(peers)))
|
||||
|
||||
var p2p, relayed float64
|
||||
for _, p := range peers {
|
||||
if p.ConnStatus != peer.StatusConnected {
|
||||
continue
|
||||
}
|
||||
if p.Relayed {
|
||||
relayed++
|
||||
continue
|
||||
}
|
||||
p2p++
|
||||
|
||||
if latency := p.Latency.Seconds(); latency > 0 {
|
||||
ch <- prometheus.MustNewConstMetric(c.peerLatency, prometheus.GaugeValue, latency, p.FQDN)
|
||||
}
|
||||
}
|
||||
ch <- prometheus.MustNewConstMetric(c.peersConnected, prometheus.GaugeValue, p2p, "p2p")
|
||||
ch <- prometheus.MustNewConstMetric(c.peersConnected, prometheus.GaugeValue, relayed, "relay")
|
||||
}
|
||||
|
||||
func boolToFloat(b bool) float64 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// IsLoopback reports whether addr binds the endpoint to the local host only.
|
||||
// An empty address means DefaultListenAddress. It fails closed: an address
|
||||
// that cannot be confirmed loopback, including an unparseable one, is not.
|
||||
func IsLoopback(addr string) bool {
|
||||
if addr == "" {
|
||||
addr = DefaultListenAddress
|
||||
}
|
||||
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if host == "localhost" {
|
||||
return true
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(host)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return ip.Unmap().IsLoopback()
|
||||
}
|
||||
|
||||
// warnIfNotLoopback logs a warning when the listen address cannot be
|
||||
// confirmed to be local-only, since the endpoint exposes peer and
|
||||
// connectivity details without authentication.
|
||||
func warnIfNotLoopback(addr string) {
|
||||
if IsLoopback(addr) {
|
||||
return
|
||||
}
|
||||
log.Warnf("local metrics endpoint listens on non-loopback address %s and is reachable from the network without authentication", addr)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package localmetrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
)
|
||||
|
||||
type stubStatus struct {
|
||||
peers []peer.State
|
||||
management peer.ManagementState
|
||||
signal peer.SignalState
|
||||
}
|
||||
|
||||
func (s *stubStatus) GetPeerStates() []peer.State { return s.peers }
|
||||
func (s *stubStatus) GetManagementState() peer.ManagementState { return s.management }
|
||||
func (s *stubStatus) GetSignalState() peer.SignalState { return s.signal }
|
||||
|
||||
func testStatus() *stubStatus {
|
||||
return &stubStatus{
|
||||
management: peer.ManagementState{Connected: true},
|
||||
signal: peer.SignalState{Connected: true},
|
||||
peers: []peer.State{
|
||||
{FQDN: "peer-a.netbird.cloud", IP: "100.90.0.1", ConnStatus: peer.StatusConnected, Relayed: false, Latency: 12 * time.Millisecond},
|
||||
{FQDN: "peer-b.netbird.cloud", IP: "100.90.0.2", ConnStatus: peer.StatusConnected, Relayed: false, Latency: 36 * time.Millisecond},
|
||||
{FQDN: "peer-c.netbird.cloud", IP: "100.90.0.3", ConnStatus: peer.StatusConnected, Relayed: true},
|
||||
{FQDN: "peer-d.netbird.cloud", IP: "100.90.0.4", ConnStatus: peer.StatusIdle},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollector(t *testing.T) {
|
||||
c := newCollector(testStatus())
|
||||
|
||||
expected := `
|
||||
# HELP netbird_management_connected Whether the client is connected to the management service (1 connected, 0 disconnected).
|
||||
# TYPE netbird_management_connected gauge
|
||||
netbird_management_connected 1
|
||||
# HELP netbird_peer_latency_seconds Round-trip latency per directly connected peer; relayed connections have no latency measurement.
|
||||
# TYPE netbird_peer_latency_seconds gauge
|
||||
netbird_peer_latency_seconds{peer="peer-a.netbird.cloud"} 0.012
|
||||
netbird_peer_latency_seconds{peer="peer-b.netbird.cloud"} 0.036
|
||||
# HELP netbird_peers Number of peers known to this client.
|
||||
# TYPE netbird_peers gauge
|
||||
netbird_peers 4
|
||||
# HELP netbird_peers_connected Number of connected peers by connection type.
|
||||
# TYPE netbird_peers_connected gauge
|
||||
netbird_peers_connected{connection_type="p2p"} 2
|
||||
netbird_peers_connected{connection_type="relay"} 1
|
||||
# HELP netbird_signal_connected Whether the client is connected to the signal service (1 connected, 0 disconnected).
|
||||
# TYPE netbird_signal_connected gauge
|
||||
netbird_signal_connected 1
|
||||
`
|
||||
require.NoError(t, testutil.CollectAndCompare(c, strings.NewReader(expected)))
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err, "must find a free port")
|
||||
addr := ln.Addr().String()
|
||||
require.NoError(t, ln.Close())
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
m := NewManager(ctx, testStatus(), nil)
|
||||
m.Reconcile(true, addr)
|
||||
|
||||
var body string
|
||||
require.Eventually(t, func() bool {
|
||||
resp, err := http.Get(fmt.Sprintf("http://%s/metrics", addr))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
return false
|
||||
}
|
||||
body = string(data)
|
||||
return true
|
||||
}, 2*time.Second, 50*time.Millisecond, "metrics endpoint should come up")
|
||||
|
||||
assert.Contains(t, body, "netbird_peers 4")
|
||||
assert.Contains(t, body, `netbird_peers_connected{connection_type="relay"} 1`)
|
||||
assert.Contains(t, body, `netbird_peer_latency_seconds{peer="peer-a.netbird.cloud"} 0.012`)
|
||||
}
|
||||
|
||||
// A server that never came up must not be remembered, otherwise reconciling the
|
||||
// same address again is a no-op and the endpoint never recovers.
|
||||
func TestReconcileForgetsAFailedServer(t *testing.T) {
|
||||
blocker, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err, "must find a free port")
|
||||
t.Cleanup(func() { _ = blocker.Close() })
|
||||
addr := blocker.Addr().String()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
m := NewManager(ctx, testStatus(), nil)
|
||||
m.Reconcile(true, addr)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.srv == nil && m.addr == ""
|
||||
}, 2*time.Second, 20*time.Millisecond, "the failed server should be dropped")
|
||||
|
||||
require.NoError(t, blocker.Close())
|
||||
m.Reconcile(true, addr)
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
resp, err := http.Get(fmt.Sprintf("http://%s/metrics", addr))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return resp.StatusCode == http.StatusOK
|
||||
}, 2*time.Second, 50*time.Millisecond, "reconciling the same address should retry the bind")
|
||||
}
|
||||
|
||||
func TestIsLoopback(t *testing.T) {
|
||||
tests := map[string]bool{
|
||||
"": true,
|
||||
"127.0.0.1:9191": true,
|
||||
"127.9.9.9:9191": true,
|
||||
"[::1]:9191": true,
|
||||
"[::ffff:127.0.0.1]:9191": true,
|
||||
"localhost:9191": true,
|
||||
"0.0.0.0:9191": false,
|
||||
"[::]:9191": false,
|
||||
"192.168.1.10:9191": false,
|
||||
"not-an-address": false,
|
||||
"example.com:9191": false,
|
||||
}
|
||||
|
||||
for addr, want := range tests {
|
||||
t.Run(addr, func(t *testing.T) {
|
||||
assert.Equal(t, want, IsLoopback(addr), "loopback verdict for %q", addr)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -45,30 +45,13 @@ func (m *influxDBMetrics) RecordConnectionStages(
|
||||
isReconnection bool,
|
||||
timestamps ConnectionStageTimestamps,
|
||||
) {
|
||||
var signalingReceivedToConnection, connectionToWgHandshake, totalDuration float64
|
||||
|
||||
if !timestamps.SignalingReceived.IsZero() && !timestamps.ConnectionReady.IsZero() {
|
||||
signalingReceivedToConnection = timestamps.ConnectionReady.Sub(timestamps.SignalingReceived).Seconds()
|
||||
}
|
||||
|
||||
if !timestamps.ConnectionReady.IsZero() && !timestamps.WgHandshakeSuccess.IsZero() {
|
||||
connectionToWgHandshake = timestamps.WgHandshakeSuccess.Sub(timestamps.ConnectionReady).Seconds()
|
||||
}
|
||||
|
||||
if !timestamps.SignalingReceived.IsZero() && !timestamps.WgHandshakeSuccess.IsZero() {
|
||||
totalDuration = timestamps.WgHandshakeSuccess.Sub(timestamps.SignalingReceived).Seconds()
|
||||
}
|
||||
|
||||
attemptType := "initial"
|
||||
if isReconnection {
|
||||
attemptType = "reconnection"
|
||||
}
|
||||
signalingReceivedToConnection, connectionToWgHandshake, totalDuration := timestamps.Durations()
|
||||
|
||||
connTypeStr := connectionType.String()
|
||||
tags := fmt.Sprintf("deployment_type=%s,connection_type=%s,attempt_type=%s,version=%s,os=%s,arch=%s,peer_id=%s,connection_pair_id=%s",
|
||||
agentInfo.DeploymentType.String(),
|
||||
connTypeStr,
|
||||
attemptType,
|
||||
attemptType(isReconnection),
|
||||
agentInfo.Version,
|
||||
agentInfo.OS,
|
||||
agentInfo.Arch,
|
||||
@@ -94,7 +77,7 @@ func (m *influxDBMetrics) RecordConnectionStages(
|
||||
m.trimLocked()
|
||||
|
||||
log.Tracef("peer connection metrics [%s, %s, %s]: signalingReceived→connection: %.3fs, connection→wg_handshake: %.3fs, total: %.3fs",
|
||||
agentInfo.DeploymentType.String(), connTypeStr, attemptType, signalingReceivedToConnection, connectionToWgHandshake, totalDuration)
|
||||
agentInfo.DeploymentType.String(), connTypeStr, attemptType(isReconnection), signalingReceivedToConnection, connectionToWgHandshake, totalDuration)
|
||||
}
|
||||
|
||||
func (m *influxDBMetrics) RecordSyncDuration(_ context.Context, agentInfo AgentInfo, duration time.Duration) {
|
||||
|
||||
@@ -89,6 +89,21 @@ type ConnectionStageTimestamps struct {
|
||||
WgHandshakeSuccess time.Time
|
||||
}
|
||||
|
||||
// Durations returns the stage durations in seconds. A duration is zero when
|
||||
// either of its timestamps is missing.
|
||||
func (c ConnectionStageTimestamps) Durations() (signalingToConnection, connectionToWgHandshake, total float64) {
|
||||
if !c.SignalingReceived.IsZero() && !c.ConnectionReady.IsZero() {
|
||||
signalingToConnection = c.ConnectionReady.Sub(c.SignalingReceived).Seconds()
|
||||
}
|
||||
if !c.ConnectionReady.IsZero() && !c.WgHandshakeSuccess.IsZero() {
|
||||
connectionToWgHandshake = c.WgHandshakeSuccess.Sub(c.ConnectionReady).Seconds()
|
||||
}
|
||||
if !c.SignalingReceived.IsZero() && !c.WgHandshakeSuccess.IsZero() {
|
||||
total = c.WgHandshakeSuccess.Sub(c.SignalingReceived).Seconds()
|
||||
}
|
||||
return signalingToConnection, connectionToWgHandshake, total
|
||||
}
|
||||
|
||||
// String returns a human-readable representation of the connection stage timestamps
|
||||
func (c ConnectionStageTimestamps) String() string {
|
||||
return fmt.Sprintf("ConnectionStageTimestamps{SignalingReceived=%v, ConnectionReady=%v, WgHandshakeSuccess=%v}",
|
||||
@@ -279,3 +294,11 @@ func (c *ClientMetrics) stopPushLocked() {
|
||||
c.wg.Wait()
|
||||
c.push.Store(nil)
|
||||
}
|
||||
|
||||
// attemptType returns the metric label for an initial vs reconnection attempt.
|
||||
func attemptType(isReconnection bool) string {
|
||||
if isReconnection {
|
||||
return "reconnection"
|
||||
}
|
||||
return "initial"
|
||||
}
|
||||
|
||||
@@ -2,10 +2,24 @@
|
||||
|
||||
package metrics
|
||||
|
||||
import "github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
// NewClientMetrics creates a new ClientMetrics instance
|
||||
func NewClientMetrics(agentInfo AgentInfo) *ClientMetrics {
|
||||
return &ClientMetrics{
|
||||
impl: newInfluxDBMetrics(),
|
||||
impl: newPrometheusMetrics(newInfluxDBMetrics()),
|
||||
agentInfo: agentInfo,
|
||||
}
|
||||
}
|
||||
|
||||
// PrometheusGatherer returns the registry with the mirrored Prometheus
|
||||
// metrics, or nil when unavailable.
|
||||
func (c *ClientMetrics) PrometheusGatherer() prometheus.Gatherer {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if pm, ok := c.impl.(*prometheusMetrics); ok {
|
||||
return pm.Gatherer()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//go:build !js
|
||||
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// prometheusMetrics mirrors recorded client metrics into a Prometheus
|
||||
// registry for the local /metrics endpoint, then delegates to the wrapped
|
||||
// implementation. Export and Reset pass through untouched: Prometheus
|
||||
// metrics are cumulative and pull-based.
|
||||
type prometheusMetrics struct {
|
||||
next metricsImplementation
|
||||
registry *prometheus.Registry
|
||||
|
||||
connectionStages *prometheus.HistogramVec
|
||||
syncDuration prometheus.Histogram
|
||||
syncPhaseDuration *prometheus.HistogramVec
|
||||
loginDuration *prometheus.HistogramVec
|
||||
}
|
||||
|
||||
func newPrometheusMetrics(next metricsImplementation) *prometheusMetrics {
|
||||
connectionBuckets := []float64{.05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60}
|
||||
|
||||
m := &prometheusMetrics{
|
||||
next: next,
|
||||
registry: prometheus.NewRegistry(),
|
||||
connectionStages: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "netbird_peer_connection_stage_duration_seconds",
|
||||
Help: "Duration of peer connection establishment stages.",
|
||||
Buckets: connectionBuckets,
|
||||
}, []string{"stage", "connection_type", "attempt_type"}),
|
||||
syncDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Name: "netbird_sync_duration_seconds",
|
||||
Help: "Duration of management sync message processing.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}),
|
||||
syncPhaseDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "netbird_sync_phase_duration_seconds",
|
||||
Help: "Duration of individual sync processing phases.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"phase"}),
|
||||
loginDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Name: "netbird_login_duration_seconds",
|
||||
Help: "Duration of logins to the management service.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"success"}),
|
||||
}
|
||||
|
||||
m.registry.MustRegister(m.connectionStages, m.syncDuration, m.syncPhaseDuration, m.loginDuration)
|
||||
return m
|
||||
}
|
||||
|
||||
// Gatherer returns the registry holding the mirrored metrics.
|
||||
func (m *prometheusMetrics) Gatherer() prometheus.Gatherer {
|
||||
return m.registry
|
||||
}
|
||||
|
||||
// RecordConnectionStages implements metricsImplementation.
|
||||
func (m *prometheusMetrics) RecordConnectionStages(
|
||||
ctx context.Context,
|
||||
agentInfo AgentInfo,
|
||||
connectionPairID string,
|
||||
connectionType ConnectionType,
|
||||
isReconnection bool,
|
||||
timestamps ConnectionStageTimestamps,
|
||||
) {
|
||||
attempt := attemptType(isReconnection)
|
||||
connType := connectionType.String()
|
||||
|
||||
signalingToConnection, connectionToWgHandshake, total := timestamps.Durations()
|
||||
if signalingToConnection > 0 {
|
||||
m.connectionStages.WithLabelValues("signaling_to_connection", connType, attempt).Observe(signalingToConnection)
|
||||
}
|
||||
if connectionToWgHandshake > 0 {
|
||||
m.connectionStages.WithLabelValues("connection_to_wg_handshake", connType, attempt).Observe(connectionToWgHandshake)
|
||||
}
|
||||
if total > 0 {
|
||||
m.connectionStages.WithLabelValues("total", connType, attempt).Observe(total)
|
||||
}
|
||||
|
||||
m.next.RecordConnectionStages(ctx, agentInfo, connectionPairID, connectionType, isReconnection, timestamps)
|
||||
}
|
||||
|
||||
// RecordSyncDuration implements metricsImplementation.
|
||||
func (m *prometheusMetrics) RecordSyncDuration(ctx context.Context, agentInfo AgentInfo, duration time.Duration) {
|
||||
m.syncDuration.Observe(duration.Seconds())
|
||||
m.next.RecordSyncDuration(ctx, agentInfo, duration)
|
||||
}
|
||||
|
||||
// RecordSyncPhase implements metricsImplementation.
|
||||
func (m *prometheusMetrics) RecordSyncPhase(ctx context.Context, agentInfo AgentInfo, phase string, duration time.Duration) {
|
||||
m.syncPhaseDuration.WithLabelValues(phase).Observe(duration.Seconds())
|
||||
m.next.RecordSyncPhase(ctx, agentInfo, phase, duration)
|
||||
}
|
||||
|
||||
// RecordLoginDuration implements metricsImplementation.
|
||||
func (m *prometheusMetrics) RecordLoginDuration(ctx context.Context, agentInfo AgentInfo, duration time.Duration, success bool) {
|
||||
m.loginDuration.WithLabelValues(strconv.FormatBool(success)).Observe(duration.Seconds())
|
||||
m.next.RecordLoginDuration(ctx, agentInfo, duration, success)
|
||||
}
|
||||
|
||||
// Export implements metricsImplementation by delegating to the wrapped
|
||||
// implementation; Prometheus metrics are pulled via the registry instead.
|
||||
func (m *prometheusMetrics) Export(w io.Writer) error {
|
||||
return m.next.Export(w)
|
||||
}
|
||||
|
||||
// Reset implements metricsImplementation by delegating to the wrapped
|
||||
// implementation; Prometheus metrics must not be cleared on push.
|
||||
func (m *prometheusMetrics) Reset() {
|
||||
m.next.Reset()
|
||||
}
|
||||
@@ -1167,6 +1167,18 @@ func (d *Status) GetResolvedDomainsStates() map[domain.Domain]ResolvedDomainInfo
|
||||
return maps.Clone(d.resolvedDomainsStates)
|
||||
}
|
||||
|
||||
// GetPeerStates returns a snapshot of all known peer states, including offline peers.
|
||||
func (d *Status) GetPeerStates() []State {
|
||||
d.mux.RLock()
|
||||
defer d.mux.RUnlock()
|
||||
|
||||
states := make([]State, 0, d.numOfPeers())
|
||||
for _, state := range d.peers {
|
||||
states = append(states, state)
|
||||
}
|
||||
return append(states, d.offlinePeers...)
|
||||
}
|
||||
|
||||
// GetFullStatus gets full status
|
||||
func (d *Status) GetFullStatus() FullStatus {
|
||||
fullStatus := FullStatus{
|
||||
|
||||
@@ -129,6 +129,28 @@ func TestStatus_PeerStateByIP_RemovedPeer(t *testing.T) {
|
||||
req.False(ok, "removed peer must not resolve by IPv6 tunnel address")
|
||||
}
|
||||
|
||||
// TestStatus_GetPeerStates_IncludesOfflinePeers keeps the snapshot in line with
|
||||
// GetFullStatus: offline peers are known peers, so a consumer counting peers
|
||||
// must see the same total the status command reports.
|
||||
func TestStatus_GetPeerStates_IncludesOfflinePeers(t *testing.T) {
|
||||
status := NewRecorder("https://mgm")
|
||||
req := require.New(t)
|
||||
|
||||
req.NoError(status.AddPeer("pk-online", "online.netbird", "100.64.0.10", "fd00::1"))
|
||||
status.ReplaceOfflinePeers([]State{
|
||||
{PubKey: "pk-offline", FQDN: "offline.netbird", IP: "100.64.0.20", ConnStatus: StatusIdle},
|
||||
})
|
||||
|
||||
states := status.GetPeerStates()
|
||||
req.Len(states, 2, "snapshot must carry both the online and the offline peer")
|
||||
|
||||
keys := make([]string, 0, len(states))
|
||||
for _, s := range states {
|
||||
keys = append(keys, s.PubKey)
|
||||
}
|
||||
req.ElementsMatch([]string{"pk-online", "pk-offline"}, keys, "snapshot must carry both peers")
|
||||
}
|
||||
|
||||
func TestStatus_UpdatePeerFQDN(t *testing.T) {
|
||||
key := "abc"
|
||||
fqdn := "peer-a.netbird.local"
|
||||
|
||||
@@ -64,6 +64,9 @@ type WorkerICE struct {
|
||||
|
||||
// portForwardAttempted tracks if we've already tried port forwarding this session
|
||||
portForwardAttempted bool
|
||||
|
||||
// dialFunc, when non-nil, replaces agentDial in connect(). Only for tests.
|
||||
dialFunc func(ctx context.Context, agent *icemaker.ThreadSafeAgent, remoteOfferAnswer *OfferAnswer) (net.Conn, error)
|
||||
}
|
||||
|
||||
func NewWorkerICE(ctx context.Context, log *log.Entry, config ConnConfig, conn *Conn, signaler *Signaler, ifaceDiscover stdnet.ExternalIFaceDiscover, statusRecorder *Status, hasRelayOnLocally bool) (*WorkerICE, error) {
|
||||
@@ -123,7 +126,7 @@ func (w *WorkerICE) OnNewOffer(remoteOfferAnswer *OfferAnswer) {
|
||||
w.log.Errorf("failed to create new session ID: %s", err)
|
||||
}
|
||||
w.sessionID = sessionID
|
||||
w.agent = nil
|
||||
w.abandonNegotiation()
|
||||
}
|
||||
|
||||
var preferredCandidateTypes []ice.CandidateType
|
||||
@@ -151,7 +154,9 @@ func (w *WorkerICE) OnNewOffer(remoteOfferAnswer *OfferAnswer) {
|
||||
w.remoteSessionID = ""
|
||||
}
|
||||
|
||||
go w.connect(dialerCtx, agent, remoteOfferAnswer)
|
||||
// Capture the cancel func at spawn time: connect reads it from the argument
|
||||
// instead of the field, which a newer OnNewOffer may already have replaced.
|
||||
go w.connect(dialerCtx, dialerCancel, agent, remoteOfferAnswer)
|
||||
}
|
||||
|
||||
// OnRemoteCandidate Handles ICE connection Candidate provided by the remote peer.
|
||||
@@ -200,16 +205,16 @@ func (w *WorkerICE) Close() {
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
|
||||
if w.agent == nil {
|
||||
return
|
||||
if w.agent != nil {
|
||||
w.agentDialerCancel()
|
||||
if err := w.agent.Close(); err != nil {
|
||||
w.log.Warnf("failed to close ICE agent: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
w.agentDialerCancel()
|
||||
if err := w.agent.Close(); err != nil {
|
||||
w.log.Warnf("failed to close ICE agent: %s", err)
|
||||
}
|
||||
|
||||
w.agent = nil
|
||||
// Unconditional: a dial goroutine racing this Close skips its own cleanup
|
||||
// (closeAgent finds a nil agent), so the flags must be dropped here too or
|
||||
// the reconnection guard reads the stale state as Connected forever.
|
||||
w.abandonNegotiation()
|
||||
}
|
||||
|
||||
func (w *WorkerICE) reCreateAgent(dialerCancel context.CancelFunc, candidates []ice.CandidateType) (*icemaker.ThreadSafeAgent, error) {
|
||||
@@ -247,31 +252,52 @@ func (w *WorkerICE) SessionID() ICESessionID {
|
||||
// will block until connection succeeded
|
||||
// but it won't release if ICE Agent went into Disconnected or Failed state,
|
||||
// so we have to cancel it with the provided context once agent detected a broken connection
|
||||
func (w *WorkerICE) connect(ctx context.Context, agent *icemaker.ThreadSafeAgent, remoteOfferAnswer *OfferAnswer) {
|
||||
func (w *WorkerICE) connect(ctx context.Context, dialerCancel context.CancelFunc, agent *icemaker.ThreadSafeAgent, remoteOfferAnswer *OfferAnswer) {
|
||||
w.log.Debugf("gather candidates")
|
||||
if err := agent.GatherCandidates(); err != nil {
|
||||
w.log.Warnf("failed to gather candidates: %s", err)
|
||||
w.closeAgent(agent, w.agentDialerCancel)
|
||||
w.closeAgent(agent, dialerCancel)
|
||||
return
|
||||
}
|
||||
|
||||
w.log.Debugf("agent dial")
|
||||
remoteConn, err := w.agentDial(ctx, agent, remoteOfferAnswer)
|
||||
dial := func(ctx context.Context, agent *icemaker.ThreadSafeAgent, remoteOfferAnswer *OfferAnswer) (net.Conn, error) {
|
||||
return w.agentDial(ctx, agent, remoteOfferAnswer)
|
||||
}
|
||||
if w.dialFunc != nil {
|
||||
dial = w.dialFunc
|
||||
}
|
||||
remoteConn, err := dial(ctx, agent, remoteOfferAnswer)
|
||||
if err != nil {
|
||||
w.log.Debugf("failed to dial the remote peer: %s", err)
|
||||
w.closeAgent(agent, w.agentDialerCancel)
|
||||
w.closeAgent(agent, dialerCancel)
|
||||
return
|
||||
}
|
||||
w.log.Debugf("agent dial succeeded")
|
||||
|
||||
// A newer negotiation may have replaced our agent while agentDial was
|
||||
// blocked. Drop the dead connection before running pair retrieval, port
|
||||
// punching or candidate work against a closed agent. The commit-point
|
||||
// check below still guards a replacement arriving after this point.
|
||||
w.muxAgent.Lock()
|
||||
stale := w.agent != agent
|
||||
w.muxAgent.Unlock()
|
||||
if stale {
|
||||
if err := remoteConn.Close(); err != nil {
|
||||
w.log.Warnf("failed to close stale ICE connection: %s", err)
|
||||
}
|
||||
w.log.Warnf("discarding connection from a stale ICE negotiation")
|
||||
return
|
||||
}
|
||||
|
||||
pair, err := agent.GetSelectedCandidatePair()
|
||||
if err != nil {
|
||||
w.closeAgent(agent, w.agentDialerCancel)
|
||||
w.closeAgent(agent, dialerCancel)
|
||||
return
|
||||
}
|
||||
if pair == nil {
|
||||
w.log.Warnf("selected candidate pair is nil, cannot proceed")
|
||||
w.closeAgent(agent, w.agentDialerCancel)
|
||||
w.closeAgent(agent, dialerCancel)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -301,11 +327,27 @@ func (w *WorkerICE) connect(ctx context.Context, agent *icemaker.ThreadSafeAgent
|
||||
|
||||
w.log.Infof("connection succeeded with offer session: %s", remoteOfferAnswer.SessionIDString())
|
||||
w.muxAgent.Lock()
|
||||
// Authoritative ownership guard: a negotiation that lost w.agent to a newer
|
||||
// one between the post-dial check and the commit must not clear agentConnecting,
|
||||
// record lastSuccess or report the connection, so the state commit has to be
|
||||
// atomic with the check.
|
||||
if w.agent != agent {
|
||||
w.muxAgent.Unlock()
|
||||
if err := remoteConn.Close(); err != nil {
|
||||
w.log.Warnf("failed to close stale ICE connection: %s", err)
|
||||
}
|
||||
w.log.Warnf("discarding connection from a stale ICE negotiation")
|
||||
return
|
||||
}
|
||||
w.agentConnecting = false
|
||||
w.lastSuccess = time.Now()
|
||||
w.muxAgent.Unlock()
|
||||
|
||||
// todo: the potential problem is a race between the onConnectionStateChange
|
||||
// and the delivery below: after this unlock, a newer offer can replace
|
||||
// w.agent before onICEConnectionIsReady runs, delivering this (now stale)
|
||||
// connection. The newer negotiation overwrites it with its own delivery,
|
||||
// so the window only ever downgrades an endpoint transiently.
|
||||
w.conn.onICEConnectionIsReady(selectedPriority(pair), ci)
|
||||
}
|
||||
|
||||
@@ -321,20 +363,32 @@ func (w *WorkerICE) closeAgent(agent *icemaker.ThreadSafeAgent, cancel context.C
|
||||
sessionChanged := w.remoteSessionChanged
|
||||
w.remoteSessionChanged = false
|
||||
|
||||
// Only the owner of the current session may reset its state: a stale dial
|
||||
// goroutine waking after a newer attempt must not clobber it.
|
||||
if w.agent == agent {
|
||||
// consider to remove from here and move to the OnNewOffer
|
||||
sessionID, err := NewICESessionID()
|
||||
if err != nil {
|
||||
w.log.Errorf("failed to create new session ID: %s", err)
|
||||
}
|
||||
w.sessionID = sessionID
|
||||
w.agent = nil
|
||||
w.agentConnecting = false
|
||||
w.remoteSessionID = ""
|
||||
w.abandonNegotiation()
|
||||
}
|
||||
return sessionChanged
|
||||
}
|
||||
|
||||
// abandonNegotiation drops all recorded ICE session state so the worker treats the
|
||||
// next offer as a fresh start instead of a duplicate of a dead negotiation. The
|
||||
// agent and agentConnecting flags must change together: leaving one stale wedges
|
||||
// the reconnection guard into reporting Connected forever. It neither cancels an
|
||||
// in-flight dial nor closes an agent — callers dispose of those themselves first,
|
||||
// so a stale goroutine can never cancel another session's dial through this path.
|
||||
// Caller must hold muxAgent.
|
||||
func (w *WorkerICE) abandonNegotiation() {
|
||||
w.agent = nil
|
||||
w.agentConnecting = false
|
||||
w.remoteSessionID = ""
|
||||
}
|
||||
|
||||
func (w *WorkerICE) punchRemoteWGPort(pair *ice.CandidatePair, remoteWgPort int) {
|
||||
// wait local endpoint configuration
|
||||
time.Sleep(time.Second)
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package peer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||
|
||||
icemaker "github.com/netbirdio/netbird/client/internal/peer/ice"
|
||||
signal "github.com/netbirdio/netbird/shared/signal/client"
|
||||
sProto "github.com/netbirdio/netbird/shared/signal/proto"
|
||||
)
|
||||
|
||||
// stubSignalClient satisfies signal.Client as a no-op so the candidate
|
||||
// goroutine spawned by a real GatherCandidates never dereferences a nil
|
||||
// signaler in tests.
|
||||
type stubSignalClient struct{}
|
||||
|
||||
func (stubSignalClient) Close() error { return nil }
|
||||
func (stubSignalClient) StreamConnected() bool { return false }
|
||||
func (stubSignalClient) GetStatus() signal.Status { return signal.StreamDisconnected }
|
||||
func (stubSignalClient) Receive(context.Context, func(*sProto.Message) error) error { return nil }
|
||||
func (stubSignalClient) Ready() bool { return false }
|
||||
func (stubSignalClient) IsHealthy() bool { return false }
|
||||
func (stubSignalClient) WaitStreamConnected(context.Context) {}
|
||||
func (stubSignalClient) SendToStream(*sProto.EncryptedMessage) error { return nil }
|
||||
func (stubSignalClient) Send(*sProto.Message) error { return nil }
|
||||
func (stubSignalClient) SetOnReconnectedListener(func()) {}
|
||||
|
||||
// newTestWorkerICE builds a worker with real pion plumbing and no-op signaling.
|
||||
func newTestWorkerICE(t *testing.T) *WorkerICE {
|
||||
t.Helper()
|
||||
|
||||
config := connConf
|
||||
stunTurn := &icemaker.StunTurn{}
|
||||
stunTurn.Store(nil)
|
||||
config.ICEConfig.StunTurn = stunTurn
|
||||
|
||||
w, err := NewWorkerICE(context.Background(), log.WithField("test", t.Name()), config, nil,
|
||||
NewSignaler(stubSignalClient{}, wgtypes.Key{}), nil, nil, false)
|
||||
require.NoError(t, err, "worker setup must succeed")
|
||||
return w
|
||||
}
|
||||
|
||||
// TestWorkerICE_CloseDuringDial_ClearsConnectingFlag drives the teardown race
|
||||
// through the real dial goroutine instead of simulating its cleanup.
|
||||
//
|
||||
// The real-world sequence this models:
|
||||
// 1. OnNewOffer starts a negotiation: agent set, agentConnecting = true,
|
||||
// go connect()
|
||||
// 2. The network dies and connect() stays blocked inside GatherCandidates/Dial
|
||||
// 3. A WG handshake timeout calls Close(): the agent is released and the dial
|
||||
// context cancelled, but agentConnecting is not reset
|
||||
// 4. The real goroutine wakes with an error and runs its own cleanup
|
||||
// (closeAgent), where `w.agent == agent` is now false, so the flag reset
|
||||
// is skipped
|
||||
//
|
||||
// There is no remote responder, so Dial can never succeed: whatever point the
|
||||
// goroutine is at, closing first forces it down the error path. Before the fix
|
||||
// the flag stays true forever and the deadline below expires.
|
||||
func TestWorkerICE_CloseDuringDial_ClearsConnectingFlag(t *testing.T) {
|
||||
w := newTestWorkerICE(t)
|
||||
|
||||
sid := ICESessionID("test-session-id")
|
||||
w.OnNewOffer(&OfferAnswer{
|
||||
IceCredentials: IceCredentials{
|
||||
UFrag: "testufrag",
|
||||
Pwd: "testpwdtestpwdtestpwd12",
|
||||
},
|
||||
SessionID: &sid,
|
||||
})
|
||||
require.True(t, w.InProgress(), "OnNewOffer must mark the negotiation as in progress")
|
||||
|
||||
// Teardown wins the race while connect() is still running.
|
||||
w.Close()
|
||||
|
||||
// Close drops the flags synchronously, so the assertion below does not
|
||||
// converge on the goroutine: the deadline only absorbs the dial goroutine
|
||||
// waking up in the background, proving nothing re-wedges it afterwards.
|
||||
require.Eventually(t, func() bool {
|
||||
return !w.InProgress()
|
||||
}, 10*time.Second, 50*time.Millisecond,
|
||||
"Close must leave the negotiation idle even while the dial goroutine is still winding down")
|
||||
|
||||
// abandonNegotiation owns these three fields together; the worker is idle
|
||||
// only when all of them are dropped.
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
assert.Nil(t, w.agent, "no agent may survive the teardown")
|
||||
assert.False(t, w.agentConnecting, "the connecting flag must match the nil agent")
|
||||
assert.Empty(t, w.remoteSessionID, "a dead session's remote ID must not linger")
|
||||
}
|
||||
|
||||
// TestWorkerICE_CloseClearsResidualConnectingState covers Close on a worker whose
|
||||
// agent is already gone but whose flag is stuck on true, e.g. after an aborted
|
||||
// recreate in OnNewOffer or after a first Close raced a dial goroutine.
|
||||
func TestWorkerICE_CloseClearsResidualConnectingState(t *testing.T) {
|
||||
w := newTestWorkerICE(t)
|
||||
|
||||
w.muxAgent.Lock()
|
||||
w.agentConnecting = true
|
||||
w.muxAgent.Unlock()
|
||||
|
||||
w.Close()
|
||||
|
||||
assert.False(t, w.InProgress(), "Close must drop residual connecting state even without a live agent")
|
||||
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
assert.Nil(t, w.agent)
|
||||
assert.False(t, w.agentConnecting)
|
||||
assert.Empty(t, w.remoteSessionID)
|
||||
}
|
||||
|
||||
// TestWorkerICE_StaleCloseAgentKeepsCurrentSession pins the ownership guard in
|
||||
// closeAgent: a late-waking dial goroutine from an older session must not reset
|
||||
// the state of a newer negotiation that reused the worker. The newer session
|
||||
// must survive wholesale - agent, flag and remote session identity alike.
|
||||
func TestWorkerICE_StaleCloseAgentKeepsCurrentSession(t *testing.T) {
|
||||
w := newTestWorkerICE(t)
|
||||
t.Cleanup(w.Close)
|
||||
|
||||
sidA := ICESessionID("session-a")
|
||||
w.OnNewOffer(&OfferAnswer{
|
||||
IceCredentials: IceCredentials{UFrag: "ufragaaaa", Pwd: "pwdpwdpwdpwdpwdpwdpwdp1"},
|
||||
SessionID: &sidA,
|
||||
})
|
||||
w.muxAgent.Lock()
|
||||
oldAgent := w.agent
|
||||
oldCancel := w.agentDialerCancel
|
||||
w.muxAgent.Unlock()
|
||||
require.NotNil(t, oldAgent, "OnNewOffer must have created an ICE agent")
|
||||
|
||||
w.Close()
|
||||
|
||||
sidB := ICESessionID("session-b")
|
||||
w.OnNewOffer(&OfferAnswer{
|
||||
IceCredentials: IceCredentials{UFrag: "ufragbbbb", Pwd: "pwdpwdpwdpwdpwdpwdpwdp2"},
|
||||
SessionID: &sidB,
|
||||
})
|
||||
require.True(t, w.InProgress(), "the second negotiation must be in flight")
|
||||
|
||||
w.muxAgent.Lock()
|
||||
newAgent := w.agent
|
||||
w.muxAgent.Unlock()
|
||||
|
||||
// The old dial goroutine finally wakes and cleans up its captured agent.
|
||||
w.closeAgent(oldAgent, oldCancel)
|
||||
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
assert.Same(t, newAgent, w.agent, "the current agent must be untouched by the stale cleanup")
|
||||
assert.True(t, w.agentConnecting, "the current negotiation must stay in flight")
|
||||
// Read live under the lock: a snapshot captured before the stale cleanup
|
||||
// would pass even if the cleanup wiped current state.
|
||||
assert.Equal(t, sidB, w.remoteSessionID, "the remote session identity must be preserved")
|
||||
}
|
||||
|
||||
// closeTrackConn records Close calls so a test can assert that a discarded
|
||||
// connection was actually released.
|
||||
type closeTrackConn struct {
|
||||
net.Conn
|
||||
closed atomic.Bool
|
||||
}
|
||||
|
||||
func (c *closeTrackConn) Close() error {
|
||||
c.closed.Store(true)
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// TestWorkerICE_StaleDialSuccessKeepsNewerNegotiation pins the ownership guard
|
||||
// in connect()'s success path: a dial that came back after a newer negotiation
|
||||
// replaced the agent must discard its connection and leave the newer session's
|
||||
// state - agent, agentConnecting, remoteSessionID, lastSuccess - intact.
|
||||
//
|
||||
// The dial hook holds session A's goroutine open until session B is installed,
|
||||
// then returns a live connection, mimicking the vendored pion dial which hands
|
||||
// out a live *ice.Conn when a pair is selected without checking afterwards
|
||||
// whether the agent was replaced meanwhile. Releasing A's dial therefore
|
||||
// exercises the stale-success commit path deterministically instead of racing
|
||||
// real ICE.
|
||||
func TestWorkerICE_StaleDialSuccessKeepsNewerNegotiation(t *testing.T) {
|
||||
w := newTestWorkerICE(t)
|
||||
t.Cleanup(w.Close)
|
||||
|
||||
dialStarted := make(chan struct{})
|
||||
releaseDial := make(chan struct{})
|
||||
staleConn := &closeTrackConn{}
|
||||
|
||||
var calls atomic.Int32
|
||||
w.dialFunc = func(ctx context.Context, _ *icemaker.ThreadSafeAgent, _ *OfferAnswer) (net.Conn, error) {
|
||||
if calls.Add(1) == 1 {
|
||||
// Session A: hold the goroutine open until session B is installed,
|
||||
// then return a live connection, mimicking the vendored pion dial
|
||||
// which hands out a live *ice.Conn once a pair is selected without
|
||||
// re-checking whether the agent was replaced meanwhile. Releasing
|
||||
// the dial therefore exercises the stale-success commit path
|
||||
// deterministically instead of racing real ICE.
|
||||
close(dialStarted)
|
||||
<-releaseDial
|
||||
client, _ := net.Pipe()
|
||||
staleConn.Conn = client
|
||||
return staleConn, nil
|
||||
}
|
||||
// A newer negotiation parks on its dialer context, cancelled by the
|
||||
// t.Cleanup Close at test end.
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
sidA := ICESessionID("session-a")
|
||||
w.OnNewOffer(&OfferAnswer{
|
||||
IceCredentials: IceCredentials{UFrag: "ufragaaaa", Pwd: "pwdpwdpwdpwdpwdpwdpwdp1"},
|
||||
SessionID: &sidA,
|
||||
})
|
||||
require.True(t, w.InProgress(), "session A must be in flight")
|
||||
|
||||
// Session A's goroutine is now parked in the dial hook.
|
||||
<-dialStarted
|
||||
|
||||
sidB := ICESessionID("session-b")
|
||||
w.OnNewOffer(&OfferAnswer{
|
||||
IceCredentials: IceCredentials{UFrag: "ufragbbbb", Pwd: "pwdpwdpwdpwdpwdpwdpwdp2"},
|
||||
SessionID: &sidB,
|
||||
})
|
||||
|
||||
w.muxAgent.Lock()
|
||||
agentB := w.agent
|
||||
w.lastSuccess = time.Time{}
|
||||
w.muxAgent.Unlock()
|
||||
require.NotNil(t, agentB, "session B must have created an ICE agent")
|
||||
require.True(t, w.InProgress(), "session B must be in flight")
|
||||
|
||||
// Release session A's dial: it must be recognized as stale and discarded.
|
||||
close(releaseDial)
|
||||
require.Eventually(t, func() bool {
|
||||
return staleConn.closed.Load()
|
||||
}, 10*time.Second, 10*time.Millisecond,
|
||||
"the stale connection must be closed by the ownership guard")
|
||||
|
||||
w.muxAgent.Lock()
|
||||
defer w.muxAgent.Unlock()
|
||||
assert.Same(t, agentB, w.agent, "session A must not uninstall session B's agent")
|
||||
assert.True(t, w.agentConnecting, "session A must not clear session B's connecting flag")
|
||||
assert.Equal(t, sidB, w.remoteSessionID, "session A must not clear session B's remote session identity")
|
||||
assert.True(t, w.lastSuccess.IsZero(), "session A must not record a success for session B")
|
||||
// The commit block guards agentConnecting, lastSuccess and
|
||||
// onICEConnectionIsReady together, so the state assertions above imply the
|
||||
// callback never ran for session A; the nil conn would have panicked the
|
||||
// stale goroutine on any invocation.
|
||||
}
|
||||
@@ -70,6 +70,7 @@ type ConfigInput struct {
|
||||
StateFilePath string
|
||||
PreSharedKey *string
|
||||
ServerSSHAllowed *bool
|
||||
RemoteJobsAllowed *bool
|
||||
EnableSSHRoot *bool
|
||||
EnableSSHSFTP *bool
|
||||
EnableSSHLocalPortForwarding *bool
|
||||
@@ -103,6 +104,9 @@ type ConfigInput struct {
|
||||
DNSLabels domain.List
|
||||
|
||||
MTU *uint16
|
||||
|
||||
LocalMetricsEnabled *bool
|
||||
LocalMetricsAddress *string
|
||||
}
|
||||
|
||||
// Config Configuration type
|
||||
@@ -124,6 +128,7 @@ type Config struct {
|
||||
RosenpassEnabled bool
|
||||
RosenpassPermissive bool
|
||||
ServerSSHAllowed *bool
|
||||
RemoteJobsAllowed *bool
|
||||
EnableSSHRoot *bool
|
||||
EnableSSHSFTP *bool
|
||||
EnableSSHLocalPortForwarding *bool
|
||||
@@ -144,6 +149,11 @@ type Config struct {
|
||||
|
||||
DNSLabels domain.List
|
||||
|
||||
// LocalMetricsEnabled enables the local Prometheus /metrics endpoint.
|
||||
LocalMetricsEnabled bool
|
||||
// LocalMetricsAddress is the listen address of the local /metrics endpoint.
|
||||
LocalMetricsAddress string
|
||||
|
||||
// SSHKey is a private SSH key in a PEM format
|
||||
SSHKey string
|
||||
|
||||
@@ -184,6 +194,12 @@ type Config struct {
|
||||
// Runtime-only: re-derived from MDM policy on each load, never persisted.
|
||||
LazyConnection string `json:"-"`
|
||||
|
||||
// DebugBundleUploadURL is the MDM-managed debug-bundle upload URL override.
|
||||
// When set, it takes precedence over the management-supplied upload URL for
|
||||
// remote debug bundle jobs. Runtime-only: re-derived from MDM policy on each
|
||||
// load, never persisted.
|
||||
DebugBundleUploadURL string `json:"-"`
|
||||
|
||||
MTU uint16
|
||||
|
||||
// policy is the MDM policy that produced the currently-set values for
|
||||
@@ -217,6 +233,12 @@ func getConfigDir() (string, error) {
|
||||
}
|
||||
|
||||
configDir := filepath.Join(base, "netbird")
|
||||
// Under sudo this is the invoking user's directory and strictly read-only:
|
||||
// anything root creates in it would be root-owned and break the user's own
|
||||
// runs. Reads of a missing directory fall through to defaults.
|
||||
if sudoActive() {
|
||||
return configDir, nil
|
||||
}
|
||||
if err := os.MkdirAll(configDir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -224,6 +246,16 @@ func getConfigDir() (string, error) {
|
||||
}
|
||||
|
||||
func baseConfigDir() (string, error) {
|
||||
if u, ok := sudoInvokingUser(); ok {
|
||||
return userBaseConfigDir(u)
|
||||
}
|
||||
// Fail closed instead of falling through to root's own config directory:
|
||||
// reading root's active-profile and email state for what is actually the
|
||||
// invoking user's invocation is the very confusion this resolution exists
|
||||
// to prevent.
|
||||
if sudoActive() {
|
||||
return "", fmt.Errorf("resolve sudo invoking user %q: refusing to fall back to root's config directory", os.Getenv(envSudoUser))
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
if u, err := user.Current(); err == nil && u.HomeDir != "" {
|
||||
return filepath.Join(u.HomeDir, "Library", "Application Support"), nil
|
||||
@@ -265,7 +297,10 @@ func createNewConfig(input ConfigInput) (*Config, error) {
|
||||
config := &Config{
|
||||
// defaults to false only for new (post 0.26) configurations
|
||||
ServerSSHAllowed: util.False(),
|
||||
WgPort: iface.DefaultWgPort,
|
||||
// Remote jobs are an explicit opt-in and default off, including for
|
||||
// legacy configs (a nil value materializes to false at connect time).
|
||||
RemoteJobsAllowed: util.False(),
|
||||
WgPort: iface.DefaultWgPort,
|
||||
}
|
||||
|
||||
if _, err := config.apply(input); err != nil {
|
||||
@@ -388,6 +423,18 @@ func (config *Config) apply(input ConfigInput) (updated bool, err error) {
|
||||
updated = true
|
||||
}
|
||||
|
||||
if input.LocalMetricsEnabled != nil && *input.LocalMetricsEnabled != config.LocalMetricsEnabled {
|
||||
log.Infof("switching local metrics to %t", *input.LocalMetricsEnabled)
|
||||
config.LocalMetricsEnabled = *input.LocalMetricsEnabled
|
||||
updated = true
|
||||
}
|
||||
|
||||
if input.LocalMetricsAddress != nil && *input.LocalMetricsAddress != config.LocalMetricsAddress {
|
||||
log.Infof("switching local metrics address to %s", *input.LocalMetricsAddress)
|
||||
config.LocalMetricsAddress = *input.LocalMetricsAddress
|
||||
updated = true
|
||||
}
|
||||
|
||||
if input.NetworkMonitor != nil && (config.NetworkMonitor == nil || *input.NetworkMonitor != *config.NetworkMonitor) {
|
||||
log.Infof("switching Network Monitor to %t", *input.NetworkMonitor)
|
||||
config.NetworkMonitor = input.NetworkMonitor
|
||||
@@ -456,6 +503,21 @@ func (config *Config) apply(input ConfigInput) (updated bool, err error) {
|
||||
updated = true
|
||||
}
|
||||
|
||||
if input.RemoteJobsAllowed != nil && (config.RemoteJobsAllowed == nil || *input.RemoteJobsAllowed != *config.RemoteJobsAllowed) {
|
||||
if *input.RemoteJobsAllowed {
|
||||
log.Infof("enabling remote jobs")
|
||||
} else {
|
||||
log.Infof("disabling remote jobs")
|
||||
}
|
||||
config.RemoteJobsAllowed = input.RemoteJobsAllowed
|
||||
updated = true
|
||||
} else if config.RemoteJobsAllowed == nil {
|
||||
// Remote jobs are an explicit opt-in: unlike SSH, a pre-existing config
|
||||
// with no value defaults to disabled rather than being turned on.
|
||||
config.RemoteJobsAllowed = util.False()
|
||||
updated = true
|
||||
}
|
||||
|
||||
if input.EnableSSHRoot != nil && (config.EnableSSHRoot == nil || *input.EnableSSHRoot != *config.EnableSSHRoot) {
|
||||
if *input.EnableSSHRoot {
|
||||
log.Infof("enabling SSH root login")
|
||||
@@ -665,6 +727,14 @@ func (config *Config) apply(input ConfigInput) (updated bool, err error) {
|
||||
// for the key, so per-field rejection of user writes still applies).
|
||||
func (config *Config) applyMDMPolicy(policy *mdm.Policy) {
|
||||
config.policy = policy
|
||||
|
||||
// DebugBundleUploadURL is a runtime-only override re-derived from MDM on
|
||||
// every apply. Resolve it unconditionally (before the IsEmpty early return)
|
||||
// so a policy that drops the key, becomes empty, or carries an invalid
|
||||
// value can never leave a previously-enforced upload target active on a
|
||||
// reused Config instance.
|
||||
config.DebugBundleUploadURL = mdmDebugBundleUploadURL(policy)
|
||||
|
||||
if policy.IsEmpty() {
|
||||
return
|
||||
}
|
||||
@@ -712,12 +782,19 @@ func (config *Config) applyMDMPolicy(policy *mdm.Policy) {
|
||||
}
|
||||
|
||||
applyBool(mdm.KeyAllowServerSSH, func(v bool) { bv := v; config.ServerSSHAllowed = &bv })
|
||||
applyBool(mdm.KeyRemoteJobsAllowed, func(v bool) { bv := v; config.RemoteJobsAllowed = &bv })
|
||||
applyBool(mdm.KeyDisableClientRoutes, func(v bool) { config.DisableClientRoutes = v })
|
||||
applyBool(mdm.KeyDisableServerRoutes, func(v bool) { config.DisableServerRoutes = v })
|
||||
applyBool(mdm.KeyBlockInbound, func(v bool) { config.BlockInbound = v })
|
||||
applyBool(mdm.KeyDisableAutoConnect, func(v bool) { config.DisableAutoConnect = v })
|
||||
applyBool(mdm.KeyRosenpassEnabled, func(v bool) { config.RosenpassEnabled = v })
|
||||
applyBool(mdm.KeyRosenpassPermissive, func(v bool) { config.RosenpassPermissive = v })
|
||||
applyBool(mdm.KeyEnableLocalMetrics, func(v bool) { config.LocalMetricsEnabled = v })
|
||||
|
||||
if v, ok := policy.GetString(mdm.KeyLocalMetricsAddress); ok {
|
||||
config.LocalMetricsAddress = v
|
||||
logApplied(mdm.KeyLocalMetricsAddress, v)
|
||||
}
|
||||
|
||||
if v, ok := policy.GetInt(mdm.KeyWireguardPort); ok {
|
||||
// REG_DWORD is 32-bit; UDP port range is 1-65535. Clamp at the
|
||||
@@ -739,6 +816,52 @@ func (config *Config) applyMDMPolicy(policy *mdm.Policy) {
|
||||
config.LazyConnection = state
|
||||
logApplied(mdm.KeyLazyConnection, state)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// ValidateBundleUploadURL sanity-checks a debug-bundle upload URL. An empty
|
||||
// value is accepted — the executor falls back to the default upload service. A
|
||||
// non-empty value must be a well-formed https URL with a host; a malformed
|
||||
// value or a plaintext scheme is rejected. It deliberately does not constrain
|
||||
// which host may receive the bundle. This is the single source of truth for the
|
||||
// rule, shared by the remote-job executor (client/internal) and the MDM policy
|
||||
// override below so the two validation paths cannot drift.
|
||||
func ValidateBundleUploadURL(raw string) error {
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse upload URL: %w", err)
|
||||
}
|
||||
// Hostname(), not Host: an authority like ":443" is non-empty but has no
|
||||
// host, and would fail the actual upload.
|
||||
if parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return fmt.Errorf("upload URL must be an https URL with a host")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mdmDebugBundleUploadURL resolves the MDM-enforced debug-bundle upload URL
|
||||
// override from the policy, returning the empty string when the policy does
|
||||
// not carry a valid KeyBundleUploadURL. An absent or invalid value fails
|
||||
// closed to "" so it falls back to the management-supplied or default upload
|
||||
// target rather than a previously-enforced one. The URL is never logged: it
|
||||
// can embed credentials or signed query tokens (KeyBundleUploadURL is in
|
||||
// mdm.SecretKeys).
|
||||
func mdmDebugBundleUploadURL(policy *mdm.Policy) string {
|
||||
v, ok := policy.GetString(mdm.KeyBundleUploadURL)
|
||||
if !ok || v == "" {
|
||||
return ""
|
||||
}
|
||||
// Must be a well-formed https URL with a host, matching the client's
|
||||
// remote-job upload-URL validation (shared validator, single source of truth).
|
||||
if err := ValidateBundleUploadURL(v); err != nil {
|
||||
log.Warnf("MDM debug bundle upload URL is invalid (must be an https URL with a host); ignoring the override")
|
||||
return ""
|
||||
}
|
||||
log.Infof("MDM override %s = ********** (secret)", mdm.KeyBundleUploadURL)
|
||||
return v
|
||||
}
|
||||
|
||||
// parseURL parses and validates the URL for the named service. The URL
|
||||
|
||||
@@ -130,6 +130,32 @@ func TestApply_MDMBoolKeysOverrideOnDiskValue(t *testing.T) {
|
||||
assert.True(t, cfg.Policy().HasKey(mdm.KeyRosenpassEnabled))
|
||||
}
|
||||
|
||||
func TestApply_MDMLocalMetrics(t *testing.T) {
|
||||
tmp := filepath.Join(t.TempDir(), "config.json")
|
||||
|
||||
// Seed without MDM.
|
||||
withMDMPolicy(t, mdm.NewPolicy(nil))
|
||||
_, err := UpdateOrCreateConfig(ConfigInput{
|
||||
ConfigPath: tmp,
|
||||
LocalMetricsEnabled: boolPtr(false),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
withMDMPolicy(t, mdm.NewPolicy(map[string]any{
|
||||
mdm.KeyEnableLocalMetrics: true,
|
||||
mdm.KeyLocalMetricsAddress: "127.0.0.1:9292",
|
||||
}))
|
||||
|
||||
cfg, err := UpdateOrCreateConfig(ConfigInput{ConfigPath: tmp})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cfg)
|
||||
|
||||
assert.True(t, cfg.LocalMetricsEnabled, "MDM override should flip on-disk false to true")
|
||||
assert.Equal(t, "127.0.0.1:9292", cfg.LocalMetricsAddress)
|
||||
assert.True(t, cfg.Policy().HasKey(mdm.KeyEnableLocalMetrics))
|
||||
assert.True(t, cfg.Policy().HasKey(mdm.KeyLocalMetricsAddress))
|
||||
}
|
||||
|
||||
func TestApply_MDMLazyConnection(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/netbirdio/netbird/client/iface"
|
||||
"github.com/netbirdio/netbird/client/internal/routemanager/dynamic"
|
||||
"github.com/netbirdio/netbird/client/mdm"
|
||||
"github.com/netbirdio/netbird/util"
|
||||
)
|
||||
|
||||
@@ -271,6 +272,83 @@ func TestUpdateConfigServerSSHAllowedNotSet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateConfigRemoteJobsAllowed(t *testing.T) {
|
||||
// Unlike SSH (which defaults on for legacy configs), remote jobs are an
|
||||
// explicit opt-in: a pre-existing config with no value materializes to off.
|
||||
t.Run("legacy config defaults off", func(t *testing.T) {
|
||||
configPath := filepath.Join(t.TempDir(), "config.json")
|
||||
require.NoError(t, os.WriteFile(configPath, []byte("{}"), 0600))
|
||||
|
||||
config, err := UpdateConfig(ConfigInput{ConfigPath: configPath})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, config.RemoteJobsAllowed, "RemoteJobsAllowed should be materialized")
|
||||
assert.False(t, *config.RemoteJobsAllowed, "remote jobs must default off")
|
||||
})
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
input *bool
|
||||
want bool
|
||||
}{
|
||||
{"enable", util.True(), true},
|
||||
{"disable", util.False(), false},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
configPath := filepath.Join(t.TempDir(), "config.json")
|
||||
require.NoError(t, os.WriteFile(configPath, []byte("{}"), 0600))
|
||||
|
||||
config, err := UpdateConfig(ConfigInput{ConfigPath: configPath, RemoteJobsAllowed: tt.input})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, config.RemoteJobsAllowed)
|
||||
assert.Equal(t, tt.want, *config.RemoteJobsAllowed)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyMDMPolicyRemoteJobs(t *testing.T) {
|
||||
t.Run("enables remote jobs and sets the upload URL override", func(t *testing.T) {
|
||||
cfg := &Config{}
|
||||
cfg.applyMDMPolicy(mdm.NewPolicy(map[string]any{
|
||||
mdm.KeyRemoteJobsAllowed: true,
|
||||
mdm.KeyBundleUploadURL: "https://upload.example.com",
|
||||
}))
|
||||
require.NotNil(t, cfg.RemoteJobsAllowed)
|
||||
assert.True(t, *cfg.RemoteJobsAllowed, "MDM allowRemoteJobs must enable the flag")
|
||||
assert.Equal(t, "https://upload.example.com", cfg.DebugBundleUploadURL, "MDM upload URL override must be applied")
|
||||
})
|
||||
|
||||
t.Run("a non-https upload URL is rejected", func(t *testing.T) {
|
||||
cfg := &Config{}
|
||||
cfg.applyMDMPolicy(mdm.NewPolicy(map[string]any{
|
||||
mdm.KeyBundleUploadURL: "http://insecure.example.com",
|
||||
}))
|
||||
assert.Empty(t, cfg.DebugBundleUploadURL, "a non-https upload URL must be skipped")
|
||||
})
|
||||
|
||||
t.Run("dropping the key clears a previously-applied override", func(t *testing.T) {
|
||||
cfg := &Config{DebugBundleUploadURL: "https://old.example.com"}
|
||||
// A replacement policy that no longer carries the key must not leave
|
||||
// the old upload target directing bundles.
|
||||
cfg.applyMDMPolicy(mdm.NewPolicy(map[string]any{mdm.KeyRemoteJobsAllowed: true}))
|
||||
assert.Empty(t, cfg.DebugBundleUploadURL, "the stale upload URL override must be cleared")
|
||||
})
|
||||
|
||||
t.Run("an empty replacement policy clears a previously-applied override", func(t *testing.T) {
|
||||
cfg := &Config{DebugBundleUploadURL: "https://old.example.com"}
|
||||
// A policy that becomes empty entirely hits the IsEmpty early return;
|
||||
// the override must still be cleared rather than surviving on the
|
||||
// reused Config instance.
|
||||
cfg.applyMDMPolicy(mdm.NewPolicy(map[string]any{}))
|
||||
assert.Empty(t, cfg.DebugBundleUploadURL, "the stale upload URL override must be cleared when the policy empties")
|
||||
})
|
||||
|
||||
t.Run("an invalid upload URL clears a previously-applied override (fail closed)", func(t *testing.T) {
|
||||
cfg := &Config{DebugBundleUploadURL: "https://old.example.com"}
|
||||
cfg.applyMDMPolicy(mdm.NewPolicy(map[string]any{mdm.KeyBundleUploadURL: "not-a-url"}))
|
||||
assert.Empty(t, cfg.DebugBundleUploadURL, "an invalid override must fail closed, not keep the stale target")
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateOldManagementURL(t *testing.T) {
|
||||
origProber := newMgmProber
|
||||
newMgmProber = func(_ context.Context, _ string, _ wgtypes.Key, _ bool) (mgmProber, error) {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package profilemanager
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const envSudoUser = "SUDO_USER"
|
||||
|
||||
var (
|
||||
geteuid = os.Geteuid
|
||||
lookupUser = user.Lookup
|
||||
)
|
||||
|
||||
// InvokingUser returns the user a CLI invocation acts for. Under sudo that is
|
||||
// the user who ran sudo, not root: privileged flags force commands through
|
||||
// sudo, and resolving profiles as root would silently switch the daemon to
|
||||
// root's (default) profile instead of the invoking user's. Privilege decisions
|
||||
// are not made here — those stay on the kernel credentials of the daemon
|
||||
// connection, which SUDO_USER (a plain environment variable) can never
|
||||
// influence; a forged value only selects a profile root could select anyway.
|
||||
func InvokingUser() (*user.User, error) {
|
||||
if u, ok := sudoInvokingUser(); ok {
|
||||
return u, nil
|
||||
}
|
||||
// Fail closed instead of falling through to root: every caller feeds this
|
||||
// username into profile-path resolution, so a lookup failure would resolve
|
||||
// (and create) a root-owned profile namespace and switch the daemon onto it
|
||||
// behind the invoking user's back.
|
||||
if sudoActive() {
|
||||
return nil, fmt.Errorf("resolve sudo invoking user %q: refusing to fall back to root", os.Getenv(envSudoUser))
|
||||
}
|
||||
return user.Current()
|
||||
}
|
||||
|
||||
// IsPlainRoot reports that the process runs as root with no usable sudo
|
||||
// context: there is no invoking user to act for, so per-user resolution falls
|
||||
// back to root's own (empty) state. Callers use it to refuse ambiguous
|
||||
// operations instead of silently acting on the wrong profile.
|
||||
func IsPlainRoot() bool {
|
||||
if geteuid() != 0 {
|
||||
return false
|
||||
}
|
||||
_, ok := sudoInvokingUser()
|
||||
return !ok
|
||||
}
|
||||
|
||||
// MirrorIsAuthoritative reports whether the invoking user's local
|
||||
// active-profile mirror can be trusted as the profile selector. It cannot under
|
||||
// sudo (writes to it are skipped, so it goes stale) or as plain root (there is
|
||||
// no invoking user, so it falls back to root's own default). Callers use it to
|
||||
// decide whether to read the profile from the mirror or from the daemon.
|
||||
func MirrorIsAuthoritative() bool {
|
||||
return !sudoActive() && !IsPlainRoot()
|
||||
}
|
||||
|
||||
// sudoInvokingUser resolves SUDO_USER when the process runs as root under
|
||||
// sudo. Returns false whenever the sudo context is absent or unusable, in
|
||||
// which case callers fall back to the process user.
|
||||
func sudoInvokingUser() (*user.User, bool) {
|
||||
if !sudoActive() {
|
||||
return nil, false
|
||||
}
|
||||
name := os.Getenv(envSudoUser)
|
||||
u, err := lookupUser(name)
|
||||
if err != nil {
|
||||
log.Warnf("sudo invoking user %q lookup: %v", name, err)
|
||||
return nil, false
|
||||
}
|
||||
return u, true
|
||||
}
|
||||
|
||||
// sudoActive reports a sudo context from the environment alone: write-skip
|
||||
// decisions key off it so a transient user lookup failure can never flip a
|
||||
// run from read-only to writing root-owned files into the user's directory.
|
||||
func sudoActive() bool {
|
||||
if geteuid() != 0 {
|
||||
return false
|
||||
}
|
||||
name := os.Getenv(envSudoUser)
|
||||
return name != "" && name != "root"
|
||||
}
|
||||
|
||||
// userBaseConfigDir mirrors os.UserConfigDir for a user other than the process
|
||||
// owner. Environment overrides (XDG_CONFIG_HOME) cannot be honoured here: under
|
||||
// sudo the environment is root's, not the invoking user's.
|
||||
func userBaseConfigDir(u *user.User) (string, error) {
|
||||
if u.HomeDir == "" {
|
||||
return "", fmt.Errorf("user %s has no home directory", u.Username)
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
return filepath.Join(u.HomeDir, "Library", "Application Support"), nil
|
||||
}
|
||||
return filepath.Join(u.HomeDir, ".config"), nil
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package profilemanager
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestInvokingUserFallsBackToProcessUser(t *testing.T) {
|
||||
t.Setenv(envSudoUser, "")
|
||||
|
||||
got, err := InvokingUser()
|
||||
require.NoError(t, err)
|
||||
|
||||
current, err := user.Current()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, current.Username, got.Username)
|
||||
}
|
||||
|
||||
func TestSudoInvokingUserInactiveWithoutSudoContext(t *testing.T) {
|
||||
t.Setenv(envSudoUser, "")
|
||||
_, ok := sudoInvokingUser()
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestSudoInvokingUserIgnoresRoot(t *testing.T) {
|
||||
t.Setenv(envSudoUser, "root")
|
||||
origEuid := geteuid
|
||||
geteuid = func() int { return 0 }
|
||||
t.Cleanup(func() { geteuid = origEuid })
|
||||
|
||||
_, ok := sudoInvokingUser()
|
||||
assert.False(t, ok, "sudo from a root shell must not redirect anything")
|
||||
assert.False(t, sudoActive())
|
||||
assert.True(t, IsPlainRoot())
|
||||
}
|
||||
|
||||
func TestSudoInvokingUserResolvesInvokingUser(t *testing.T) {
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
|
||||
u, ok := sudoInvokingUser()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "misha", u.Username)
|
||||
|
||||
got, err := InvokingUser()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "misha", got.Username)
|
||||
|
||||
assert.False(t, IsPlainRoot())
|
||||
}
|
||||
|
||||
func TestInvokingUserFailsClosedWhenSudoLookupFails(t *testing.T) {
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
lookupUser = func(string) (*user.User, error) { return nil, errors.New("nss unavailable") }
|
||||
|
||||
got, err := InvokingUser()
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, got, "must not resolve to the root process user")
|
||||
}
|
||||
|
||||
func TestProfileFilePathFailsClosedWhenSudoLookupFails(t *testing.T) {
|
||||
profilesRoot := t.TempDir()
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
lookupUser = func(string) (*user.User, error) { return nil, errors.New("nss unavailable") }
|
||||
|
||||
origDir := DefaultConfigPathDir
|
||||
DefaultConfigPathDir = profilesRoot
|
||||
t.Cleanup(func() { DefaultConfigPathDir = origDir })
|
||||
|
||||
p := &Profile{ID: "0123456789abcdef0123456789abcdef"}
|
||||
_, err := p.FilePath()
|
||||
require.Error(t, err)
|
||||
assertNoEntries(t, profilesRoot)
|
||||
}
|
||||
|
||||
func TestSudoActiveSurvivesLookupFailure(t *testing.T) {
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
lookupUser = func(string) (*user.User, error) { return nil, errors.New("nss unavailable") }
|
||||
|
||||
_, ok := sudoInvokingUser()
|
||||
assert.False(t, ok)
|
||||
assert.True(t, sudoActive())
|
||||
assert.True(t, IsPlainRoot())
|
||||
}
|
||||
|
||||
func TestGetConfigDirUnderSudoIsReadOnly(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
fakeSudo(t, home)
|
||||
|
||||
base, err := baseConfigDir()
|
||||
require.NoError(t, err)
|
||||
if runtime.GOOS == "darwin" {
|
||||
assert.Equal(t, filepath.Join(home, "Library", "Application Support"), base)
|
||||
} else {
|
||||
assert.Equal(t, filepath.Join(home, ".config"), base)
|
||||
}
|
||||
|
||||
dir, err := getConfigDir()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, filepath.Join(base, "netbird"), dir)
|
||||
assert.NoDirExists(t, dir)
|
||||
}
|
||||
|
||||
func TestBaseConfigDirFailsClosedWhenSudoLookupFails(t *testing.T) {
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
lookupUser = func(string) (*user.User, error) { return nil, errors.New("nss unavailable") }
|
||||
|
||||
_, err := baseConfigDir()
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = getConfigDir()
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestSwitchProfileSkipsStateWriteUnderSudo(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
fakeSudo(t, home)
|
||||
|
||||
pm := NewProfileManager()
|
||||
require.NoError(t, pm.SwitchProfile(defaultProfileName))
|
||||
assertNoEntries(t, home)
|
||||
}
|
||||
|
||||
func TestSetProfileStateSkipsWriteUnderSudo(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
fakeSudo(t, home)
|
||||
|
||||
pm := NewProfileManager()
|
||||
require.NoError(t, pm.SetProfileState(defaultProfileName, &ProfileState{Email: "misha@example.com"}))
|
||||
assertNoEntries(t, home)
|
||||
}
|
||||
|
||||
func TestRemoveProfileStateSkipsRemoveUnderSudo(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
stateDir := filepath.Join(home, ".config", "netbird")
|
||||
if runtime.GOOS == "darwin" {
|
||||
stateDir = filepath.Join(home, "Library", "Application Support", "netbird")
|
||||
}
|
||||
require.NoError(t, os.MkdirAll(stateDir, 0o700))
|
||||
stateFile := filepath.Join(stateDir, "default.state.json")
|
||||
require.NoError(t, os.WriteFile(stateFile, []byte(`{"email":"misha@example.com"}`), 0o600))
|
||||
|
||||
fakeSudo(t, home)
|
||||
pm := NewProfileManager()
|
||||
require.NoError(t, pm.RemoveProfileState("default"))
|
||||
assert.FileExists(t, stateFile)
|
||||
}
|
||||
|
||||
func TestUserBaseConfigDir(t *testing.T) {
|
||||
u := &user.User{Username: "misha", HomeDir: filepath.Join("/home", "misha")}
|
||||
dir, err := userBaseConfigDir(u)
|
||||
require.NoError(t, err)
|
||||
if runtime.GOOS == "darwin" {
|
||||
assert.Equal(t, filepath.Join(u.HomeDir, "Library", "Application Support"), dir)
|
||||
} else {
|
||||
assert.Equal(t, filepath.Join(u.HomeDir, ".config"), dir)
|
||||
}
|
||||
|
||||
_, err = userBaseConfigDir(&user.User{Username: "nohome"})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestIsPlainRoot(t *testing.T) {
|
||||
t.Setenv(envSudoUser, "")
|
||||
origEuid := geteuid
|
||||
t.Cleanup(func() { geteuid = origEuid })
|
||||
|
||||
geteuid = func() int { return 1000 }
|
||||
assert.False(t, IsPlainRoot())
|
||||
|
||||
geteuid = func() int { return 0 }
|
||||
assert.True(t, IsPlainRoot())
|
||||
}
|
||||
|
||||
func TestMirrorIsAuthoritative(t *testing.T) {
|
||||
t.Setenv(envSudoUser, "")
|
||||
origEuid := geteuid
|
||||
t.Cleanup(func() { geteuid = origEuid })
|
||||
|
||||
geteuid = func() int { return 1000 }
|
||||
assert.True(t, MirrorIsAuthoritative(), "a normal user's own mirror is authoritative")
|
||||
|
||||
geteuid = func() int { return 0 }
|
||||
assert.False(t, MirrorIsAuthoritative(), "plain root has no authoritative mirror")
|
||||
}
|
||||
|
||||
func TestMirrorIsAuthoritativeFalseUnderSudo(t *testing.T) {
|
||||
fakeSudo(t, filepath.Join("/home", "misha"))
|
||||
assert.False(t, MirrorIsAuthoritative(), "the sudo mirror is frozen, so it is not authoritative")
|
||||
}
|
||||
|
||||
func fakeSudo(t *testing.T, home string) {
|
||||
t.Helper()
|
||||
t.Setenv(envSudoUser, "misha")
|
||||
|
||||
origEuid := geteuid
|
||||
origLookup := lookupUser
|
||||
origOverride := ConfigDirOverride
|
||||
geteuid = func() int { return 0 }
|
||||
lookupUser = func(name string) (*user.User, error) {
|
||||
return &user.User{Username: name, Uid: "1234", Gid: "1234", HomeDir: home}, nil
|
||||
}
|
||||
ConfigDirOverride = ""
|
||||
t.Cleanup(func() {
|
||||
geteuid = origEuid
|
||||
lookupUser = origLookup
|
||||
ConfigDirOverride = origOverride
|
||||
})
|
||||
}
|
||||
|
||||
func assertNoEntries(t *testing.T, root string) {
|
||||
t.Helper()
|
||||
err := filepath.WalkDir(root, func(path string, _ fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if path != root {
|
||||
t.Errorf("unexpected entry created under %s: %s", root, path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package profilemanager
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -54,7 +53,7 @@ func (p *Profile) FilePath() (string, error) {
|
||||
return "", fmt.Errorf("invalid profile ID: %q", id)
|
||||
}
|
||||
|
||||
username, err := user.Current()
|
||||
username, err := InvokingUser()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get current user: %w", err)
|
||||
}
|
||||
@@ -130,7 +129,7 @@ func (pm *ProfileManager) getActiveProfileState() ID {
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
log.Warnf("failed to read active profile state: %v", err)
|
||||
} else {
|
||||
} else if !sudoActive() {
|
||||
if err := pm.setActiveProfileState(defaultProfileName); err != nil {
|
||||
log.Warnf("failed to set default profile state: %v", err)
|
||||
}
|
||||
@@ -148,6 +147,13 @@ func (pm *ProfileManager) getActiveProfileState() ID {
|
||||
}
|
||||
|
||||
func (pm *ProfileManager) setActiveProfileState(id ID) error {
|
||||
// The invoking user's state is read-only under sudo — a root-owned file in
|
||||
// the user's directory would break their own runs. The daemon still records
|
||||
// the switch on its side; only the user-local bookkeeping is skipped.
|
||||
if sudoActive() {
|
||||
log.Infof("running under sudo: not persisting active profile %q for user %s", id, os.Getenv(envSudoUser))
|
||||
return nil
|
||||
}
|
||||
|
||||
configDir, err := getConfigDir()
|
||||
if err != nil {
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/netbirdio/netbird/util"
|
||||
)
|
||||
|
||||
@@ -63,6 +65,15 @@ func (pm *ProfileManager) SetProfileState(id ID, state *ProfileState) error {
|
||||
return fmt.Errorf("invalid profile ID: %q", id)
|
||||
}
|
||||
|
||||
// The invoking user's state is read-only under sudo. The file only carries
|
||||
// the account email for the login hint and display, so skipping the write
|
||||
// costs at most one extra account prompt later — a root-owned file in the
|
||||
// user's directory would cost every later update instead.
|
||||
if sudoActive() {
|
||||
log.Debugf("running under sudo: not persisting profile state for user %s", os.Getenv(envSudoUser))
|
||||
return nil
|
||||
}
|
||||
|
||||
stateFile := filepath.Join(configDir, id.String()+".state.json")
|
||||
if err := util.WriteJsonWithRestrictedPermission(context.Background(), stateFile, state); err != nil {
|
||||
return fmt.Errorf("write profile state: %w", err)
|
||||
@@ -92,6 +103,11 @@ func (pm *ProfileManager) SetActiveProfileState(state *ProfileState) error {
|
||||
// equivalent to clearing it; the next SSO login recreates it. A missing file
|
||||
// is not an error.
|
||||
func (pm *ProfileManager) RemoveProfileState(profileName string) error {
|
||||
if sudoActive() {
|
||||
log.Debugf("running under sudo: not removing profile state for user %s", os.Getenv(envSudoUser))
|
||||
return nil
|
||||
}
|
||||
|
||||
configDir, err := getConfigDir()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get config directory: %w", err)
|
||||
|
||||
@@ -17,23 +17,30 @@ import (
|
||||
// are mutually exclusive: if the selection activates an exit node, every other
|
||||
// available exit node is deselected so two can't be active at once. With
|
||||
// appendRoute=false the previous selection is replaced instead of extended.
|
||||
// A partial failure (e.g. an unknown ID mixed with valid ones) still applies
|
||||
// the valid IDs to the routing table; the unknown ones are reported in the
|
||||
// returned error.
|
||||
func (m *DefaultManager) SelectRoutes(ids []route.NetID, appendRoute bool) error {
|
||||
if err := m.selectRoutes(ids, appendRoute); err != nil {
|
||||
return err
|
||||
}
|
||||
err := m.selectRoutes(ids, appendRoute)
|
||||
// Apply regardless of err: selectRoutes already selects the valid part of a
|
||||
// partial request, and skipping this on error would leave those routes
|
||||
// selected in the selector but never installed in the routing table.
|
||||
m.TriggerSelection(m.GetClientRoutes())
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
// DeselectRoutes removes the routes with the given network IDs from the
|
||||
// selection and applies the change. V4/v6 exit-node pairs are expanded
|
||||
// automatically.
|
||||
// automatically. A partial failure (e.g. an unknown ID mixed with valid ones)
|
||||
// still applies the valid IDs to the routing table; the unknown ones are
|
||||
// reported in the returned error.
|
||||
func (m *DefaultManager) DeselectRoutes(ids []route.NetID) error {
|
||||
if err := m.deselectRoutes(ids); err != nil {
|
||||
return err
|
||||
}
|
||||
err := m.deselectRoutes(ids)
|
||||
// Apply regardless of err: deselectRoutes already deselects the valid part
|
||||
// of a partial request, and skipping this on error would leave those routes
|
||||
// installed in the routing table despite being marked deselected.
|
||||
m.TriggerSelection(m.GetClientRoutes())
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *DefaultManager) deselectRoutes(ids []route.NetID) error {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
package routemanager
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/exp/maps"
|
||||
|
||||
"github.com/netbirdio/netbird/client/internal/peer"
|
||||
"github.com/netbirdio/netbird/client/internal/routemanager/client"
|
||||
"github.com/netbirdio/netbird/client/internal/routemanager/notifier"
|
||||
"github.com/netbirdio/netbird/client/internal/routeselector"
|
||||
"github.com/netbirdio/netbird/route"
|
||||
)
|
||||
@@ -112,6 +117,75 @@ func TestSelectRoutes_UnknownRoute(t *testing.T) {
|
||||
assert.Error(t, m.deselectRoutes([]route.NetID{"missing"}), "deselecting an unavailable route must fail")
|
||||
}
|
||||
|
||||
// newPartialFailureTestManager exercises the real install/remove path without
|
||||
// touching the system: the noop refcounter absorbs the route changes, and every
|
||||
// route already has a watcher, so none is started.
|
||||
func newPartialFailureTestManager() *DefaultManager {
|
||||
ctx := context.Background()
|
||||
|
||||
m := &DefaultManager{
|
||||
ctx: ctx,
|
||||
clientRoutes: route.HAMap{
|
||||
"lan|192.168.1.0/24": {{NetID: "lan", Network: netip.MustParsePrefix("192.168.1.0/24"), Peer: "p1"}},
|
||||
"other|10.1.2.0/24": {{NetID: "other", Network: netip.MustParsePrefix("10.1.2.0/24"), Peer: "p2"}},
|
||||
},
|
||||
routeSelector: routeselector.NewRouteSelector(),
|
||||
notifier: notifier.NewNotifier(),
|
||||
statusRecorder: peer.NewRecorder("https://mgm"),
|
||||
activeRoutes: make(map[route.HAUniqueID]client.RouteHandler),
|
||||
clientNetworks: map[route.HAUniqueID]*client.Watcher{
|
||||
"lan|192.168.1.0/24": client.NewWatcher(client.WatcherConfig{Context: ctx}),
|
||||
"other|10.1.2.0/24": client.NewWatcher(client.WatcherConfig{Context: ctx}),
|
||||
},
|
||||
}
|
||||
m.setupRefCounters(true)
|
||||
return m
|
||||
}
|
||||
|
||||
// Regression for the reported symptom: a partial failure returned before
|
||||
// TriggerSelection ran, so the valid route was marked selected while never
|
||||
// reaching the routing table (activeRoutes/ip route).
|
||||
func TestSelectRoutes_PartialFailureStillInstallsValidRoute(t *testing.T) {
|
||||
m := newPartialFailureTestManager()
|
||||
|
||||
err := m.SelectRoutes([]route.NetID{"missing", "lan"}, false)
|
||||
|
||||
assert.Error(t, err, "the unknown id must still be reported")
|
||||
assert.Contains(t, m.activeRoutes, route.HAUniqueID("lan|192.168.1.0/24"), "the valid route must be installed despite the error")
|
||||
assert.NotContains(t, m.activeRoutes, route.HAUniqueID("other|10.1.2.0/24"), "the deselected route must not be installed")
|
||||
}
|
||||
|
||||
// Mirror of the case above: a partial failure must remove the valid route from
|
||||
// the routing table, not just mark it deselected in the selector.
|
||||
func TestDeselectRoutes_PartialFailureStillRemovesValidRoute(t *testing.T) {
|
||||
m := newPartialFailureTestManager()
|
||||
|
||||
require.NoError(t, m.SelectRoutes([]route.NetID{"lan", "other"}, false))
|
||||
require.Contains(t, m.activeRoutes, route.HAUniqueID("lan|192.168.1.0/24"))
|
||||
require.Contains(t, m.activeRoutes, route.HAUniqueID("other|10.1.2.0/24"))
|
||||
|
||||
err := m.DeselectRoutes([]route.NetID{"missing", "other"})
|
||||
|
||||
assert.Error(t, err, "the unknown id must still be reported")
|
||||
assert.NotContains(t, m.activeRoutes, route.HAUniqueID("other|10.1.2.0/24"), "the deselected route must be removed")
|
||||
assert.Contains(t, m.activeRoutes, route.HAUniqueID("lan|192.168.1.0/24"), "the untouched route stays installed")
|
||||
}
|
||||
|
||||
// The selection now runs on every request, including one where no ID is known
|
||||
// and the selector stays untouched. Nothing may be torn down or reinstalled on
|
||||
// that path.
|
||||
func TestSelectRoutes_TotalFailureLeavesInstalledRoutesAlone(t *testing.T) {
|
||||
m := newPartialFailureTestManager()
|
||||
|
||||
require.NoError(t, m.SelectRoutes([]route.NetID{"lan", "other"}, false))
|
||||
installed := maps.Keys(m.activeRoutes)
|
||||
|
||||
err := m.SelectRoutes([]route.NetID{"missing"}, false)
|
||||
|
||||
assert.Error(t, err, "the unknown id must still be reported")
|
||||
assert.ElementsMatch(t, installed, maps.Keys(m.activeRoutes), "a fully invalid request must not disturb the routing table")
|
||||
}
|
||||
|
||||
func TestExitNodeSelectionHelpers(t *testing.T) {
|
||||
routesMap := map[route.NetID][]*route.Route{
|
||||
"exitA": {{Network: netip.MustParsePrefix("0.0.0.0/0")}},
|
||||
|
||||
@@ -32,6 +32,22 @@ func (rs *RouteSelector) SelectRoutes(routes []route.NetID, appendRoute bool, al
|
||||
rs.mu.Lock()
|
||||
defer rs.mu.Unlock()
|
||||
|
||||
// Validate before mutating: a non-append selection wipes the current selection
|
||||
// first, so a request of only unavailable routes would deselect everything and
|
||||
// put nothing back. An empty request means deselect all, so it still goes through.
|
||||
var err *multierror.Error
|
||||
available := make([]route.NetID, 0, len(routes))
|
||||
for _, r := range routes {
|
||||
if !slices.Contains(allRoutes, r) {
|
||||
err = multierror.Append(err, fmt.Errorf("route '%s' is not available", r))
|
||||
continue
|
||||
}
|
||||
available = append(available, r)
|
||||
}
|
||||
if len(available) == 0 && err != nil {
|
||||
return errors.FormatErrorOrNil(err)
|
||||
}
|
||||
|
||||
if !appendRoute || rs.deselectAll {
|
||||
if rs.deselectedRoutes == nil {
|
||||
rs.deselectedRoutes = map[route.NetID]struct{}{}
|
||||
@@ -46,14 +62,9 @@ func (rs *RouteSelector) SelectRoutes(routes []route.NetID, appendRoute bool, al
|
||||
}
|
||||
}
|
||||
|
||||
var err *multierror.Error
|
||||
for _, route := range routes {
|
||||
if !slices.Contains(allRoutes, route) {
|
||||
err = multierror.Append(err, fmt.Errorf("route '%s' is not available", route))
|
||||
continue
|
||||
}
|
||||
delete(rs.deselectedRoutes, route)
|
||||
rs.selectedRoutes[route] = struct{}{}
|
||||
for _, r := range available {
|
||||
delete(rs.deselectedRoutes, r)
|
||||
rs.selectedRoutes[r] = struct{}{}
|
||||
}
|
||||
|
||||
rs.deselectAll = false
|
||||
|
||||
@@ -887,3 +887,70 @@ func TestRouteSelector_EnableExitNodeKeepsOtherRoutes(t *testing.T) {
|
||||
assert.True(t, rs.IsSelected("lan1"), "non-exit route must stay selected")
|
||||
assert.True(t, rs.IsSelected("lan2"), "non-exit route must stay selected")
|
||||
}
|
||||
|
||||
// A non-append selection clears the current selection before applying the requested
|
||||
// one, so an all-unavailable request used to leave nothing selected while returning
|
||||
// an error. Requests with at least one available route are unaffected.
|
||||
func TestRouteSelector_SelectRoutes_AllUnavailableKeepsSelection(t *testing.T) {
|
||||
allRoutes := []route.NetID{"route1", "route2", "route3"}
|
||||
|
||||
rs := routeselector.NewRouteSelector()
|
||||
require.NoError(t, rs.SelectRoutes([]route.NetID{"route1"}, false, allRoutes))
|
||||
|
||||
err := rs.SelectRoutes([]route.NetID{"Route1", "route4"}, false, allRoutes)
|
||||
|
||||
assert.Error(t, err, "an unavailable route ID must still be reported")
|
||||
assert.True(t, rs.IsSelected("route1"), "the previous selection must survive a fully invalid request")
|
||||
for _, id := range []route.NetID{"route2", "route3"} {
|
||||
assert.False(t, rs.IsSelected(id), "no other route may become selected")
|
||||
}
|
||||
}
|
||||
|
||||
// Boundary of the check above: an empty request is the caller deselecting everything,
|
||||
// not a failed lookup, so it must keep working.
|
||||
func TestRouteSelector_SelectRoutes_EmptyRequestStillDeselectsAll(t *testing.T) {
|
||||
allRoutes := []route.NetID{"route1", "route2", "route3"}
|
||||
|
||||
rs := routeselector.NewRouteSelector()
|
||||
require.NoError(t, rs.SelectRoutes([]route.NetID{"route1"}, false, allRoutes))
|
||||
|
||||
require.NoError(t, rs.SelectRoutes(nil, false, allRoutes))
|
||||
|
||||
for _, id := range allRoutes {
|
||||
assert.False(t, rs.IsSelected(id), "an empty selection request must deselect everything")
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile clients always call SelectRoutes with append=true. On that path an
|
||||
// all-unavailable request was never destructive to begin with (append skips the
|
||||
// wipe regardless of the guard above), but the behavior has no coverage yet.
|
||||
func TestRouteSelector_SelectRoutes_AppendAllUnavailableKeepsSelection(t *testing.T) {
|
||||
allRoutes := []route.NetID{"route1", "route2", "route3"}
|
||||
|
||||
rs := routeselector.NewRouteSelector()
|
||||
require.NoError(t, rs.SelectRoutes([]route.NetID{"route1"}, false, allRoutes))
|
||||
|
||||
err := rs.SelectRoutes([]route.NetID{"missing"}, true, allRoutes)
|
||||
|
||||
assert.Error(t, err, "an unavailable route ID must still be reported")
|
||||
assert.True(t, rs.IsSelected("route1"), "the previous selection must survive a fully invalid request")
|
||||
for _, id := range []route.NetID{"route2", "route3"} {
|
||||
assert.False(t, rs.IsSelected(id), "no other route may become selected")
|
||||
}
|
||||
}
|
||||
|
||||
// The early return for an all-unavailable request must not clear deselectAll,
|
||||
// or a typo'd network ID would silently drop the "nothing selected, including
|
||||
// future networks" policy.
|
||||
func TestRouteSelector_SelectRoutes_AllUnavailableAfterDeselectAllKeepsPolicy(t *testing.T) {
|
||||
allRoutes := []route.NetID{"route1", "route2"}
|
||||
|
||||
rs := routeselector.NewRouteSelector()
|
||||
rs.DeselectAllRoutes()
|
||||
|
||||
err := rs.SelectRoutes([]route.NetID{"missing"}, false, allRoutes)
|
||||
|
||||
assert.Error(t, err, "an unavailable route ID must still be reported")
|
||||
assert.True(t, rs.IsDeselectAll(), "deselect-all policy must survive a fully invalid request")
|
||||
assert.False(t, rs.IsSelected("route3"), "deselect-all must still cover networks not present in allRoutes yet")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user