From cf017119711184a0661062a0c8ac2043e4e8d411 Mon Sep 17 00:00:00 2001 From: Zoltan Papp Date: Fri, 16 Oct 2026 20:52:43 +0200 Subject: [PATCH 01/15] [client] Bump wireguard-go to bd0cb75a3df0 (#8229) StdNetBind.Send reused pooled *net.UDPAddr objects and copied the destination into ua.IP before resizing the slice. After an IPv4 send the slice was 4 bytes long, so the next IPv6 send copied only 4 bytes and extended the slice with stale data, misdirecting datagrams to a truncated or foreign IPv6 address. Userspace clients with both IPv4 and IPv6 P2P peers saw intermittent loss and restarting handshakes. The fork now carries the upstream fix (WireGuard/wireguard-go#135, netbirdio/wireguard-go#24). Pick it up. --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index dcbc7d9d7..79dcd1867 100644 --- a/go.mod +++ b/go.mod @@ -369,7 +369,7 @@ replace github.com/kardianos/service => github.com/netbirdio/service v0.0.0-2024 replace github.com/getlantern/systray => github.com/netbirdio/systray v0.0.0-20231030152038-ef1ed2a27949 -replace golang.zx2c4.com/wireguard => github.com/netbirdio/wireguard-go v0.0.0-20261008122457-d2b1ce9bfee9 +replace golang.zx2c4.com/wireguard => github.com/netbirdio/wireguard-go v0.0.0-20261016113635-bd0cb75a3df0 replace github.com/cloudflare/circl => codeberg.org/cunicu/circl v0.0.0-20230801113412-fec58fc7b5f6 diff --git a/go.sum b/go.sum index 64197c736..5b9cd5a11 100644 --- a/go.sum +++ b/go.sum @@ -541,8 +541,8 @@ github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250805121659-6b4ac470 github.com/netbirdio/signal-dispatcher/dispatcher v0.0.0-20250805121659-6b4ac470ca45/go.mod h1:5/sjFmLb8O96B5737VCqhHyGRzNFIaN/Bu7ZodXc3qQ= github.com/netbirdio/wails/v3 v3.0.0-beta.3.0.20261009120932-4e087a8bfd6d h1:DV0FHFhNAaU69JHXKclYQWr/ZJoc2BA/ZpqlnX8l22U= github.com/netbirdio/wails/v3 v3.0.0-beta.3.0.20261009120932-4e087a8bfd6d/go.mod h1:62UsqQRqanuCbFi6xElIw3/2X+yGF+TKlyiWImA5taU= -github.com/netbirdio/wireguard-go v0.0.0-20261008122457-d2b1ce9bfee9 h1:Mjt3tIBGa1/mJh1Xn8uZP30cd2VYd0NHANqTn+HBsaU= -github.com/netbirdio/wireguard-go v0.0.0-20261008122457-d2b1ce9bfee9/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= +github.com/netbirdio/wireguard-go v0.0.0-20261016113635-bd0cb75a3df0 h1:nCK1YzDybjbAfrx+C2QPmcQ+7jYj4Rcb3FskqTNZEXo= +github.com/netbirdio/wireguard-go v0.0.0-20261016113635-bd0cb75a3df0/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/nxadm/tail v1.4.11 h1:8feyoE3OzPrcshW5/MJ4sGESc5cqmGkGCWlco4l0bqY= From 279adb8fdd5c5eb6d0f960fb6b65ab543ebb1f9d Mon Sep 17 00:00:00 2001 From: Edward <43848523+thomashacker@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:58:14 +0200 Subject: [PATCH 02/15] [management] Return the reason when custom domain validation fails (#8122) * [management] Return the reason when custom domain validation fails The validate endpoint returned an empty 202 and ran the check in a goroutine, so a failed verification only reached the management log. Run the check in the request and return 204 or 412 with a classified reason. Resolver errors are not forwarded. * [management] Address review feedback on custom domain validation Pass the request context to the lookup and store calls now that the check runs in the request, compare the self-resolved name case-insensitively, document the 412 like the other entries, and check the returned error in the existing tests. * [management] Match custom domain CNAME targets case-insensitively DNS names are case-insensitive, so a CNAME pointing at the cluster in different casing should validate instead of failing as a mismatch. * [management] Add validation timeout --------- Co-authored-by: DevBot NetBird <91386968+netbirddev@users.noreply.github.com> --- .../modules/reverseproxy/domain/interface.go | 2 +- .../reverseproxy/domain/manager/api.go | 7 +- .../domain/manager/expiration_test.go | 8 +- .../reverseproxy/domain/manager/manager.go | 87 +++++----- .../domain/manager/manager_realstore_test.go | 4 +- .../domain/manager/normalization_test.go | 2 +- .../domain/manager/validation_test.go | 151 ++++++++++++++++++ .../modules/reverseproxy/domain/validator.go | 59 ++++++- .../reverseproxy/domain/validator_test.go | 66 ++++++++ shared/management/http/api/openapi.yml | 9 +- 10 files changed, 331 insertions(+), 64 deletions(-) create mode 100644 management/internals/modules/reverseproxy/domain/manager/validation_test.go diff --git a/management/internals/modules/reverseproxy/domain/interface.go b/management/internals/modules/reverseproxy/domain/interface.go index a4bba5841..c729fb7b0 100644 --- a/management/internals/modules/reverseproxy/domain/interface.go +++ b/management/internals/modules/reverseproxy/domain/interface.go @@ -8,6 +8,6 @@ type Manager interface { GetDomains(ctx context.Context, accountID, userID string) ([]*Domain, error) CreateDomain(ctx context.Context, accountID, userID, domainName, targetCluster string) (*Domain, error) DeleteDomain(ctx context.Context, accountID, userID, domainID string) error - ValidateDomain(ctx context.Context, accountID, userID, domainID string) + ValidateDomain(ctx context.Context, accountID, userID, domainID string) error GetClusterDomains() []string } diff --git a/management/internals/modules/reverseproxy/domain/manager/api.go b/management/internals/modules/reverseproxy/domain/manager/api.go index f01329010..ec5daf7d6 100644 --- a/management/internals/modules/reverseproxy/domain/manager/api.go +++ b/management/internals/modules/reverseproxy/domain/manager/api.go @@ -134,7 +134,10 @@ func (h *handler) triggerCustomDomainValidation(w http.ResponseWriter, r *http.R return } - go h.manager.ValidateDomain(r.Context(), userAuth.AccountId, userAuth.UserId, domainID) + if err := h.manager.ValidateDomain(r.Context(), userAuth.AccountId, userAuth.UserId, domainID); err != nil { + util.WriteError(r.Context(), err, w) + return + } - w.WriteHeader(http.StatusAccepted) + w.WriteHeader(http.StatusNoContent) } diff --git a/management/internals/modules/reverseproxy/domain/manager/expiration_test.go b/management/internals/modules/reverseproxy/domain/manager/expiration_test.go index e3b05efbb..3a3bd6e92 100644 --- a/management/internals/modules/reverseproxy/domain/manager/expiration_test.go +++ b/management/internals/modules/reverseproxy/domain/manager/expiration_test.go @@ -29,7 +29,7 @@ func TestValidateDomain_ExpiredRegistration(t *testing.T) { Update("validation_expires_at", expiresAt).Error) env.resolver.set("validation.expired.example.com", testCluster) - env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) + assert.Error(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID), "an expired registration must be refused") stored := storedDomain(t, env.store, accountA, d.Domain) require.NotNil(t, stored) @@ -47,7 +47,7 @@ func TestCreateDomain_ValidationDeadline(t *testing.T) { assert.Equal(t, createdAt.Add(48*time.Hour), *d.ValidationExpiresAt, "new registrations get 48 hours") time.Sleep(time.Hour) - env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) + assert.Error(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID), "a missing CNAME must fail validation") stored := storedDomain(t, env.store, accountA, d.Domain) require.NotNil(t, stored) require.NotNil(t, stored.ValidationExpiresAt) @@ -198,9 +198,10 @@ func TestValidateDomain_DeadlinePassesDuringLookup(t *testing.T) { resolver := blockingDomainResolver{started: make(chan struct{}), release: make(chan struct{})} env.manager.validator.Resolver = resolver done := make(chan struct{}) + var validateErr error go func() { defer close(done) - env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) + validateErr = env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) }() <-resolver.started time.Sleep(48 * time.Hour) @@ -211,6 +212,7 @@ func TestValidateDomain_DeadlinePassesDuringLookup(t *testing.T) { } close(resolver.release) <-done + assert.Error(t, validateErr, "a validation finishing after the deadline must be refused") owner := accountA if cleanup { assert.Nil(t, storedDomain(t, env.store, accountA, d.Domain), "late validation must not restore the old claim") diff --git a/management/internals/modules/reverseproxy/domain/manager/manager.go b/management/internals/modules/reverseproxy/domain/manager/manager.go index 1e9ecab43..f92ed8201 100644 --- a/management/internals/modules/reverseproxy/domain/manager/manager.go +++ b/management/internals/modules/reverseproxy/domain/manager/manager.go @@ -227,22 +227,19 @@ func (m Manager) DeleteDomain(ctx context.Context, accountID, userID, domainID s return nil } -func (m Manager) ValidateDomain(ctx context.Context, accountID, userID, domainID string) { - ok, _, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Services, operations.Create) +// validationTimeout bounds the DNS check so it ends, and reports why, before a proxy in +// front of management times the request out. +const validationTimeout = 10 * time.Second + +// ValidateDomain checks the domain's validation CNAME and marks it validated. A failure +// the user can act on is returned as PreconditionFailed carrying the reason. +func (m Manager) ValidateDomain(ctx context.Context, accountID, userID, domainID string) error { + ok, ctx, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Services, operations.Create) if err != nil { - log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - }).WithError(err).Error("validate domain") - return + return status.NewPermissionValidationError(err) } if !ok { - log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - "userID": userID, - }).Error("validate domain: permission denied") - return + return status.NewPermissionDeniedError() } log.WithFields(log.Fields{ @@ -250,32 +247,23 @@ func (m Manager) ValidateDomain(ctx context.Context, accountID, userID, domainID "domainID": domainID, }).Info("starting domain validation") - d, err := m.store.GetCustomDomain(context.Background(), accountID, domainID) + d, err := m.store.GetCustomDomain(ctx, accountID, domainID) if err != nil { - log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - }).WithError(err).Error("get custom domain from store") - return + return fmt.Errorf("get domain from store: %w", err) } if d.Validated { - return + return nil } if d.ValidationExpiresAt == nil || !time.Now().Before(*d.ValidationExpiresAt) { - log.WithFields(log.Fields{"accountID": accountID, "domainID": domainID}). - Debug("custom domain validation window has expired") - return + return validationFailed(domain.NewValidationError(domain.ValidationReasonExpired, + "custom domain %s validation window has expired; delete and add the domain again", d.Domain)) } // Validate only against the domain's target cluster targetCluster := d.TargetCluster if targetCluster == "" { - log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - "domain": d.Domain, - }).Warn("domain has no target cluster set, skipping validation") - return + return validationFailed(domain.NewValidationError(domain.ValidationReasonNoTargetCluster, + "custom domain %s has no target cluster", d.Domain)) } log.WithFields(log.Fields{ @@ -285,32 +273,35 @@ func (m Manager) ValidateDomain(ctx context.Context, accountID, userID, domainID "targetCluster": targetCluster, }).Info("validating domain against target cluster") - if m.validator.IsValid(context.Background(), d.Domain, []string{targetCluster}) { + lookupCtx, cancel := context.WithTimeout(ctx, validationTimeout) + _, err = m.validator.Validate(lookupCtx, d.Domain, []string{targetCluster}) + cancel() + if err == nil { d.Validated = true - if _, err := m.store.UpdateCustomDomain(context.Background(), accountID, d); err != nil { - entry := log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - }).WithError(err) - if sErr, ok := status.FromError(err); ok && sErr.Type() == status.PreconditionFailed { - entry.Debug("custom domain registration is no longer pending validation") - return + if _, err := m.store.UpdateCustomDomain(ctx, accountID, d); err != nil { + // A concurrent request may have validated the domain first. + if current, getErr := m.store.GetCustomDomain(ctx, accountID, domainID); getErr == nil && current.Validated { + return nil } - entry.Error("update custom domain in store") - return + return fmt.Errorf("update domain in store: %w", err) } log.WithFields(log.Fields{"accountID": accountID, "domainID": domainID}). Info("custom domain validated successfully") - m.accountManager.StoreEvent(context.Background(), userID, domainID, accountID, activity.DomainValidated, d.EventMeta()) - } else { - log.WithFields(log.Fields{ - "accountID": accountID, - "domainID": domainID, - "domain": d.Domain, - "targetCluster": targetCluster, - }).Warn("domain validation failed - CNAME does not match target cluster") + m.accountManager.StoreEvent(ctx, userID, domainID, accountID, activity.DomainValidated, d.EventMeta()) + return nil } + + return validationFailed(err) +} + +// validationFailed shows a classified failure to the user and keeps anything else internal. +func validationFailed(err error) error { + var vErr *domain.ValidationError + if errors.As(err, &vErr) { + return status.Errorf(status.PreconditionFailed, "%s", vErr.Message) + } + return fmt.Errorf("validate domain: %w", err) } // GetClusterDomains returns a list of proxy cluster domains. diff --git a/management/internals/modules/reverseproxy/domain/manager/manager_realstore_test.go b/management/internals/modules/reverseproxy/domain/manager/manager_realstore_test.go index fed402498..dfb999fbd 100644 --- a/management/internals/modules/reverseproxy/domain/manager/manager_realstore_test.go +++ b/management/internals/modules/reverseproxy/domain/manager/manager_realstore_test.go @@ -229,7 +229,7 @@ func TestValidateDomain_UnlocksClusterDerivation(t *testing.T) { require.Error(t, err) env.resolver.set("validation.later.example.com", testCluster) - env.manager.ValidateDomain(ctx, accountA, accountAUser, created.ID) + require.NoError(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, created.ID)) require.True(t, storedDomain(t, env.store, accountA, "later.example.com").Validated) @@ -286,7 +286,7 @@ func TestValidateDomain_PermissionDeniedDoesNotValidate(t *testing.T) { // a validated domain is the permission check. env.resolver.set("validation.guarded.example.com", testCluster) - env.manager.ValidateDomain(ctx, accountA, accountAMember, created.ID) + assert.Error(t, env.manager.ValidateDomain(ctx, accountA, accountAMember, created.ID), "a caller without permission must be refused") stored := storedDomain(t, env.store, accountA, "guarded.example.com") require.NotNil(t, stored) diff --git a/management/internals/modules/reverseproxy/domain/manager/normalization_test.go b/management/internals/modules/reverseproxy/domain/manager/normalization_test.go index da5e4bdd1..810454c57 100644 --- a/management/internals/modules/reverseproxy/domain/manager/normalization_test.go +++ b/management/internals/modules/reverseproxy/domain/manager/normalization_test.go @@ -52,7 +52,7 @@ func TestCreateDomain_NormalizedNameCanValidateLater(t *testing.T) { require.False(t, created.Validated, "a missing CNAME must leave the normalized registration pending") env.resolver.set("validation.apps.example.com", testCluster) - env.manager.ValidateDomain(ctx, accountA, accountAUser, created.ID) + require.NoError(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, created.ID)) stored, err := env.store.GetCustomDomain(ctx, accountA, created.ID) require.NoError(t, err) assert.Equal(t, "apps.example.com", stored.Domain, "retrying validation must retain the normalized name") diff --git a/management/internals/modules/reverseproxy/domain/manager/validation_test.go b/management/internals/modules/reverseproxy/domain/manager/validation_test.go new file mode 100644 index 000000000..b7800c6f5 --- /dev/null +++ b/management/internals/modules/reverseproxy/domain/manager/validation_test.go @@ -0,0 +1,151 @@ +package manager + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/netbirdio/netbird/management/internals/modules/reverseproxy/domain" + nbstore "github.com/netbirdio/netbird/management/server/store" + "github.com/netbirdio/netbird/shared/management/status" +) + +// The validator tests cover each DNS outcome. These cover what the manager adds on top: +// the status type the API turns into a response code, and the checks before the lookup. +func TestValidateDomain_ReturnsReason(t *testing.T) { + ctx := context.Background() + tests := []struct { + name string + setup func(t *testing.T, env *domainTestEnv, d *domain.Domain) + user string + want status.Type + message string + }{ + { + name: "cname mismatch", + setup: func(_ *testing.T, env *domainTestEnv, d *domain.Domain) { + env.resolver.set("validation."+d.Domain, "other.example.net") + }, + want: status.PreconditionFailed, + message: "CNAME record validation.test.example.com points to other.example.net; point it to " + testCluster, + }, + { + name: "expired window", + setup: func(t *testing.T, env *domainTestEnv, d *domain.Domain) { + setDomainColumn(t, env, d, "validation_expires_at", time.Now().Add(-time.Second)) + }, + want: status.PreconditionFailed, + message: "custom domain test.example.com validation window has expired; delete and add the domain again", + }, + { + name: "no target cluster", + setup: func(t *testing.T, env *domainTestEnv, d *domain.Domain) { + setDomainColumn(t, env, d, "target_cluster", "") + }, + want: status.PreconditionFailed, + message: "custom domain test.example.com has no target cluster", + }, + { + name: "permission denied", + setup: func(_ *testing.T, env *domainTestEnv, d *domain.Domain) { + env.resolver.set("validation."+d.Domain, testCluster) + }, + user: accountAMember, + want: status.PermissionDenied, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + env := setupDomainTest(t) + d, err := env.manager.CreateDomain(ctx, accountA, accountAUser, "test.example.com", testCluster) + require.NoError(t, err) + tt.setup(t, env, d) + user := accountAUser + if tt.user != "" { + user = tt.user + } + + err = env.manager.ValidateDomain(ctx, accountA, user, d.ID) + sErr, ok := status.FromError(err) + require.True(t, ok, "expected a status error, got %v", err) + assert.Equal(t, tt.want, sErr.Type(), "status type") + if tt.message != "" { + assert.Equal(t, tt.message, sErr.Message, "user-facing message") + } + assert.False(t, storedDomain(t, env.store, accountA, d.Domain).Validated, "a failed check must not validate the domain") + }) + } +} + +func TestValidateDomain_SuccessIsIdempotent(t *testing.T) { + ctx := context.Background() + env := setupDomainTest(t) + d, err := env.manager.CreateDomain(ctx, accountA, accountAUser, "ok.example.com", testCluster) + require.NoError(t, err) + env.resolver.set("validation.ok.example.com", testCluster) + + require.NoError(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID)) + assert.True(t, storedDomain(t, env.store, accountA, d.Domain).Validated, "domain should be validated") + assert.NoError(t, env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID), "an already validated domain is a success") +} + +func setDomainColumn(t *testing.T, env *domainTestEnv, d *domain.Domain, column string, value any) { + t.Helper() + db := env.store.(*nbstore.SqlStore).GetDB() + require.NoError(t, db.Model(&domain.Domain{}).Where("id = ?", d.ID).Update(column, value).Error) +} + +// Two verify requests can both read the domain as pending. The one that loses the store +// update must still report success when the other one validated the domain. +func TestValidateDomain_ConcurrentValidationSucceeds(t *testing.T) { + ctx := context.Background() + env := setupDomainTest(t) + d, err := env.manager.CreateDomain(ctx, accountA, accountAUser, "twice.example.com", testCluster) + require.NoError(t, err) + resolver := blockingDomainResolver{started: make(chan struct{}), release: make(chan struct{})} + env.manager.validator.Resolver = resolver + + done := make(chan error, 1) + go func() { + done <- env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) + }() + <-resolver.started + // The other request completes while this one is still looking up the CNAME. + setDomainColumn(t, env, d, "validated", true) + close(resolver.release) + + assert.NoError(t, <-done, "a domain validated by a concurrent request is a success") +} + +// hangingResolver never answers, so only a deadline on the context ends the lookup. +type hangingResolver struct{} + +func (hangingResolver) LookupCNAME(ctx context.Context, _ string) (string, error) { + <-ctx.Done() + return "", ctx.Err() +} + +// A lookup that hangs must end on the validation timeout and still report the reason, +// rather than leaving the request to whatever timeout sits in front of management. +func TestValidateDomain_LookupTimeout(t *testing.T) { + env := setupClockDomainTest(t) + synctest.Test(t, func(t *testing.T) { + ctx := context.Background() + d, err := env.manager.CreateDomain(ctx, accountA, accountAUser, "slow.example.com", testCluster) + require.NoError(t, err) + env.manager.validator.Resolver = hangingResolver{} + + start := time.Now() + err = env.manager.ValidateDomain(ctx, accountA, accountAUser, d.ID) + sErr, ok := status.FromError(err) + require.True(t, ok, "expected a status error, got %v", err) + assert.Equal(t, status.PreconditionFailed, sErr.Type(), "status type") + assert.Equal(t, "DNS lookup for validation.slow.example.com failed; retry the validation", sErr.Message, "user-facing message") + assert.Equal(t, validationTimeout, time.Since(start), "the lookup must end on the validation timeout") + }) +} diff --git a/management/internals/modules/reverseproxy/domain/validator.go b/management/internals/modules/reverseproxy/domain/validator.go index 9c23c1192..e8d1ea3d0 100644 --- a/management/internals/modules/reverseproxy/domain/validator.go +++ b/management/internals/modules/reverseproxy/domain/validator.go @@ -2,6 +2,8 @@ package domain import ( "context" + "errors" + "fmt" "net" "strings" @@ -16,6 +18,33 @@ type Validator struct { Resolver resolver } +// ValidationReason classifies why a custom domain failed validation. +type ValidationReason string + +const ( + ValidationReasonCNAMENotFound ValidationReason = "cname_not_found" + ValidationReasonCNAMEMismatch ValidationReason = "cname_mismatch" + ValidationReasonLookupFailed ValidationReason = "lookup_failed" + ValidationReasonExpired ValidationReason = "validation_expired" + ValidationReasonNoTargetCluster ValidationReason = "no_target_cluster" +) + +// ValidationError is a validation failure whose message is safe to show to the user. +type ValidationError struct { + Reason ValidationReason + Message string +} + +// Error returns the user-facing message. +func (e *ValidationError) Error() string { + return e.Message +} + +// NewValidationError returns a ValidationError with a formatted message. +func NewValidationError(reason ValidationReason, format string, args ...any) *ValidationError { + return &ValidationError{Reason: reason, Message: fmt.Sprintf(format, args...)} +} + // NewValidator initializes a validator with a specific DNS Resolver. // If a Validator is used without specifying a Resolver, then it will // use the net.DefaultResolver. @@ -39,6 +68,13 @@ func (v *Validator) IsValid(ctx context.Context, domain string, accept []string) // ValidateWithCluster validates a custom domain and returns the matched cluster address. // Returns the cluster address and true if valid, or empty string and false if invalid. func (v *Validator) ValidateWithCluster(ctx context.Context, domain string, accept []string) (string, bool) { + cluster, err := v.Validate(ctx, domain, accept) + return cluster, err == nil +} + +// Validate validates a custom domain and returns the matched cluster address. +// On failure it returns a *ValidationError whose message is safe to show to the user. +func (v *Validator) Validate(ctx context.Context, domain string, accept []string) (string, error) { if v.Resolver == nil { v.Resolver = net.DefaultResolver } @@ -56,10 +92,19 @@ func (v *Validator) ValidateWithCluster(ctx context.Context, domain string, acce "domain": domain, "lookupDomain": lookupDomain, }).WithError(err).Warn("CNAME lookup failed for domain validation") - return "", false + // Never forward the resolver error: its text includes the resolver address. + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) && dnsErr.IsNotFound { + return "", cnameNotFound(lookupDomain, accept) + } + return "", NewValidationError(ValidationReasonLookupFailed, "DNS lookup for %s failed; retry the validation", lookupDomain) } nakedCNAME := strings.TrimSuffix(cname, ".") + // A name without a CNAME record resolves to itself. + if strings.EqualFold(nakedCNAME, lookupDomain) { + return "", cnameNotFound(lookupDomain, accept) + } log.WithFields(log.Fields{ "domain": domain, "cname": cname, @@ -69,13 +114,13 @@ func (v *Validator) ValidateWithCluster(ctx context.Context, domain string, acce for _, acceptDomain := range accept { normalizedAccept := strings.TrimSuffix(acceptDomain, ".") - if nakedCNAME == normalizedAccept { + if strings.EqualFold(nakedCNAME, normalizedAccept) { log.WithFields(log.Fields{ "domain": domain, "cname": nakedCNAME, "cluster": acceptDomain, }).Info("domain CNAME matched cluster") - return acceptDomain, true + return acceptDomain, nil } } @@ -84,5 +129,11 @@ func (v *Validator) ValidateWithCluster(ctx context.Context, domain string, acce "cname": nakedCNAME, "acceptList": accept, }).Warn("domain CNAME does not match any accepted cluster") - return "", false + return "", NewValidationError(ValidationReasonCNAMEMismatch, "CNAME record %s points to %s; point it to %s", + lookupDomain, nakedCNAME, strings.Join(accept, ", ")) +} + +func cnameNotFound(lookupDomain string, accept []string) *ValidationError { + return NewValidationError(ValidationReasonCNAMENotFound, "no CNAME record found for %s; point it to %s", + lookupDomain, strings.Join(accept, ", ")) } diff --git a/management/internals/modules/reverseproxy/domain/validator_test.go b/management/internals/modules/reverseproxy/domain/validator_test.go index 1f9583728..8d47bca32 100644 --- a/management/internals/modules/reverseproxy/domain/validator_test.go +++ b/management/internals/modules/reverseproxy/domain/validator_test.go @@ -2,6 +2,8 @@ package domain_test import ( "context" + "errors" + "net" "testing" "github.com/netbirdio/netbird/management/internals/modules/reverseproxy/domain" @@ -36,6 +38,12 @@ func TestIsValid(t *testing.T) { accept: []string{"bar.example.com"}, expect: false, }, + "match in other case": { + resolver: resolver{"Bar.Example.COM."}, + domain: "foo.example.com", + accept: []string{"bar.example.com"}, + expect: true, + }, "accept trailing dot": { resolver: resolver{"bar.example.com."}, domain: "foo.example.com", @@ -54,3 +62,61 @@ func TestIsValid(t *testing.T) { }) } } + +type errResolver struct { + err error +} + +func (r errResolver) LookupCNAME(context.Context, string) (string, error) { + return "", r.err +} + +func TestValidate_Reason(t *testing.T) { + const notFound = "no CNAME record found for validation.foo.example.com; point it to eu.proxy.example.com" + tests := map[string]struct { + resolver interface { + LookupCNAME(context.Context, string) (string, error) + } + reason domain.ValidationReason + message string + }{ + "mismatch": { + resolver: resolver{"other.example.net."}, + reason: domain.ValidationReasonCNAMEMismatch, + message: "CNAME record validation.foo.example.com points to other.example.net; point it to eu.proxy.example.com", + }, + "no cname resolves to itself": { + resolver: resolver{"validation.foo.example.com."}, + reason: domain.ValidationReasonCNAMENotFound, + message: notFound, + }, + "no cname resolves to itself in other case": { + resolver: resolver{"Validation.Foo.example.com."}, + reason: domain.ValidationReasonCNAMENotFound, + message: notFound, + }, + "not found": { + resolver: errResolver{&net.DNSError{Err: "no such host", Name: "validation.foo.example.com", Server: "10.0.0.2:53", IsNotFound: true}}, + reason: domain.ValidationReasonCNAMENotFound, + message: notFound, + }, + "other error is not forwarded": { + resolver: errResolver{errors.New("dial udp 10.0.0.2:53: connect: network is unreachable")}, + reason: domain.ValidationReasonLookupFailed, + message: "DNS lookup for validation.foo.example.com failed; retry the validation", + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + _, err := domain.NewValidator(test.resolver).Validate(t.Context(), "foo.example.com", []string{"eu.proxy.example.com"}) + var vErr *domain.ValidationError + if !errors.As(err, &vErr) { + t.Fatalf("expected a *domain.ValidationError, got %v", err) + } + if vErr.Reason != test.reason || vErr.Message != test.message { + t.Errorf("expect %q %q, actual %q %q", test.reason, test.message, vErr.Reason, vErr.Message) + } + }) + } +} diff --git a/shared/management/http/api/openapi.yml b/shared/management/http/api/openapi.yml index fbf8bf5cd..ca8c1339b 100644 --- a/shared/management/http/api/openapi.yml +++ b/shared/management/http/api/openapi.yml @@ -12895,7 +12895,7 @@ paths: /api/reverse-proxies/domains/{domainId}/validate: get: summary: Validate a custom domain - description: Trigger domain ownership validation for a custom domain + description: Validate domain ownership for a custom domain tags: [ Services ] security: - BearerAuth: [ ] @@ -12908,8 +12908,8 @@ paths: type: string description: The custom domain ID responses: - '202': - description: Reverse proxy custom domain validation triggered + '204': + description: Reverse proxy custom domain validated '400': "$ref": "#/components/responses/bad_request" '401': @@ -12918,6 +12918,9 @@ paths: "$ref": "#/components/responses/forbidden" '404': "$ref": "#/components/responses/not_found" + '412': + description: Precondition failed - the custom domain could not be validated + content: { } '500': "$ref": "#/components/responses/internal_error" /api/integrations/notifications/types: From f8f335720de0d7f5e4842fd24c42b78bfa042859 Mon Sep 17 00:00:00 2001 From: Riccardo Manfrin <3090891+riccardomanfrin@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:08:15 +0200 Subject: [PATCH 03/15] [client,relay] Bump quic-go to v0.64.0 (#8249) --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 79dcd1867..bc8e5e287 100644 --- a/go.mod +++ b/go.mod @@ -105,7 +105,7 @@ require ( github.com/pkg/sftp v1.13.9 github.com/prometheus/client_golang v1.23.2 github.com/prometheus/client_model v0.6.2 - github.com/quic-go/quic-go v0.62.0 + github.com/quic-go/quic-go v0.64.0 github.com/redis/go-redis/v9 v9.7.3 github.com/rs/xid v1.3.0 github.com/shirou/gopsutil/v4 v4.25.8 diff --git a/go.sum b/go.sum index 5b9cd5a11..9af59daf5 100644 --- a/go.sum +++ b/go.sum @@ -647,8 +647,8 @@ github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4 github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0= github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= -github.com/quic-go/quic-go v0.62.0 h1:ZHDjCk5OacATwGvs8PWE97CTvX7AqZiVoW7++ZOXTf8= -github.com/quic-go/quic-go v0.62.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= +github.com/quic-go/quic-go v0.64.0 h1:dlUpiyp9+7UrbbuhLvV7CJ9F8uoZxXf/vi2h8tkuuoA= +github.com/quic-go/quic-go v0.64.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w= github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= From b1f4efb160071bb04052bfbb736ca0227ff151e3 Mon Sep 17 00:00:00 2001 From: Viktor Liu <17948409+lixmal@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:16:59 +0900 Subject: [PATCH 04/15] [client] Fix errcheck findings from the latest golangci-lint (#8251) --- client/iface/iface_close_test.go | 24 ++++++++++++++++-------- client/ssh/client/client.go | 6 ++++-- management/internals/server/server.go | 6 +++++- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/client/iface/iface_close_test.go b/client/iface/iface_close_test.go index ea3115ec0..ecbbf4866 100644 --- a/client/iface/iface_close_test.go +++ b/client/iface/iface_close_test.go @@ -12,6 +12,7 @@ import ( "golang.zx2c4.com/wireguard/tun/netstack" "github.com/netbirdio/netbird/client/iface/device" + nbnetstack "github.com/netbirdio/netbird/client/iface/netstack" "github.com/netbirdio/netbird/client/iface/udpmux" "github.com/netbirdio/netbird/client/iface/wgaddr" "github.com/netbirdio/netbird/client/iface/wgproxy" @@ -34,14 +35,14 @@ func (f *fakeTunDevice) Create() (device.WGConfigurer, error) { func (f *fakeTunDevice) Up() (*udpmux.UniversalUDPMuxDefault, error) { return nil, errors.New("not implemented") } -func (f *fakeTunDevice) UpdateAddr(wgaddr.Address) error { return nil } -func (f *fakeTunDevice) WgAddress() wgaddr.Address { return wgaddr.Address{} } -func (f *fakeTunDevice) MTU() uint16 { return DefaultMTU } -func (f *fakeTunDevice) DeviceName() string { return "nb-close-test" } +func (f *fakeTunDevice) UpdateAddr(wgaddr.Address) error { return nil } +func (f *fakeTunDevice) WgAddress() wgaddr.Address { return wgaddr.Address{} } +func (f *fakeTunDevice) MTU() uint16 { return DefaultMTU } +func (f *fakeTunDevice) DeviceName() string { return "nb-close-test" } func (f *fakeTunDevice) FilteredDevice() *device.FilteredDevice { return nil } -func (f *fakeTunDevice) Device() *wgdevice.Device { return nil } -func (f *fakeTunDevice) GetNet() *netstack.Net { return nil } -func (f *fakeTunDevice) GetICEBind() device.EndpointManager { return nil } +func (f *fakeTunDevice) Device() *wgdevice.Device { return nil } +func (f *fakeTunDevice) GetNet() *netstack.Net { return nil } +func (f *fakeTunDevice) GetICEBind() device.EndpointManager { return nil } func (f *fakeTunDevice) Close() error { close(f.closeStarted) @@ -62,6 +63,10 @@ func (fakeProxyFactory) Free() error { return nil } // WGIface.GetDevice() which needs the same mutex. The fix is to drop // the lock before tun.Close() returns control. func TestWGIface_CloseReleasesMutexBeforeTunClose(t *testing.T) { + // Netstack mode skips the platform interface cleanup in Close, so only + // the mutex and tun close behavior is exercised. + t.Setenv(nbnetstack.EnvUseNetstackMode, "true") + tun := &fakeTunDevice{ closeStarted: make(chan struct{}), unblockClose: make(chan struct{}), @@ -105,7 +110,10 @@ func TestWGIface_CloseReleasesMutexBeforeTunClose(t *testing.T) { close(tun.unblockClose) select { - case <-closeDone: + case err := <-closeDone: + if err != nil { + t.Errorf("WGIface.Close() returned an error: %v", err) + } case <-time.After(2 * time.Second): t.Fatal("WGIface.Close() never returned after the tun was unblocked") } diff --git a/client/ssh/client/client.go b/client/ssh/client/client.go index 31143a4f4..dc94c33f4 100644 --- a/client/ssh/client/client.go +++ b/client/ssh/client/client.go @@ -166,7 +166,8 @@ func (c *Client) ExecuteCommandWithIO(ctx context.Context, command string) error case <-ctx.Done(): _ = session.Signal(ssh.SIGTERM) select { - case <-done: + case err := <-done: + log.Debugf("session ended after SIGTERM: %v", err) return ctx.Err() case <-time.After(100 * time.Millisecond): return ctx.Err() @@ -205,7 +206,8 @@ func (c *Client) ExecuteCommandWithPTY(ctx context.Context, command string) erro case <-ctx.Done(): _ = session.Signal(ssh.SIGTERM) select { - case <-done: + case err := <-done: + log.Debugf("session ended after SIGTERM: %v", err) return ctx.Err() case <-time.After(100 * time.Millisecond): return ctx.Err() diff --git a/management/internals/server/server.go b/management/internals/server/server.go index bbf0f389d..c95092d70 100644 --- a/management/internals/server/server.go +++ b/management/internals/server/server.go @@ -335,7 +335,11 @@ func (s *BaseServer) Stop() error { } select { - case <-s.Errors(): + case err := <-s.Errors(): + if err != nil { + log.WithContext(ctx).Infof("stopped Management Service: %v", err) + return nil + } log.WithContext(ctx).Infof("stopped Management Service") return nil case <-ctx.Done(): From 6e1065882a453a199a7c3ed7831fe6b6011b9b80 Mon Sep 17 00:00:00 2001 From: DevBot NetBird <91386968+netbirddev@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:24:07 +0200 Subject: [PATCH 05/15] New Crowdin updates (#8101) * New translations common.json (French) [ci skip] * New translations common.json (Spanish) [ci skip] * New translations common.json (German) [ci skip] * New translations common.json (Hebrew) [ci skip] * New translations common.json (Hungarian) [ci skip] * New translations common.json (Italian) [ci skip] * New translations common.json (Japanese) [ci skip] * New translations common.json (Russian) [ci skip] * New translations common.json (Ukrainian) [ci skip] * New translations common.json (Chinese Simplified) [ci skip] * New translations common.json (Portuguese, Brazilian) [ci skip] * New translations common.json (Galician) [ci skip] * Update client/ui/i18n/locales/he/common.json Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> * New translations common.json (French) [ci skip] * New translations common.json (Spanish) [ci skip] * New translations common.json (German) [ci skip] * New translations common.json (Hebrew) [ci skip] * New translations common.json (Hungarian) [ci skip] * New translations common.json (Italian) [ci skip] * New translations common.json (Japanese) [ci skip] * New translations common.json (Russian) [ci skip] * New translations common.json (Ukrainian) [ci skip] * New translations common.json (Chinese Simplified) [ci skip] * New translations common.json (Portuguese, Brazilian) [ci skip] * New translations common.json (Galician) [ci skip] --------- Co-authored-by: Edward <43848523+thomashacker@users.noreply.github.com> Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- client/ui/i18n/locales/de/common.json | 6 +- client/ui/i18n/locales/es/common.json | 6 +- client/ui/i18n/locales/fr/common.json | 6 +- client/ui/i18n/locales/he/common.json | 1397 ++++++++++++++++++++++ client/ui/i18n/locales/hu/common.json | 6 +- client/ui/i18n/locales/it/common.json | 6 +- client/ui/i18n/locales/ja/common.json | 6 +- client/ui/i18n/locales/pt/common.json | 6 +- client/ui/i18n/locales/ru/common.json | 6 +- client/ui/i18n/locales/zh-CN/common.json | 6 +- 10 files changed, 1415 insertions(+), 36 deletions(-) create mode 100644 client/ui/i18n/locales/he/common.json diff --git a/client/ui/i18n/locales/de/common.json b/client/ui/i18n/locales/de/common.json index dcce2f908..105c8c0b3 100644 --- a/client/ui/i18n/locales/de/common.json +++ b/client/ui/i18n/locales/de/common.json @@ -552,12 +552,10 @@ "message": "Ändern des Autostarts fehlgeschlagen" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Nach dem Beenden verbunden bleiben", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Nach dem Beenden verbunden bleiben" }, "settings.general.keepConnectedOnQuit.help": { - "message": "Die Verbindung bleibt im Hintergrund bestehen, nachdem Sie NetBird schließen. Sie endet erst, wenn Sie sie selbst trennen.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "Die Verbindung bleibt im Hintergrund bestehen, nachdem Sie NetBird schließen. Sie endet erst, wenn Sie sie selbst trennen." }, "settings.general.language.label": { "message": "Anzeigesprache" diff --git a/client/ui/i18n/locales/es/common.json b/client/ui/i18n/locales/es/common.json index 979879680..f786592a7 100644 --- a/client/ui/i18n/locales/es/common.json +++ b/client/ui/i18n/locales/es/common.json @@ -552,12 +552,10 @@ "message": "Error al cambiar el inicio automático" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Permanecer conectado al salir", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Permanecer conectado al salir" }, "settings.general.keepConnectedOnQuit.help": { - "message": "La conexión sigue activa en segundo plano después de cerrar NetBird. Solo se detiene cuando la desconectas tú.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "La conexión sigue activa en segundo plano después de cerrar NetBird. Solo se detiene cuando la desconectas tú." }, "settings.general.language.label": { "message": "Idioma de la interfaz" diff --git a/client/ui/i18n/locales/fr/common.json b/client/ui/i18n/locales/fr/common.json index f9961d864..87e833e3f 100644 --- a/client/ui/i18n/locales/fr/common.json +++ b/client/ui/i18n/locales/fr/common.json @@ -552,12 +552,10 @@ "message": "Échec de la modification du démarrage automatique" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Rester connecté après la fermeture", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Rester connecté après la fermeture" }, "settings.general.keepConnectedOnQuit.help": { - "message": "La connexion reste active en arrière-plan après la fermeture de NetBird. Elle ne s'arrête que si vous la coupez vous-même.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "La connexion reste active en arrière-plan après la fermeture de NetBird. Elle ne s'arrête que si vous la coupez vous-même." }, "settings.general.language.label": { "message": "Langue d’affichage" diff --git a/client/ui/i18n/locales/he/common.json b/client/ui/i18n/locales/he/common.json new file mode 100644 index 000000000..640f6b3da --- /dev/null +++ b/client/ui/i18n/locales/he/common.json @@ -0,0 +1,1397 @@ +{ + "tray.tooltip": { + "message": "NetBird" + }, + "tray.status.disconnected": { + "message": "מנותק" + }, + "tray.status.daemonUnavailable": { + "message": "לא פעיל" + }, + "tray.status.error": { + "message": "שגיאה" + }, + "tray.status.connected": { + "message": "מחובר" + }, + "tray.status.connecting": { + "message": "מתחבר" + }, + "tray.status.needsLogin": { + "message": "צריך להיכנס" + }, + "tray.status.loginFailed": { + "message": "הכניסה נכשלה" + }, + "tray.status.sessionExpired": { + "message": "תוקף ההפעלה פג" + }, + "tray.session.expiresIn": { + "message": "תוקף ההפעלה יפוג בעוד {remaining}" + }, + "tray.session.unit.lessThanMinute": { + "message": "פחות מדקה" + }, + "tray.session.unit.minute": { + "message": "דקה" + }, + "tray.session.unit.minutes": { + "message": "{count} דקות" + }, + "tray.session.unit.hour": { + "message": "שעה" + }, + "tray.session.unit.hours": { + "message": "{count} שעות" + }, + "tray.session.unit.day": { + "message": "יום" + }, + "tray.session.unit.days": { + "message": "{count} ימים" + }, + "tray.menu.open": { + "message": "פתיחת NetBird" + }, + "tray.menu.connect": { + "message": "התחברות" + }, + "tray.menu.disconnect": { + "message": "התנתקות" + }, + "tray.menu.exitNode": { + "message": "נקודת יציאה" + }, + "tray.menu.networks": { + "message": "משאבים" + }, + "tray.menu.profiles": { + "message": "פרופילים" + }, + "tray.menu.manageProfiles": { + "message": "ניהול פרופילים" + }, + "tray.menu.settings": { + "message": "הגדרות…" + }, + "tray.menu.debugBundle": { + "message": "יצירת מאגד ניפוי שגיאות" + }, + "tray.menu.about": { + "message": "עזרה ותמיכה" + }, + "tray.menu.github": { + "message": "GitHub" + }, + "tray.menu.documentation": { + "message": "תיעוד" + }, + "tray.menu.troubleshoot": { + "message": "פתרון בעיות" + }, + "tray.menu.downloadLatest": { + "message": "הורדת הגרסה העדכנית ביותר" + }, + "tray.menu.installVersion": { + "message": "התקנת גרסה {version}" + }, + "tray.menu.guiVersion": { + "message": "ממשק משתמש: {version}" + }, + "tray.menu.daemonVersion": { + "message": "סוכן: {version}" + }, + "tray.menu.versionUnknown": { + "message": "—" + }, + "tray.menu.quit": { + "message": "יציאה מ־NetBird" + }, + "notify.daemonOutdated.title": { + "message": "שירות NetBird אינו עדכני" + }, + "notify.daemonOutdated.body": { + "message": "יש לעדכן את שירות NetBird כדי להשתמש ביישום הזה." + }, + "notify.update.title": { + "message": "יש עדכון ל־NetBird" + }, + "notify.update.body": { + "message": "יצא NetBird {version}." + }, + "notify.update.enforcedSuffix": { + "message": " הנהלת המערכת דורשת ממך לעדכן לגרסה הזאת." + }, + "notify.error.title": { + "message": "שגיאה" + }, + "notify.error.connect": { + "message": "החיבור נכשל" + }, + "notify.error.disconnect": { + "message": "הניתוק נכשל" + }, + "notify.error.switchProfile": { + "message": "המעבר לפרופיל {profile} נכשל" + }, + "notify.error.exitNode": { + "message": "עדכון נקודת היציאה {name} נכשל" + }, + "notify.sessionExpired.title": { + "message": "תוקף הפעלת NetBird פג" + }, + "notify.sessionExpired.body": { + "message": "תוקף הפעלת ה־NetBird שלך פג. נא להיכנס למערכת שוב." + }, + "notify.sessionWarning.title": { + "message": "תוקף ההפעלה יפוג בקרוב" + }, + "notify.sessionWarning.body": { + "message": "הפעלת ה־NetBird שלך תפוג בעוד {remaining}. לחיצה על להאריך כעת תחדש אותה." + }, + "notify.sessionWarning.bodyGeneric": { + "message": "תוקף הפעלת ה־NetBird שלך עומד לפוג. לחיצה על להאריך כעת תחדש אותו." + }, + "notify.sessionWarning.extend": { + "message": "להאריך כעת" + }, + "notify.sessionWarning.dismiss": { + "message": "התעלמות" + }, + "notify.sessionWarning.failed": { + "message": "הארכת ההפעלה של NetBird נכשלה" + }, + "notify.sessionWarning.successTitle": { + "message": "ההפעלה של NetBird הוארכה" + }, + "notify.sessionWarning.successBody": { + "message": "ההפעלה שלך התרעננה." + }, + "notify.sessionDeadlineRejected.title": { + "message": "מועד הסיום של ההפעלה נדחה" + }, + "notify.sessionDeadlineRejected.body": { + "message": "השרת שלח מועד סיום שגוי להפעלה. נא להיכנס שוב למערכת." + }, + "notify.mdm.policyApplied.title": { + "message": "ההגדרות של NetBird עודכנו" + }, + "notify.mdm.policyApplied.body": { + "message": "הגדרות ה־NetBird שלך עודכנו על ידי מדיניות צוות המחשוב שלך." + }, + "common.cancel": { + "message": "ביטול" + }, + "common.save": { + "message": "שמירה" + }, + "common.saveChanges": { + "message": "שמירת השינויים" + }, + "common.saving": { + "message": "שמירה…" + }, + "common.close": { + "message": "סגירה" + }, + "common.copy": { + "message": "העתקה" + }, + "common.togglePasswordVisibility": { + "message": "הסתרת/חשיפת סיסמה" + }, + "common.increase": { + "message": "הגדלה" + }, + "common.decrease": { + "message": "הקטנה" + }, + "common.delete": { + "message": "מחיקה" + }, + "common.create": { + "message": "יצירה" + }, + "common.add": { + "message": "הוספה" + }, + "common.remove": { + "message": "הסרה" + }, + "common.refresh": { + "message": "ריענון" + }, + "common.loading": { + "message": "בטעינה…" + }, + "common.netbird": { + "message": "NetBird" + }, + "common.noResults.title": { + "message": "לא ניתן למצוא תוצאות כלשהן." + }, + "common.noResults.description": { + "message": "לא הצלחנו למצוא תוצאות כלשהן. נא לנסות ביטוי חיפוש אחר או לשנות את המסננים שלך." + }, + "notConnected.title": { + "message": "מנותק" + }, + "notConnected.description": { + "message": "יש להתחבר ל־NetBird תחילה כדי לצפות במידע מפורט על העמיתים, משאבי הרשת ונקודות היציאה שלך." + }, + "connect.status.disconnected": { + "message": "מנותק" + }, + "connect.status.connecting": { + "message": "מתחבר…" + }, + "connect.status.connected": { + "message": "מחובר" + }, + "connect.status.disconnecting": { + "message": "מתנתק…" + }, + "connect.status.daemonUnavailable": { + "message": "הסוכן לא זמין" + }, + "connect.status.loginRequired": { + "message": "נדרשת כניסה" + }, + "connect.error.loginTitle": { + "message": "הכניסה נכשלה" + }, + "connect.error.connectTitle": { + "message": "התחברות נכשלה" + }, + "connect.error.disconnectTitle": { + "message": "התנתקות נכשלה" + }, + "nav.peers.title": { + "message": "עמיתים" + }, + "nav.peers.description": { + "message": "{connected} מתוך {total} מחוברים" + }, + "nav.resources.title": { + "message": "משאבים" + }, + "nav.resources.description": { + "message": "{active} מתוך {total} פעילים" + }, + "nav.exitNode.title": { + "message": "נקודות יציאה" + }, + "nav.exitNode.none": { + "message": "לא פעיל" + }, + "nav.exitNode.using": { + "message": "דרך {name}" + }, + "header.openSettings": { + "message": "פתיחת הגדרות" + }, + "header.togglePanel": { + "message": "הצגת/הסתרת לוח צד" + }, + "profile.selector.loading": { + "message": "בטעינה…" + }, + "profile.selector.noProfile": { + "message": "אין פרופיל" + }, + "profile.selector.searchPlaceholder": { + "message": "חיפוש פרופיל לפי שם…" + }, + "profile.selector.emptyTitle": { + "message": "לא נמצאו פרופילים" + }, + "profile.selector.emptyDescription": { + "message": "כדאי לנסות ביטוי אחר לחיפוש או ליצור פרופיל חדש." + }, + "profile.selector.newProfile": { + "message": "פרופיל חדש" + }, + "profile.selector.moreOptions": { + "message": "אפשרויות נוספות" + }, + "profile.selector.deregister": { + "message": "ביטול רישום" + }, + "profile.selector.delete": { + "message": "מחיקה" + }, + "profile.selector.switchTo": { + "message": "החלפה לפרופיל הזה" + }, + "profile.selector.edit": { + "message": "עריכה" + }, + "profile.edit.title": { + "message": "עריכת פרופיל" + }, + "profile.edit.submit": { + "message": "שמירת השינויים" + }, + "profile.dialog.title": { + "message": "נא למלא שם פרופיל" + }, + "profile.dialog.nameLabel": { + "message": "שם פרופיל" + }, + "profile.dialog.description": { + "message": "הגדרת שם שניתן לזהות בקלות לפרופיל שלך." + }, + "profile.dialog.placeholder": { + "message": "למשל: עבודה" + }, + "profile.dialog.submit": { + "message": "הוספת פרופיל" + }, + "profile.dialog.required": { + "message": "נא למלא שם לפרופיל, למשל: עבודה, בית" + }, + "profile.dialog.managementHelp": { + "message": "אפשר להשתמש בענן של NetBird או בשרת משלך." + }, + "profile.dialog.urlUnreachable": { + "message": "לא ניתן להגיע לשרת. נא לבדוק שהכתובת נכונה או להוסיף את הפרופיל בכל זאת אם ברור לך שהיא נכונה." + }, + "header.menu.settings": { + "message": "הגדרות…" + }, + "header.menu.defaultView": { + "message": "תצוגת ברירת מחדל" + }, + "header.menu.advancedView": { + "message": "תצוגה מתקדמת" + }, + "header.menu.updateAvailable": { + "message": "יש עדכון" + }, + "header.menu.open": { + "message": "פתיחת התפריט" + }, + "header.profile.switch": { + "message": "החלפת פרופיל" + }, + "connect.toggle.label": { + "message": "החלפת מצב חיבור NetBird" + }, + "connect.localIp.label": { + "message": "כתובות IP מקומיות" + }, + "common.search": { + "message": "חיפוש" + }, + "common.filter": { + "message": "סינון" + }, + "exitNodes.dropdown.trigger": { + "message": "בחירת נקודת יציאה" + }, + "peers.row.label": { + "message": "פתיחת פרטים עבור {name}, {status}" + }, + "peers.dialog.title": { + "message": "פרטי עמית" + }, + "networks.row.toggle": { + "message": "להחליף את המצב של {name}" + }, + "networks.bulk.label": { + "message": "להחליף את המצב של כל המשאבים הגלויים" + }, + "profile.switch.title": { + "message": "להחליף את הפרופיל כך שיהיה „{name}”?" + }, + "profile.switch.message": { + "message": "להחליף פרופילים?\nהפרופיל הנוכחי שלך יתנתק." + }, + "profile.switch.confirm": { + "message": "אישור" + }, + "profile.deregister.title": { + "message": "לבטל את רישום הפרופיל „{name}”?" + }, + "profile.deregister.message": { + "message": "לבטל את רישום הפרופיל הזה?\nצריך להיכנס שוב כדי להשתמש בו." + }, + "profile.deregister.confirm": { + "message": "לבטל רישום" + }, + "profile.delete.title": { + "message": "למחוק את הפרופיל „{name}”?" + }, + "profile.delete.message": { + "message": "למחוק את הפרופיל הזה?\nזאת פעולה בלתי הפיכה." + }, + "profile.delete.disabledActive": { + "message": "לא ניתן למחוק פרופילים פעילים. יש להחליף לפרופיל אחר בטרם מחיקת הפרופיל הזה." + }, + "profile.delete.disabledDefault": { + "message": "לא ניתן למחוק את פרופיל ברירת המחדל." + }, + "profile.error.switchTitle": { + "message": "החלפת פרופיל נכשלה" + }, + "profile.error.deregisterTitle": { + "message": "ביטול רישום פרופיל נכשל" + }, + "profile.error.deleteTitle": { + "message": "מחיקת פרופיל נכשלה" + }, + "profile.error.createTitle": { + "message": "יצירת פרופיל נכשלה" + }, + "profile.error.editTitle": { + "message": "עריכת פרופיל נכשלה" + }, + "profile.error.loadTitle": { + "message": "טעינת הפרופילים נכשלה" + }, + "profile.dropdown.activeProfile": { + "message": "הפרופיל הפעיל" + }, + "profile.dropdown.switchProfile": { + "message": "החלפת פרופיל" + }, + "profile.dropdown.noEmail": { + "message": "אחר" + }, + "profile.dropdown.addProfile": { + "message": "הוספת פרופיל" + }, + "profile.dropdown.manageProfiles": { + "message": "ניהול פרופילים" + }, + "profile.dropdown.settings": { + "message": "הגדרות" + }, + "settings.profiles.section.profiles": { + "message": "פרופילים" + }, + "settings.profiles.intro": { + "message": "ניתן להחזיק את זהויות ה־NetBird הנפרדות זו לצד זו, למשל חשבון עבודה וחשבון פרטי או שרתי ניהול שונים. אפשר להוסיף, לבטל רישום או למחוק פרופילים להלן." + }, + "settings.profiles.addProfile": { + "message": "הוספת פרופיל" + }, + "settings.profiles.active": { + "message": "פעיל" + }, + "settings.profiles.emptyTitle": { + "message": "אין פרופילים" + }, + "settings.profiles.emptyDescription": { + "message": "יש ליצור פרופיל כדי להתחבר לשרת ניהול של NetBird." + }, + "settings.error.loadTitle": { + "message": "טעינת ההגדרות נכשלה" + }, + "settings.error.saveTitle": { + "message": "שמירת ההגדרות נכשלה" + }, + "settings.error.debugBundleTitle": { + "message": "מאגד ניפוי השגיאות נכשל" + }, + "settings.nav.label": { + "message": "סעיפי הגדרות" + }, + "settings.tabs.general": { + "message": "כללי" + }, + "settings.tabs.network": { + "message": "רשת" + }, + "settings.tabs.security": { + "message": "אבטחה" + }, + "settings.tabs.profiles": { + "message": "פרופילים" + }, + "settings.tabs.ssh": { + "message": "SSH" + }, + "settings.tabs.advanced": { + "message": "מתקדם" + }, + "settings.tabs.troubleshooting": { + "message": "פתרון בעיות" + }, + "settings.tabs.about": { + "message": "על אודות" + }, + "settings.tabs.updateAvailable": { + "message": "יש עדכון" + }, + "settings.general.section.general": { + "message": "כללי" + }, + "settings.general.section.connection": { + "message": "חיבור" + }, + "settings.general.connectOnStartup.label": { + "message": "להתחבר עם העלייה" + }, + "settings.general.connectOnStartup.help": { + "message": "להקים חיבור אוטומטית כשהשירות מופעל." + }, + "settings.general.notifications.label": { + "message": "התראות שולחן עבודה" + }, + "settings.general.notifications.help": { + "message": "להציג התראות שולחן עבודה על עדכונים חדשים ואירועי חיבור." + }, + "settings.general.autostart.label": { + "message": "להפעיל את ממשק המשתמש של NetBird עם הכניסה למערכת" + }, + "settings.general.autostart.help": { + "message": "להפעיל את הממשק של NetBird אוטומטית עם הכניסה. הפעולה הזאת משפיעה על הממשק הגרפי בלבד, לא על שירות הרקע." + }, + "settings.general.autostart.errorTitle": { + "message": "שינוי בהפעלה האוטומטית נכשל" + }, + "settings.general.keepConnectedOnQuit.label": { + "message": "להשאיר את החיבור לאחר היציאה" + }, + "settings.general.keepConnectedOnQuit.help": { + "message": "החיבור נשאר פעיל ברקע לאחר סגירת NetBird. הוא נקטע רק כשבחרת לנתק אותו בעצמך." + }, + "settings.general.language.label": { + "message": "שפת התצוגה" + }, + "settings.general.language.help": { + "message": "בחירת שפת הממשק של NetBird." + }, + "settings.general.language.search": { + "message": "חיפוש שפה…" + }, + "settings.general.language.empty": { + "message": "אין שפות תואמות." + }, + "settings.general.theme.label": { + "message": "ערכת עיצוב" + }, + "settings.general.theme.help": { + "message": "נא לבחור בהירה או כהה או להתאים למערכת." + }, + "settings.general.theme.system": { + "message": "מערכת" + }, + "settings.general.theme.light": { + "message": "בהירה" + }, + "settings.general.theme.dark": { + "message": "כהה" + }, + "settings.general.management.label": { + "message": "שרת ניהול" + }, + "settings.general.management.help": { + "message": "אפשר להתחבר לענן של NetBird או לשרת ניהול באירוח שלך. שינויים יחברו את הלקוח מחדש." + }, + "settings.general.management.cloud": { + "message": "ענן" + }, + "settings.general.management.selfHosted": { + "message": "אירוח עצמי" + }, + "settings.general.management.urlPlaceholder": { + "message": "https://netbird.selfhosted.com:443" + }, + "settings.general.management.urlError": { + "message": "נא למלא כתובת תקפה, למשל, https://netbird.selfhosted.com:443" + }, + "settings.general.management.urlUnreachable": { + "message": "לא ניתן להגיע לשרת הזה. נא לבדוק את הכתובת או לשמור בכל זאת אם ברור לך שהיא נכונה." + }, + "settings.general.management.switchCloudTitle": { + "message": "לעבור לענן NetBird?" + }, + "settings.general.management.switchCloudMessage": { + "message": "מנתק אותך מהשרת שלך באירוח עצמי.\nיתכן שיהיה עליך להיכנס למערכת שוב." + }, + "settings.general.management.switchCloudConfirm": { + "message": "מעבר לענן" + }, + "settings.network.section.connectivity": { + "message": "קישוריות" + }, + "settings.network.section.routingDns": { + "message": "ניתוב ו־DNS" + }, + "settings.network.monitor.label": { + "message": "להתחבר מחדש כשחל שינוי ברשת" + }, + "settings.network.monitor.help": { + "message": "מעקב אחר הרשת כדי להתחבר מחדש עקב שינויים כגון מעבר רשת אלחוטית, שינויים בחיבור הקווי או התעוררות משינה." + }, + "settings.network.dns.label": { + "message": "הפעלת DNS" + }, + "settings.network.dns.help": { + "message": "החלת הגדרות DNS בניהול NetBird לפותר שמות המארחים." + }, + "settings.network.clientRoutes.label": { + "message": "הפעלת ניתובי לקוח" + }, + "settings.network.clientRoutes.help": { + "message": "קבלת ניתובים מעמיתים אחרים כדי להגיע לרשתות שלהם." + }, + "settings.network.serverRoutes.label": { + "message": "הפעלת ניתובי שרת" + }, + "settings.network.serverRoutes.help": { + "message": "לפרסם את הניתובים המקומיים של המארח הזה לעמיתים אחרים." + }, + "settings.network.ipv6.label": { + "message": "הפעלת IPv6" + }, + "settings.network.ipv6.help": { + "message": "להשתמש בחלוקת כתובות IPv6 לרשת שכבת העל של NetBird." + }, + "settings.security.section.firewall": { + "message": "חומת אש" + }, + "settings.security.section.encryption": { + "message": "הצפנה" + }, + "settings.security.blockInbound.label": { + "message": "חסימת תעבורה נכנסת" + }, + "settings.security.blockInbound.help": { + "message": "לדחות חיבורים שלא התבקשו מעמיתים למכשיר הזה ולרשתות כלשהן שהוא מנתב אליהן. אין השפעה על התקשורת היוצאת." + }, + "settings.security.blockLan.label": { + "message": "חסימת גישה לרשת המקומית" + }, + "settings.security.blockLan.help": { + "message": "למנוע מעמיתים להגיע לרשת המקומית שלך או המכשירים שבה כאשר המכשיר הזה מנתב את התעבורה שלהם." + }, + "settings.security.rosenpass.label": { + "message": "הפעלת עמידות לפיענוח צפנים קוונטי" + }, + "settings.security.rosenpass.help": { + "message": "הוספת החלפת מפתחות עמידה לפיענוח צפנים קוונטי דרך Rosenpass על גבי WireGuard®." + }, + "settings.security.rosenpassPermissive.label": { + "message": "הפעלת מצב מתירני" + }, + "settings.security.rosenpassPermissive.help": { + "message": "לאפשר חיבורים לעמיתים ללא תמיכה בעמידות לפיענוח צפנים קוונטי." + }, + "settings.ssh.section.server": { + "message": "שרת" + }, + "settings.ssh.section.capabilities": { + "message": "יכולות" + }, + "settings.ssh.section.authentication": { + "message": "אימות" + }, + "settings.ssh.server.label": { + "message": "הפעלת שרת SSH" + }, + "settings.ssh.server.help": { + "message": "להריץ את שרת ה־SSH של NetBird על המארח הזה כדי שעמיתים אחרים יוכלו להתחבר אליו." + }, + "settings.ssh.root.label": { + "message": "לאפשר כניסת ניהול (root)" + }, + "settings.ssh.root.help": { + "message": "לאפשר לעמיתים להיכנס בתור משתמש הניהול. אפשר להשבית כדי לדרוש שזה יהיה חשבון ללא הרשאות מופלגות." + }, + "settings.ssh.sftp.label": { + "message": "לאפשר SFTP" + }, + "settings.ssh.sftp.help": { + "message": "העברת קבצים בבטחה עם לקוחות מובנים של SFTP או SCP." + }, + "settings.ssh.localForward.label": { + "message": "העברת פתחה מקומית" + }, + "settings.ssh.localForward.help": { + "message": "לאפשר לעמיתים שמתחברים לתעל פתחות מקומיות לשירותים שנגישים למארח הזה." + }, + "settings.ssh.remoteForward.label": { + "message": "העברת פתחה מרוחקת" + }, + "settings.ssh.remoteForward.help": { + "message": "לאפשר לעמיתים שמתחברים לחשוף בפני המארח הזה פתחות שחוזרות למכונות שלהם." + }, + "settings.ssh.jwt.label": { + "message": "הפעלת אימות JWT" + }, + "settings.ssh.jwt.help": { + "message": "לאמת כל הפעלת SSH מול ספק הזהות (IdP) שלך לזהות המשתמש ולפיקוח. יש להשבית כדי לסמוך רק על מדיניויות ה־ACL (רשימת בקרת גישה) של הרשתות בלבד, שימושי כשאין ספק זהות (IdP) זמין." + }, + "settings.ssh.jwtTtl.label": { + "message": "זמן חיי JWT במטמון (TTL)" + }, + "settings.ssh.jwtTtl.help": { + "message": "כמה זמן הלקוח הזה שומר JWT במטמון בטרם הצגת בקשה חוזרת לחיבורי SSH יוצאים. יש להגדיר ל־0 כדי להשבית את המטמון ולעבור אימות עם כל חיבור מחדש." + }, + "settings.ssh.jwtTtl.suffix": { + "message": "שנייה/ות" + }, + "settings.advanced.section.interface": { + "message": "ממשק" + }, + "settings.advanced.section.security": { + "message": "אבטחה" + }, + "settings.advanced.interfaceName.label": { + "message": "שם" + }, + "settings.advanced.interfaceName.error": { + "message": "יש להשתמש ב־1-15 אותיות, ספרות, נקודות, מינוסים או קווים תחתיים." + }, + "settings.advanced.interfaceName.errorMac": { + "message": "חייב להתחיל ב־„utun” ולאחריו מספר (למשל: utun100)." + }, + "settings.advanced.port.label": { + "message": "פתחה" + }, + "settings.advanced.port.error": { + "message": "נא למלא פתחה בין {min} ל־{max}." + }, + "settings.advanced.port.help": { + "message": "אם מוגדר ל־0, ייעשה שימוש בפתחה פנויה אקראית." + }, + "settings.advanced.mtu.label": { + "message": "MTU" + }, + "settings.advanced.mtu.error": { + "message": "נא למלא ערך MTU בין {min} לבין {max}." + }, + "settings.advanced.psk.label": { + "message": "מפתח ששותף מראש" + }, + "settings.advanced.psk.help": { + "message": "מפתח ששותף מראש (PSK) של WireGuard כרשות להצפנה סימטרית בנוסף. לא זהה למפתח התקנה של NetBird. תהיה לך תקשורת רק מול עמיתים שמשתמשים באותו המפתח ששותף מראש." + }, + "settings.troubleshooting.section.title": { + "message": "מאגד ניפוי שגיאות" + }, + "settings.troubleshooting.anonymize.label": { + "message": "הסוואת מידע רגיש עם מידע אלמוני" + }, + "settings.troubleshooting.anonymize.help": { + "message": "הסתרת כתובות IP ציבוריות ושמות תחום שאינם של NetBird מהיומנים." + }, + "settings.troubleshooting.anonymize.info": { + "message": "ברירת המחדל משאירה את כתובות ה־IPv4 הפנימיות ואת שמות העמיתים קריאים למטרות תמיכה. מצב מחמיר מסתיר באלמוניות כתובות פרטיות (RFC 1918), CGNAT ו־link-local (קישור מקומי), שמות עמיתים ומפתחות ציבוריים של WireGuard. ערכים חוזרים ממופים לאותו ממלא המקום, כך שהעמיתים נשארים בלתי ניתנים להבדלה. כדאי להשתמש במחמיר בעת שיתוף המאגד מחוץ לארגון שלך." + }, + "settings.troubleshooting.anonymize.none": { + "message": "ללא" + }, + "settings.troubleshooting.anonymize.default": { + "message": "ברירת מחדל" + }, + "settings.troubleshooting.anonymize.strict": { + "message": "מחמיר" + }, + "settings.troubleshooting.systemInfo.label": { + "message": "לכלול את פרטי המערכת" + }, + "settings.troubleshooting.systemInfo.help": { + "message": "לכלול את מערכת ההפעלה, הליבה, ממשקי הרשת וטבלאות הניתוב." + }, + "settings.troubleshooting.upload.label": { + "message": "להעלות את המאגד לשרתים של NetBird" + }, + "settings.troubleshooting.upload.help": { + "message": "החזרת מפתח שליחה לשיתוף עם התמיכה של NetBird." + }, + "settings.troubleshooting.trace.label": { + "message": "הפעלת יומני מעקב" + }, + "settings.troubleshooting.trace.help": { + "message": "הגברת רמת התיעוד ביומן ל־TRACE (מעקב) ומשחזרת אותה לאחר מכן." + }, + "settings.troubleshooting.capture.label": { + "message": "הפעלת לכידה" + }, + "settings.troubleshooting.capture.help": { + "message": "חיבור מחדש והמתנה כדי לאפשר ליצור את התקלה מחדש." + }, + "settings.troubleshooting.packets.label": { + "message": "לכידת מנות נתונים מהרשת" + }, + "settings.troubleshooting.packets.help": { + "message": "שמירת ‎.pcap של תעבורת רשת בזמן חלון האיסוף." + }, + "settings.troubleshooting.duration.label": { + "message": "משך לכידה" + }, + "settings.troubleshooting.duration.help": { + "message": "למשך כמה זמן הפעלת הלכידה רצה." + }, + "settings.troubleshooting.duration.suffix": { + "message": "דקה/ות" + }, + "settings.troubleshooting.create": { + "message": "יצירת מאגד" + }, + "settings.troubleshooting.progress.description": { + "message": "היומנים, פרטי המערכת ומצב החיבור נאספים. האיסוף בדרך כלל לוקח כמה רגעים. אפשר להמשיך להשתמש ב־NetBird או לסגור את ההגדרות בזמן שהתהליך מסתיים." + }, + "settings.troubleshooting.cancelling": { + "message": "מבוטל…" + }, + "settings.troubleshooting.done.uploadedTitle": { + "message": "מאגד ניפוי השגיאות נשלח בהצלחה!" + }, + "settings.troubleshooting.done.savedTitle": { + "message": "המאגד נשמר" + }, + "settings.troubleshooting.done.uploadedDescription": { + "message": "יש לשתף את מפתח השליחה להלן עם התמיכה של NetBird. עותק מקומי נשמר בנוסף על המכונה שלך." + }, + "settings.troubleshooting.done.savedDescription": { + "message": "מאגד ניפוי השגיאות שלך נשמר מקומית." + }, + "settings.troubleshooting.done.copyKey": { + "message": "העתקת מפתח" + }, + "settings.troubleshooting.done.openFolder": { + "message": "פתיחת תיקייה" + }, + "settings.troubleshooting.done.openFileLocation": { + "message": "פתיחת מקום הקובץ" + }, + "settings.troubleshooting.uploadFailedWithReason": { + "message": "ההעלאה נכשלה: {reason}, המאגד עדיין שמור מקומית." + }, + "settings.troubleshooting.uploadFailed": { + "message": "ההעלאה נכשלה. המאגד עדיין שמור מקומית." + }, + "settings.troubleshooting.stage.reconnecting": { + "message": "NetBird מתחבר מחדש…" + }, + "settings.troubleshooting.stage.capturing": { + "message": "יומני ניפוי השגיאות נלכדים" + }, + "settings.troubleshooting.stage.bundling": { + "message": "מאגד ניפוי שגיאות נוצר…" + }, + "settings.troubleshooting.stage.uploading": { + "message": "נשלח ל־NetBird…" + }, + "settings.troubleshooting.stage.cancelling": { + "message": "מבטל…" + }, + "settings.about.client": { + "message": "לקוח NetBird v{version}" + }, + "settings.about.clientName": { + "message": "לקוח NetBird" + }, + "settings.about.development": { + "message": "[פיתוח]" + }, + "settings.about.gui": { + "message": "ממשק משתמש v{version}" + }, + "settings.about.guiName": { + "message": "ממשק משתמש" + }, + "settings.about.copyright": { + "message": "© {year} NetBird. כל הזכויות שמורות." + }, + "settings.about.links.imprint": { + "message": "הצהרה משפטית" + }, + "settings.about.links.privacy": { + "message": "פרטיות" + }, + "settings.about.links.cla": { + "message": "CLA" + }, + "settings.about.links.terms": { + "message": "תנאי השירות" + }, + "settings.about.community.github": { + "message": "GitHub" + }, + "settings.about.community.slack": { + "message": "Slack" + }, + "settings.about.community.forum": { + "message": "פורום" + }, + "settings.about.community.documentation": { + "message": "תיעוד" + }, + "settings.about.community.feedback": { + "message": "משוב" + }, + "update.banner.message": { + "message": "ההתקנה של NetBird {version} מוכנה." + }, + "update.banner.later": { + "message": "אחר כך" + }, + "update.banner.installNow": { + "message": "להתקין עכשיו" + }, + "update.card.versionAvailableDownload": { + "message": "גרסה {version} זמינה להורדה." + }, + "update.card.versionAvailableInstall": { + "message": "גרסה {version} זמינה להתקנה." + }, + "update.card.whatsNew": { + "message": "מה חדש?" + }, + "update.card.installNow": { + "message": "להתקין עכשיו" + }, + "update.card.getInstaller": { + "message": "הורדה" + }, + "update.card.autoCheckInterval": { + "message": "NetBird בודק ברקע אם יש עדכונים." + }, + "update.card.changelog": { + "message": "יומן שינויים" + }, + "update.card.onLatestVersion": { + "message": "הגרסה המותקנת היא העדכנית ביותר" + }, + "update.header.tooltip": { + "message": "יש עדכון" + }, + "update.overlay.updatingVersion": { + "message": "NetBird מתעדכן ל־v{version}" + }, + "update.overlay.updating": { + "message": "NetBird מתעדכן" + }, + "update.overlay.description": { + "message": "גרסה חדשה יותר זמינה ומותקנת כרגע. NetBird יופעל מחדש אוטומטית לאחר סיום העדכון." + }, + "update.overlay.error.timeoutTitle": { + "message": "העדכון אורך זמן רב מדי" + }, + "update.overlay.error.timeoutDescription": { + "message": "התקנת {target} ארכה זמן רב מדי ולא הסתיימה." + }, + "update.overlay.error.canceledTitle": { + "message": "העדכון נעצר" + }, + "update.overlay.error.canceledDescription": { + "message": "העדכון לגרסה {target} בוטל לפני שהספיק להסתיים." + }, + "update.overlay.error.failTitle": { + "message": "לא ניתן להתקין את העדכון" + }, + "update.overlay.error.failDescription": { + "message": "לא ניתן להתקין את {target}." + }, + "update.overlay.error.unknownMessage": { + "message": "שגיאה לא ידועה" + }, + "update.overlay.error.targetVersion": { + "message": "v{version}" + }, + "update.overlay.error.targetFallback": { + "message": "הגרסה החדשה" + }, + "update.error.loadStateTitle": { + "message": "טעינת מצב העדכון נכשלה" + }, + "update.error.triggerTitle": { + "message": "התחלת העדכון נכשלה" + }, + "update.page.versionLine": { + "message": "הלקוח מתעדכן לגרסה: {version}." + }, + "update.page.versionLineGeneric": { + "message": "הלקוח מתעדכן." + }, + "update.page.outdated": { + "message": "גרסת הלקוח שלך ישנה מגרסת העדכון האוטומטי שהוגדרה בניהול." + }, + "update.page.status.running": { + "message": "מתעדכן" + }, + "update.page.status.timeout": { + "message": "הזמן שהוקצב לעדכון הסתיים. נא לנסות שוב." + }, + "update.page.status.canceled": { + "message": "העדכון בוטל." + }, + "update.page.status.failed": { + "message": "העדכון נכשל: {message}" + }, + "update.page.status.unknownError": { + "message": "שגיאת עדכון לא ידועה" + }, + "update.page.failedTitle": { + "message": "העדכון נכשל" + }, + "update.page.timeoutMessage": { + "message": "הזמן שהוקצב לעדכון תם." + }, + "update.page.dontClose": { + "message": "נא לא לסגור את החלון הזה" + }, + "update.page.updating": { + "message": "מתעדכן…" + }, + "update.page.complete": { + "message": "העדכון הושלם" + }, + "update.page.failed": { + "message": "העדכון נכשל" + }, + "window.title.settings": { + "message": "הגדרות" + }, + "window.title.signIn": { + "message": "כניסה" + }, + "window.title.sessionExpiration": { + "message": "תוקף ההפעלה פג" + }, + "window.title.updating": { + "message": "מתעדכן" + }, + "window.title.welcome": { + "message": "ברוך בואך ל־NetBird" + }, + "window.title.error": { + "message": "שגיאה" + }, + "welcome.title": { + "message": "כדאי לחפש את NetBird בשורת המשימות שלך" + }, + "welcome.titleMac": { + "message": "כדאי לחפש את NetBird בשורת התפריטים שלך" + }, + "welcome.description": { + "message": "NetBird שוכן בשורת המשימות שלך. יש ללחוץ על הסמל כדי להתחבר, להחליף פרופילים או כדי לפתוח את ההגדרות." + }, + "welcome.descriptionMac": { + "message": "NetBird שוכן בסרגל התפריטים שלך. יש ללחוץ על הסמל כדי להתחבר, להחליף פרופילים או כדי לפתוח את ההגדרות." + }, + "welcome.continue": { + "message": "המשך" + }, + "welcome.back": { + "message": "חזרה" + }, + "welcome.management.title": { + "message": "הגדרת NetBird" + }, + "welcome.management.description": { + "message": "יש ללחוץ על המשך כדי להתחיל או לבחור באירוח עצמי אם יש לך שרת NetBird משלך." + }, + "welcome.management.cloud.title": { + "message": "ענן NetBird" + }, + "welcome.management.cloud.description": { + "message": "אפשר להשתמש בשירות באירוח שלנו. לא צריך הגדרות." + }, + "welcome.management.selfHosted.title": { + "message": "אירוח עצמי" + }, + "welcome.management.selfHosted.description": { + "message": "התחברות לשרת ניהול משלך." + }, + "welcome.management.urlLabel": { + "message": "כתובת שרת ניהול" + }, + "welcome.management.urlPlaceholder": { + "message": "https://netbird.selfhosted.com:443" + }, + "welcome.management.urlInvalid": { + "message": "נא למלא כתובת שרת ניהול תקפה, כגון, https://netbird.selfhosted.com:443" + }, + "welcome.management.urlUnreachable": { + "message": "לא ניתן להגיע לשרת הזה. נא לבדוק את הכתובת או את הרשת שלך, לאחר מכן להמשיך אם היא נכונה בוודאות." + }, + "welcome.management.checking": { + "message": "מתבצעת בדיקה…" + }, + "browserLogin.title": { + "message": "יש להשלים את הכניסה בדפדפן שלך" + }, + "browserLogin.notSeeing": { + "message": "פתחנו לשונית בדפדפן כדי לאפשר לך לסיים את הכניסה למערכת. לא רואה אותה?" + }, + "browserLogin.tryAgain": { + "message": "לנסות שוב" + }, + "browserLogin.openFailedTitle": { + "message": "פתיחת הדפדפן נכשלה" + }, + "sessionExpiration.title": { + "message": "תוקף ההפעלה עומד לפוג בקרוב" + }, + "sessionExpiration.titleLater": { + "message": "תוקף ההפעלה שלך יפוג" + }, + "sessionExpiration.description": { + "message": "המכשיר הזה ינותק בהקדם. יש לחדש את הכניסה דרך הדפדפן." + }, + "sessionExpiration.descriptionLater": { + "message": "כניסה עם דפדפן משאירה את המכשיר הזה מחובר לרשת שלך." + }, + "sessionExpiration.stay": { + "message": "חידוש הפעלה" + }, + "sessionExpiration.authenticate": { + "message": "אימות" + }, + "sessionExpiration.logout": { + "message": "יציאה" + }, + "sessionExpiration.expired": { + "message": "תוקף ההפעלה פג" + }, + "sessionExpiration.expiredDescription": { + "message": "המכשיר נותק. יש לעבור אימות עם כניסת דפדפן כדי להתחבר מחדש." + }, + "sessionExpiration.close": { + "message": "סגירה" + }, + "sessionExpiration.extendFailedTitle": { + "message": "הארכת ההפעלה נכשלה" + }, + "sessionExpiration.logoutFailedTitle": { + "message": "היציאה מהחשבון נכשלה" + }, + "peers.search.placeholder": { + "message": "חיפוש לפי שם או IP" + }, + "peers.filter.all": { + "message": "כולם" + }, + "peers.filter.online": { + "message": "מחוברים" + }, + "peers.filter.offline": { + "message": "מנותקים" + }, + "peers.empty.title": { + "message": "אין עמיתים זמינים" + }, + "peers.empty.description": { + "message": "או שאין לך עמיתים זמינים או שאין לך גישה לאף אחד מהם." + }, + "peers.details.domain": { + "message": "שם תחום" + }, + "peers.details.netbirdIp": { + "message": "IP של NetBird" + }, + "peers.details.netbirdIpv6": { + "message": "IPv6 של NetBird" + }, + "peers.details.publicKey": { + "message": "מפתח ציבורי" + }, + "peers.details.connection": { + "message": "חיבור" + }, + "peers.details.latency": { + "message": "עיכוב" + }, + "peers.details.lastHandshake": { + "message": "לחיצת יד אחרונה" + }, + "peers.details.statusSince": { + "message": "עדכון אחרון על החיבור" + }, + "peers.details.bytes": { + "message": "בתים" + }, + "peers.details.bytesSent": { + "message": "נשלחו" + }, + "peers.details.bytesReceived": { + "message": "התקבלו" + }, + "peers.details.localIce": { + "message": "ICE מקומי" + }, + "peers.details.remoteIce": { + "message": "ICE מרוחק" + }, + "peers.details.never": { + "message": "אף פעם לא" + }, + "peers.details.justNow": { + "message": "כרגע" + }, + "peers.details.refresh": { + "message": "ריענון" + }, + "peers.status.connected": { + "message": "מחובר" + }, + "peers.status.connecting": { + "message": "מתחבר" + }, + "peers.status.disconnected": { + "message": "מנותק" + }, + "peers.details.relayAddress": { + "message": "ממסר" + }, + "peers.details.networks": { + "message": "משאבים" + }, + "peers.details.relayed": { + "message": "דרך ממסר" + }, + "peers.details.p2p": { + "message": "P2P" + }, + "peers.details.rosenpass": { + "message": "Rosenpass הופעל" + }, + "networks.search.placeholder": { + "message": "חיפוש לפי רשת או שם תחום" + }, + "networks.filter.all": { + "message": "כולן" + }, + "networks.filter.active": { + "message": "פעילות" + }, + "networks.filter.overlapping": { + "message": "חופפות" + }, + "networks.empty.title": { + "message": "אין משאבים זמינים" + }, + "networks.empty.description": { + "message": "או שאין לך משאבי רשת זמינים או שאין לך גישה לאף אחד מהם." + }, + "networks.selected": { + "message": "נבחרה" + }, + "networks.unselected": { + "message": "לא נבחרה" + }, + "networks.ips.heading": { + "message": "כתובות IP שנפתרו" + }, + "networks.bulk.selectionCount": { + "message": "{selected} מתוך {total} פעילות" + }, + "networks.bulk.enableAll": { + "message": "להפעיל הכול" + }, + "networks.bulk.disableAll": { + "message": "לכבות הכול" + }, + "exitNodes.search.placeholder": { + "message": "חיפוש נקודות יציאה" + }, + "exitNodes.none": { + "message": "אין" + }, + "exitNodes.empty.title": { + "message": "אין נקודות יציאה זמינות" + }, + "exitNodes.empty.description": { + "message": "לא שותפו נקודות יציאה עם העמית הזה." + }, + "exitNodes.card.title": { + "message": "נקודת יציאה" + }, + "exitNodes.card.statusActive": { + "message": "פעילה" + }, + "exitNodes.card.statusInactive": { + "message": "כבויה" + }, + "exitNodes.dropdown.noneTitle": { + "message": "אין" + }, + "exitNodes.dropdown.noneDescription": { + "message": "חיבור ישיר ללא נקודת יציאה" + }, + "quickActions.connect": { + "message": "התחברות" + }, + "quickActions.disconnect": { + "message": "התנתקות" + }, + "daemon.unavailable.title": { + "message": "שירות NetBird לא פעיל" + }, + "daemon.unavailable.description": { + "message": "היישום יתחבר אוטומטית לאחר שהשירות יופעל." + }, + "daemon.unavailable.docsLink": { + "message": "תיעוד" + }, + "daemon.outdated.title": { + "message": "שירות NetBird אינו עדכני" + }, + "daemon.outdated.description": { + "message": "ממשק המשתמש החדש לא תואם ללקוח ישן יותר של NetBird. יש לעדכן את הלקוח שלך כדי להשתמש ביישום החדש" + }, + "daemon.outdated.download": { + "message": "להוריד את העדכני ביותר" + }, + "error.jwt_clock_skew": { + "message": "הכניסה נכשלה: השעון של המכשיר הזה לא תואם במדויק את זה של השרת. נא לכוון את שעון המערכת שלך ולנסות שוב." + }, + "error.jwt_expired": { + "message": "תוקף אסימון הכניסה שלך פג. נא להיכנס שוב." + }, + "error.jwt_signature_invalid": { + "message": "הכניסה נכשלה: חתימת האסימון שגויה. נא ליצור קשר עם הנהלת המערכת שלך." + }, + "error.session_expired": { + "message": "תוקף ההפעלה שלך פג. נא להיכנס שוב." + }, + "error.invalid_setup_key": { + "message": "מפתח ההתקנה חסר או שגוי." + }, + "error.permission_denied": { + "message": "בקשת הכניסה נדחתה על ידי השרת." + }, + "error.daemon_unreachable": { + "message": "הסוכן של NetBird לא מגיב. נא לבדוק שהשירות פעיל." + }, + "error.settings_locked": { + "message": "אי אפשר לשנות את ההגדרות במכשיר הזה: הן ננעלו על ידי ההנהלה." + }, + "error.settings_managed_by_mdm": { + "message": "ההגדרה הזאת מנוהלת על ידי הארגון שלך ואי אפשר לשנות אותה." + }, + "error.unknown": { + "message": "הפעולה נכשלה." + }, + "error.elevation_unavailable": { + "message": "NetBird לא הצליח לבקש מהמערכת הזאת את ההרשאות שהשינוי הזה צריך. יש להריץ את זה במקום:" + }, + "error.elevation_failed": { + "message": "אי אפשר להחיל את השינויים עם הרשאות גבוהות יותר. יש להריץ את זה במקום:" + }, + "settings.ssh.privilege.actorRoot": { + "message": "משתמש על/root" + }, + "settings.ssh.privilege.actorAdministrator": { + "message": "הרשאות ניהול" + }, + "settings.ssh.privilege.hint": { + "message": "דורש {actor}. יש להריץ את זה במקום:" + }, + "settings.ssh.privilege.oneWay": { + "message": "אפשר לכבות את זה, אבל ההפעלה דורשת {actor}." + }, + "settings.ssh.privilege.oneWayInverted": { + "message": "אפשר להפעיל את זה, אבל הכיבוי דורש {actor}." + }, + "settings.ssh.privilege.authorizePending": { + "message": "בהמתנה לאימות…" + } +} diff --git a/client/ui/i18n/locales/hu/common.json b/client/ui/i18n/locales/hu/common.json index 94dcb578c..36705afbc 100644 --- a/client/ui/i18n/locales/hu/common.json +++ b/client/ui/i18n/locales/hu/common.json @@ -552,12 +552,10 @@ "message": "Az automatikus indítás módosítása sikertelen" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Kapcsolat megtartása kilépéskor", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Kapcsolat megtartása kilépéskor" }, "settings.general.keepConnectedOnQuit.help": { - "message": "A kapcsolat a háttérben megmarad, miután bezárod a NetBirdöt. Csak akkor szakad meg, ha te magad bontod.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "A kapcsolat a háttérben megmarad, miután bezárod a NetBirdöt. Csak akkor szakad meg, ha te magad bontod." }, "settings.general.language.label": { "message": "Megjelenítési nyelv" diff --git a/client/ui/i18n/locales/it/common.json b/client/ui/i18n/locales/it/common.json index 8c1312535..6590a01fe 100644 --- a/client/ui/i18n/locales/it/common.json +++ b/client/ui/i18n/locales/it/common.json @@ -552,12 +552,10 @@ "message": "Modifica avvio automatico non riuscita" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Resta connesso dopo la chiusura", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Resta connesso dopo la chiusura" }, "settings.general.keepConnectedOnQuit.help": { - "message": "La connessione resta attiva in background dopo la chiusura di NetBird. Si interrompe solo quando la disconnetti tu.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "La connessione resta attiva in background dopo la chiusura di NetBird. Si interrompe solo quando la disconnetti tu." }, "settings.general.language.label": { "message": "Lingua dell'interfaccia" diff --git a/client/ui/i18n/locales/ja/common.json b/client/ui/i18n/locales/ja/common.json index a3138de6c..c8918e4ae 100644 --- a/client/ui/i18n/locales/ja/common.json +++ b/client/ui/i18n/locales/ja/common.json @@ -552,12 +552,10 @@ "message": "自動起動の変更に失敗しました" }, "settings.general.keepConnectedOnQuit.label": { - "message": "終了後も接続を維持", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "終了後も接続を維持" }, "settings.general.keepConnectedOnQuit.help": { - "message": "NetBird を閉じたあとも接続はバックグラウンドで維持されます。自分で切断したときにだけ停止します。", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "NetBird を閉じたあとも接続はバックグラウンドで維持されます。自分で切断したときにだけ停止します。" }, "settings.general.language.label": { "message": "表示言語" diff --git a/client/ui/i18n/locales/pt/common.json b/client/ui/i18n/locales/pt/common.json index a75ae3dfc..aca458a4d 100644 --- a/client/ui/i18n/locales/pt/common.json +++ b/client/ui/i18n/locales/pt/common.json @@ -552,12 +552,10 @@ "message": "Falha ao alterar o início automático" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Permanecer conectado ao sair", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Permanecer conectado ao sair" }, "settings.general.keepConnectedOnQuit.help": { - "message": "A conexão continua ativa em segundo plano depois de fechar o NetBird. Ela só para quando você mesmo a desconecta.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "A conexão continua ativa em segundo plano depois de fechar o NetBird. Ela só para quando você mesmo a desconecta." }, "settings.general.language.label": { "message": "Idioma de exibição" diff --git a/client/ui/i18n/locales/ru/common.json b/client/ui/i18n/locales/ru/common.json index e11ed26a4..a0795c1da 100644 --- a/client/ui/i18n/locales/ru/common.json +++ b/client/ui/i18n/locales/ru/common.json @@ -552,12 +552,10 @@ "message": "Не удалось изменить автозапуск" }, "settings.general.keepConnectedOnQuit.label": { - "message": "Оставаться подключённым после выхода", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "Оставаться подключённым после выхода" }, "settings.general.keepConnectedOnQuit.help": { - "message": "Соединение остаётся активным в фоне после закрытия NetBird. Оно прервётся, только когда вы отключите его сами.", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "Соединение остаётся активным в фоне после закрытия NetBird. Оно прервётся, только когда вы отключите его сами." }, "settings.general.language.label": { "message": "Язык интерфейса" diff --git a/client/ui/i18n/locales/zh-CN/common.json b/client/ui/i18n/locales/zh-CN/common.json index 64725a69f..9f4713899 100644 --- a/client/ui/i18n/locales/zh-CN/common.json +++ b/client/ui/i18n/locales/zh-CN/common.json @@ -552,12 +552,10 @@ "message": "更改自启动设置失败" }, "settings.general.keepConnectedOnQuit.label": { - "message": "退出后保持连接", - "description": "Toggle label: keep the VPN connection up after quitting the UI." + "message": "退出后保持连接" }, "settings.general.keepConnectedOnQuit.help": { - "message": "关闭 NetBird 后,连接会在后台保持。只有你自己断开时才会停止。", - "description": "Helper text for the stay-connected-after-quitting toggle." + "message": "关闭 NetBird 后,连接会在后台保持。只有你自己断开时才会停止。" }, "settings.general.language.label": { "message": "显示语言" From 0bb98547042986f02a47a07ac70557a8b2893dcf Mon Sep 17 00:00:00 2001 From: Edward <43848523+thomashacker@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:39:17 +0200 Subject: [PATCH 06/15] [client] Add Hebrew to the language picker (#8102) The Hebrew translation is complete and synced from Crowdin, and RTL layout support is in, so list it in _index.json. --- client/ui/i18n/locales/_index.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/ui/i18n/locales/_index.json b/client/ui/i18n/locales/_index.json index a52ff5929..4e9b632b5 100644 --- a/client/ui/i18n/locales/_index.json +++ b/client/ui/i18n/locales/_index.json @@ -11,6 +11,7 @@ {"code": "pt", "displayName": "Português", "englishName": "Portuguese"}, {"code": "zh-CN", "displayName": "简体中文", "englishName": "Simplified Chinese"}, {"code": "ja", "displayName": "日本語", "englishName": "Japanese"}, - {"code": "gl", "displayName": "Galego", "englishName": "Galician"} + {"code": "gl", "displayName": "Galego", "englishName": "Galician"}, + {"code": "he", "displayName": "עברית", "englishName": "Hebrew"} ] } From 36fe467aba4239cb3df9d00b2f3feb75d86bbc91 Mon Sep 17 00:00:00 2001 From: Maycon Santos Date: Mon, 19 Oct 2026 18:47:25 +0200 Subject: [PATCH 07/15] [client] Avoid Signal reconnect listener shutdown deadlock (#8257) * [client] Reproduce Signal reconnect listener shutdown deadlock * [client] Invoke Signal reconnect listeners outside the client mutex Capture the listener with the registration state, then release the mutex before calling it. Watcher shutdown can now unregister a listener while an in-flight callback waits for the watcher lock. Keep callback invocation synchronous and document that unregistration does not drain an already captured callback. Record callback completion inside the regression test's external lock. --- shared/signal/client/grpc.go | 10 ++- shared/signal/client/reconnect_test.go | 98 ++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 3 deletions(-) create mode 100644 shared/signal/client/reconnect_test.go diff --git a/shared/signal/client/grpc.go b/shared/signal/client/grpc.go index e489078a9..22239047b 100644 --- a/shared/signal/client/grpc.go +++ b/shared/signal/client/grpc.go @@ -299,7 +299,6 @@ func (c *GrpcClient) notifyStreamDisconnected() { func (c *GrpcClient) notifyStreamConnected() { c.mux.Lock() - defer c.mux.Unlock() c.status = StreamConnected if c.connectedCh != nil { @@ -308,8 +307,12 @@ func (c *GrpcClient) notifyStreamConnected() { c.connectedCh = nil } - if c.onReconnectedListenerFn != nil { - c.onReconnectedListenerFn() + listener := c.onReconnectedListenerFn + c.mux.Unlock() + + // Listeners can hold their own locks while unregistering from this client. + if listener != nil { + listener() } } @@ -409,6 +412,7 @@ func (c *GrpcClient) WaitStreamConnected(ctx context.Context) { } } +// SetOnReconnectedListener replaces the listener without waiting for an in-flight callback. func (c *GrpcClient) SetOnReconnectedListener(fn func()) { c.mux.Lock() defer c.mux.Unlock() diff --git a/shared/signal/client/reconnect_test.go b/shared/signal/client/reconnect_test.go new file mode 100644 index 000000000..bf4e2cb87 --- /dev/null +++ b/shared/signal/client/reconnect_test.go @@ -0,0 +1,98 @@ +package client + +import ( + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestReconnectListenerCanBeClearedWhileCallbackIsBlocked(t *testing.T) { + client := &GrpcClient{} + var listenerMu sync.Mutex + callbackStarted := make(chan struct{}) + callbackFinished := make(chan struct{}) + callbackCalls := 0 + client.SetOnReconnectedListener(func() { + callbackCalls++ + close(callbackStarted) + listenerMu.Lock() + close(callbackFinished) + listenerMu.Unlock() + }) + + // SRWatcher.Close holds its own mutex while removing the listener. A + // reconnect callback waiting for that mutex must not block its removal. + listenerMu.Lock() + notificationDone := make(chan struct{}) + go func() { + defer close(notificationDone) + client.notifyStreamConnected() + }() + var unregisterDone chan struct{} + t.Cleanup(func() { + // Release the callback even when the regression assertion fails, so + // the unfixed implementation does not leave deadlocked goroutines. + listenerMu.Unlock() + select { + case <-notificationDone: + select { + case <-callbackFinished: + default: + t.Error("in-flight callback did not finish after listener removal") + } + case <-time.After(5 * time.Second): + t.Error("reconnect notification did not finish after releasing the listener") + } + if unregisterDone != nil { + select { + case <-unregisterDone: + case <-time.After(5 * time.Second): + t.Error("listener removal did not finish after releasing the listener") + } + } + }) + + select { + case <-callbackStarted: + case <-time.After(5 * time.Second): + t.Fatal("reconnect callback did not start") + } + + unregisterDone = make(chan struct{}) + go func() { + client.SetOnReconnectedListener(nil) + close(unregisterDone) + }() + select { + case <-unregisterDone: + case <-time.After(5 * time.Second): + t.Fatal("listener removal blocked behind the reconnect callback") + } + + // Registration still becomes visible, and future notifications do not + // invoke the removed listener even while its first callback is in flight. + assert.True(t, client.StreamConnected(), "listener removal must preserve stream registration") + client.notifyStreamConnected() + assert.Equal(t, 1, callbackCalls, "future notifications must not invoke the removed listener") +} + +func TestReconnectListenerRunsAfterRegistrationWaitersAreReleased(t *testing.T) { + connected := make(chan struct{}) + client := &GrpcClient{connectedCh: connected} + called := false + client.SetOnReconnectedListener(func() { + called = true + select { + case <-connected: + default: + t.Error("reconnect callback ran before registration waiters were released") + } + }) + + client.notifyStreamConnected() + + assert.True(t, called, "reconnect notification must invoke its listener synchronously") + assert.True(t, client.StreamConnected(), "stream must remain registered after the callback") +} From 8fef487e4256e592c1ff916fd9cd155f1849b881 Mon Sep 17 00:00:00 2001 From: dmitri-netbird Date: Mon, 19 Oct 2026 22:19:39 +0200 Subject: [PATCH 08/15] [management] Add support for pagination in GetAllPeers call (#8190) * use libopenapi OpenAPI generator Signed-off-by: Dmitri Dolguikh * added a handler for v1alpha1/peers Signed-off-by: Dmitri Dolguikh * wire up request validator Signed-off-by: Dmitri Dolguikh * wired up spec-based validation Signed-off-by: Dmitri Dolguikh * use sync validation; set base url to v1alpha1 Signed-off-by: Dmitri Dolguikh * moved stuff around, extracted runtime libopenapu deps into runtime_tooling Signed-off-by: Dmitri Dolguikh * testing /peers path params Signed-off-by: Dmitri Dolguikh * fixed tests Signed-off-by: Dmitri Dolguikh * added user schemas and paths Signed-off-by: Dmitri Dolguikh * use api validation in tests Signed-off-by: Dmitri Dolguikh * post-merge fixes Signed-off-by: Dmitri Dolguikh * deleted tmp command used to test validator integration Signed-off-by: Dmitri Dolguikh * require request body in post/put requests in order to force validation Signed-off-by: Dmitri Dolguikh * making linter happy Signed-off-by: Dmitri Dolguikh * switch to api/v1alpha1 Signed-off-by: Dmitri Dolguikh * go mod tidy Signed-off-by: Dmitri Dolguikh * keep the original order of middleware: metrics, cors, then auth Signed-off-by: Dmitri Dolguikh * return 422 on validation errors Signed-off-by: Dmitri Dolguikh * cleanups Signed-off-by: Dmitri Dolguikh * more cleanups Signed-off-by: Dmitri Dolguikh * v1alpha1 spec cleanups Signed-off-by: Dmitri Dolguikh * no need for a double-pointer Signed-off-by: Dmitri Dolguikh * more linter fixes Signed-off-by: Dmitri Dolguikh * removed more double pointers Signed-off-by: Dmitri Dolguikh * use di to inject api_v0 and api_v1 http routers Signed-off-by: Dmitri Dolguikh * do not re-add middleware on repeated call to ApiHandler Signed-off-by: Dmitri Dolguikh * support for pagination and filtering in /peers call Signed-off-by: Dmitri Dolguikh * calling ApiRouter() now also calls ApiV1Router() Signed-off-by: Dmitri Dolguikh * adding peer filters Signed-off-by: Dmitri Dolguikh * introduced paginated GetAllPeers call Signed-off-by: Dmitri Dolguikh * wire up pagination Signed-off-by: Dmitri Dolguikh * convert pagination state to query scope Signed-off-by: Dmitri Dolguikh * peer filter wip Signed-off-by: Dmitri Dolguikh * implemented peer filter Signed-off-by: Dmitri Dolguikh * test for filtering by os Signed-off-by: Dmitri Dolguikh * support for sorting of peers Signed-off-by: Dmitri Dolguikh * support for ordering + tests Signed-off-by: Dmitri Dolguikh * more tests Signed-off-by: Dmitri Dolguikh * wire up total number of records in paginated GetAllPeers call Signed-off-by: Dmitri Dolguikh * cleaned up GetAllPeers response Signed-off-by: Dmitri Dolguikh * pacify linter Signed-off-by: Dmitri Dolguikh * cleanups and fixes Signed-off-by: Dmitri Dolguikh * moar cleanups Signed-off-by: Dmitri Dolguikh * pacify linter Signed-off-by: Dmitri Dolguikh * remove duplicated test Signed-off-by: Dmitri Dolguikh * make linter happy Signed-off-by: Dmitri Dolguikh * moving GetAllPeersPaginated to peer manager, p. 1 Signed-off-by: Dmitri Dolguikh * moving GetAllPeersPaginated to peer manager, p. 2 Signed-off-by: Dmitri Dolguikh * added peer manager tests for GetPeersPaginated Signed-off-by: Dmitri Dolguikh * order peers in GetAccountPeersPaginated by their ids by default Signed-off-by: Dmitri Dolguikh * always order by peer_id, filter out proxies Signed-off-by: Dmitri Dolguikh * fixed broken tests Signed-off-by: Dmitri Dolguikh * support for filtering of peers by peer_id in GetAllPeers() Signed-off-by: Dmitri Dolguikh * filtering by peer_ids Signed-off-by: Dmitri Dolguikh * use lowercase in 'like' queries, drop ordering by ip Signed-off-by: Dmitri Dolguikh * drop sort_by ip key Signed-off-by: Dmitri Dolguikh * drop forced_approve filter Signed-off-by: Dmitri Dolguikh * replace mac with darwin in peer os filter Signed-off-by: Dmitri Dolguikh * fix peers query parameter: use peer_ids Signed-off-by: Dmitri Dolguikh * fixed broken peer_test Signed-off-by: Dmitri Dolguikh * responded to feedback Signed-off-by: Dmitri Dolguikh --------- Signed-off-by: Dmitri Dolguikh --- management/internals/modules/peers/manager.go | 47 ++-- .../internals/modules/peers/manager_mock.go | 32 +-- .../internals/modules/peers/manager_test.go | 197 ++++++++++++++ management/internals/server/boot.go | 2 +- management/server/api/v1alpha1/handler.go | 4 +- .../api/v1alpha1/peers/peers_handler.go | 224 ++++++++++------ .../peers/peers_handler_pagination_test.go | 191 +++++++++++++ .../api/v1alpha1/peers/peers_handler_test.go | 162 +++++++++--- .../handlers/groups/groups_handler_test.go | 4 +- .../http/handlers/peers/peers_handler_test.go | 4 +- management/server/mock_server/account_mock.go | 5 +- management/server/peer.go | 4 +- management/server/peer_test.go | 1 - management/server/store/sql_store_peer.go | 159 ++++++++++- .../server/store/sql_store_peer_test.go | 4 +- .../store/sql_store_peers_filter_test.go | 250 ++++++++++++++++++ management/server/store/sql_store_test.go | 16 ++ management/server/store/store.go | 117 ++++++-- management/server/store/store_mock.go | 16 ++ .../server/testdata/peers_pagination.sql | 112 ++++++++ .../management/http/apiv1alpha1/bundle.yaml | 116 ++++++-- .../http/apiv1alpha1/peer/components.yaml | 40 +-- .../http/apiv1alpha1/peer/peers.yaml | 76 +++++- .../management/http/apiv1alpha1/types.gen.go | 18 +- 24 files changed, 1571 insertions(+), 230 deletions(-) create mode 100644 management/internals/modules/peers/manager_test.go create mode 100644 management/server/api/v1alpha1/peers/peers_handler_pagination_test.go create mode 100644 management/server/store/sql_store_peers_filter_test.go create mode 100644 management/server/testdata/peers_pagination.sql diff --git a/management/internals/modules/peers/manager.go b/management/internals/modules/peers/manager.go index e944be291..6f9705efe 100644 --- a/management/internals/modules/peers/manager.go +++ b/management/internals/modules/peers/manager.go @@ -28,8 +28,8 @@ import ( type Manager interface { GetPeer(ctx context.Context, accountID, userID, peerID string) (*peer.Peer, error) GetPeerAccountID(ctx context.Context, peerID string) (string, error) - GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error) GetPeersByGroupIDs(ctx context.Context, accountID string, groupsIDs []string) ([]*peer.Peer, error) + GetPeersPaginated(ctx context.Context, accountID, userID string, pagination store.PaginationState, filters store.PeerFilters, sorting store.PeerSorting) ([]*peer.Peer, int, error) DeletePeers(ctx context.Context, accountID string, peerIDs []string, userID string, checkConnected bool) error SetNetworkMapController(networkMapController network_map.Controller) SetIntegratedPeerValidator(integratedPeerValidator integrated_validator.IntegratedValidator) @@ -51,8 +51,7 @@ type managerImpl struct { permissionsManager permissions.Manager integratedPeerValidator integrated_validator.IntegratedValidator accountManager account.Manager - - networkMapController network_map.Controller + networkMapController network_map.Controller } func NewManager(store store.Store, permissionsManager permissions.Manager) Manager { @@ -87,19 +86,6 @@ func (m *managerImpl) GetPeer(ctx context.Context, accountID, userID, peerID str return m.store.GetPeerByID(ctx, store.LockingStrengthNone, accountID, peerID) } -func (m *managerImpl) GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error) { - allowed, ctx, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Peers, operations.Read) - if err != nil { - return nil, fmt.Errorf("failed to validate user permissions: %w", err) - } - - if !allowed { - return m.store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) - } - - return m.store.GetAccountPeers(ctx, store.LockingStrengthNone, accountID, "", "", "") -} - func (m *managerImpl) GetPeerAccountID(ctx context.Context, peerID string) (string, error) { return m.store.GetAccountIDByPeerID(ctx, store.LockingStrengthNone, peerID) } @@ -108,6 +94,35 @@ func (m *managerImpl) GetPeersByGroupIDs(ctx context.Context, accountID string, return m.store.GetPeersByGroupIDs(ctx, accountID, groupsIDs) } +func (m *managerImpl) GetPeersPaginated(ctx context.Context, accountID, userID string, pagination store.PaginationState, filters store.PeerFilters, sorting store.PeerSorting) ([]*peer.Peer, int, error) { + user, err := m.store.GetUserByUserID(ctx, store.LockingStrengthNone, userID) + if err != nil { + return nil, 0, err + } + + allowed, ctx, err := m.permissionsManager.ValidateUserPermissions(ctx, accountID, userID, modules.Peers, operations.Read) + if err != nil { + return nil, 0, status.NewPermissionValidationError(err) + } + + if allowed { + return m.store.GetAccountPeersPaginated(ctx, store.LockingStrengthNone, accountID, pagination, filters, sorting) + } + + settings, err := m.store.GetAccountSettings(ctx, store.LockingStrengthNone, accountID) + if err != nil { + return nil, 0, fmt.Errorf("failed to get account settings: %w", err) + } + + if user.IsRestrictable() && settings.RegularUsersViewBlocked { + return []*peer.Peer{}, 0, nil + } + + peers, err := m.store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) + + return peers, len(peers), err +} + // GetPeerByTunnelIP delegates to the store's indexed lookup. func (m *managerImpl) GetPeerByTunnelIP(ctx context.Context, accountID string, ip net.IP) (*peer.Peer, error) { return m.store.GetPeerByIP(ctx, store.LockingStrengthNone, accountID, ip) diff --git a/management/internals/modules/peers/manager_mock.go b/management/internals/modules/peers/manager_mock.go index 8c26d43b1..ee97ba308 100644 --- a/management/internals/modules/peers/manager_mock.go +++ b/management/internals/modules/peers/manager_mock.go @@ -18,6 +18,7 @@ import ( account "github.com/netbirdio/netbird/management/server/account" integrated_validator "github.com/netbirdio/netbird/management/server/integrations/integrated_validator" peer "github.com/netbirdio/netbird/management/server/peer" + store "github.com/netbirdio/netbird/management/server/store" types "github.com/netbirdio/netbird/management/server/types" gomock "go.uber.org/mock/gomock" ) @@ -74,21 +75,6 @@ func (mr *MockManagerMockRecorder) DeletePeers(ctx, accountID, peerIDs, userID, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePeers", reflect.TypeOf((*MockManager)(nil).DeletePeers), ctx, accountID, peerIDs, userID, checkConnected) } -// GetAllPeers mocks base method. -func (m *MockManager) GetAllPeers(ctx context.Context, accountID, userID string) ([]*peer.Peer, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAllPeers", ctx, accountID, userID) - ret0, _ := ret[0].([]*peer.Peer) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAllPeers indicates an expected call of GetAllPeers. -func (mr *MockManagerMockRecorder) GetAllPeers(ctx, accountID, userID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllPeers", reflect.TypeOf((*MockManager)(nil).GetAllPeers), ctx, accountID, userID) -} - // GetPeer mocks base method. func (m *MockManager) GetPeer(ctx context.Context, accountID, userID, peerID string) (*peer.Peer, error) { m.ctrl.T.Helper() @@ -180,6 +166,22 @@ func (mr *MockManagerMockRecorder) GetPeersByGroupIDs(ctx, accountID, groupsIDs return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeersByGroupIDs", reflect.TypeOf((*MockManager)(nil).GetPeersByGroupIDs), ctx, accountID, groupsIDs) } +// GetPeersPaginated mocks base method. +func (m *MockManager) GetPeersPaginated(ctx context.Context, accountID, userID string, pagination store.PaginationState, filters store.PeerFilters, sorting store.PeerSorting) ([]*peer.Peer, int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPeersPaginated", ctx, accountID, userID, pagination, filters, sorting) + ret0, _ := ret[0].([]*peer.Peer) + ret1, _ := ret[1].(int) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetPeersPaginated indicates an expected call of GetPeersPaginated. +func (mr *MockManagerMockRecorder) GetPeersPaginated(ctx, accountID, userID, pagination, filters, sorting any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeersPaginated", reflect.TypeOf((*MockManager)(nil).GetPeersPaginated), ctx, accountID, userID, pagination, filters, sorting) +} + // SetAccountManager mocks base method. func (m *MockManager) SetAccountManager(accountManager account.Manager) { m.ctrl.T.Helper() diff --git a/management/internals/modules/peers/manager_test.go b/management/internals/modules/peers/manager_test.go new file mode 100644 index 000000000..2645276b7 --- /dev/null +++ b/management/internals/modules/peers/manager_test.go @@ -0,0 +1,197 @@ +package peers + +import ( + "context" + "fmt" + "testing" + + "github.com/netbirdio/netbird/management/server/peer" + "github.com/netbirdio/netbird/management/server/permissions" + "github.com/netbirdio/netbird/management/server/permissions/modules" + "github.com/netbirdio/netbird/management/server/permissions/operations" + "github.com/netbirdio/netbird/management/server/store" + "github.com/netbirdio/netbird/management/server/types" + "github.com/stretchr/testify/assert" + + "go.uber.org/mock/gomock" +) + +func TestManager_GetPeersPaginated_HappyPath(t *testing.T) { + ctrl := gomock.NewController(t) + // GetUserByUserID + // GetAccountPeersPaginated + // GetAccountSettings + // GetUserPeers + mockStore := store.NewMockStore(ctrl) + // ValidateUserPermissions + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(true, context.Background(), nil) + mockStore.EXPECT().GetAccountPeersPaginated(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account"), + gomock.Eq(store.PaginationState{Page: 11, PageSize: 111}), gomock.Eq(store.PeerFilters{UserId: "test-user"}), + gomock.Eq(store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}})).Times(1). + Return([]*peer.Peer{{ID: "test-peer"}}, 10, nil) + + peers, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, []*peer.Peer{{ID: "test-peer"}}, peers) + assert.Equal(t, 10, total) + assert.NoError(t, err) +} + +func TestManager_GetPeersPaginated_GetUserWithError(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(nil, fmt.Errorf("boom!")) + + _, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, 0, total) + assert.ErrorContains(t, err, "boom!") +} + +func TestManager_GetPeersPaginated_NoPermission(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(false, context.Background(), nil) + mockStore.EXPECT().GetAccountSettings(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account")).Times(1). + Return(&types.Settings{RegularUsersViewBlocked: false}, nil) + mockStore.EXPECT().GetUserPeers(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account"), gomock.Eq("test-user")).Times(1). + Return([]*peer.Peer{{ID: "test-peer"}}, nil) + + peers, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, []*peer.Peer{{ID: "test-peer"}}, peers) + assert.Equal(t, 1, total) + assert.NoError(t, err) +} + +func TestManager_GetPeersPaginated_NoPermission_GetUserPeers_WithError(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(false, context.Background(), nil) + mockStore.EXPECT().GetAccountSettings(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account")).Times(1). + Return(&types.Settings{RegularUsersViewBlocked: false}, nil) + mockStore.EXPECT().GetUserPeers(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account"), gomock.Eq("test-user")).Times(1). + Return(nil, fmt.Errorf("boom!")) + + _, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, 0, total) + assert.ErrorContains(t, err, "boom!") +} + +func TestManager_GetPeersPaginated_GetAccountSettings_WithError(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(false, context.Background(), nil) + mockStore.EXPECT().GetAccountSettings(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account")).Times(1). + Return(nil, fmt.Errorf("boom!")) + + _, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, 0, total) + assert.ErrorContains(t, err, "boom!") +} +func TestManager_GetPeersPaginated_NoPermission_User_IsRestrictable_ViewUnblocked(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + Role: types.UserRoleUser, + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(false, context.Background(), nil) + mockStore.EXPECT().GetAccountSettings(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account")).Times(1). + Return(&types.Settings{RegularUsersViewBlocked: false}, nil) + mockStore.EXPECT().GetUserPeers(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account"), gomock.Eq("test-user")).Times(1). + Return([]*peer.Peer{{ID: "test-peer"}}, nil) + + peers, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, []*peer.Peer{{ID: "test-peer"}}, peers) + assert.Equal(t, 1, total) + assert.NoError(t, err) +} + +func TestManager_GetPeersPaginated_NoPermission_User_IsRestrictable_ViewBlocked(t *testing.T) { + ctrl := gomock.NewController(t) + mockStore := store.NewMockStore(ctrl) + permissionsManager := permissions.NewMockManager(ctrl) + + m := NewManager(mockStore, permissionsManager) + + mockStore.EXPECT().GetUserByUserID(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-user")).Times(1). + Return(&types.User{ + Id: "test-user", + Role: types.UserRoleUser, + }, nil) + permissionsManager.EXPECT().ValidateUserPermissions(gomock.Any(), gomock.Eq("test-account"), gomock.Eq("test-user"), gomock.Eq(modules.Peers), gomock.Eq(operations.Read)).Times(1). + Return(false, context.Background(), nil) + mockStore.EXPECT().GetAccountSettings(gomock.Any(), gomock.Eq(store.LockingStrengthNone), gomock.Eq("test-account")).Times(1). + Return(&types.Settings{RegularUsersViewBlocked: true}, nil) + + peers, total, err := m.GetPeersPaginated(context.Background(), "test-account", "test-user", + store.PaginationState{Page: 11, PageSize: 111}, store.PeerFilters{UserId: "test-user"}, + store.PeerSorting{Fields: []store.PeerSortingKey{{Field: store.PeerSortByName, Order: store.DescOrderBy}}}) + + assert.Equal(t, make([]*peer.Peer, 0), peers) + assert.Equal(t, 0, total) + assert.NoError(t, err) +} diff --git a/management/internals/server/boot.go b/management/internals/server/boot.go index 13bbaa6fa..e466005fe 100644 --- a/management/internals/server/boot.go +++ b/management/internals/server/boot.go @@ -165,7 +165,7 @@ func (s *BaseServer) EventStore() activity.Store { func (s *BaseServer) APIHandler() http.Handler { _ = CreateNamed(s, "http_v1api", func() http.Handler { apiv1Router := s.ApiV1Router() - _, err := v1alpha1.NewAPIV1Handler(context.Background(), apiv1Router, s.AccountManager(), s.NetworkMapController(), s.PermissionsManager()) + _, err := v1alpha1.NewAPIV1Handler(context.Background(), apiv1Router, s.AccountManager(), s.PeersManager(), s.NetworkMapController(), s.PermissionsManager()) if err != nil { log.Fatalf("failed to create API handler: %v", err) } diff --git a/management/server/api/v1alpha1/handler.go b/management/server/api/v1alpha1/handler.go index 3af8f4871..21b9bbcec 100644 --- a/management/server/api/v1alpha1/handler.go +++ b/management/server/api/v1alpha1/handler.go @@ -12,6 +12,7 @@ import ( "github.com/netbirdio/netbird/management/server/permissions" + peersmodule "github.com/netbirdio/netbird/management/internals/modules/peers" "github.com/netbirdio/netbird/management/server/api/v1alpha1/peers" "github.com/netbirdio/netbird/management/server/api/v1alpha1/users" ) @@ -20,6 +21,7 @@ func NewAPIV1Handler( ctx context.Context, router *mux.Router, accountManager account.Manager, + peerManager peersmodule.Manager, networkMapController network_map.Controller, permissionsManager permissions.Manager) (http.Handler, error) { @@ -30,7 +32,7 @@ func NewAPIV1Handler( router.Use(v1validatorMiddleware.Handler) - peersHandler := peers.NewHandler(accountManager, networkMapController, permissionsManager) + peersHandler := peers.NewHandler(accountManager, peerManager, networkMapController, permissionsManager) _ = peersHandler.WithEndpointsForRouter(router) usersHandler := users.NewHandler(accountManager) diff --git a/management/server/api/v1alpha1/peers/peers_handler.go b/management/server/api/v1alpha1/peers/peers_handler.go index 8e0593723..50841858c 100644 --- a/management/server/api/v1alpha1/peers/peers_handler.go +++ b/management/server/api/v1alpha1/peers/peers_handler.go @@ -6,17 +6,22 @@ import ( "fmt" "net/http" "net/netip" + "net/url" + "strconv" + "strings" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "github.com/netbirdio/netbird/management/internals/controllers/network_map" + "github.com/netbirdio/netbird/management/internals/modules/peers" "github.com/netbirdio/netbird/management/server/account" "github.com/netbirdio/netbird/management/server/activity" "github.com/netbirdio/netbird/management/server/api/v1alpha1/groups" nbcontext "github.com/netbirdio/netbird/management/server/context" nbpeer "github.com/netbirdio/netbird/management/server/peer" "github.com/netbirdio/netbird/management/server/permissions" + "github.com/netbirdio/netbird/management/server/store" "github.com/netbirdio/netbird/shared/management/http/apiv1alpha1" "github.com/netbirdio/netbird/shared/management/http/util" "github.com/netbirdio/netbird/shared/management/status" @@ -26,12 +31,14 @@ type Handler struct { accountManager account.Manager permissionsManager permissions.Manager networkMapController network_map.Controller + peersManager peers.Manager } // NewHandler creates a new peers Handler -func NewHandler(accountManager account.Manager, networkMapController network_map.Controller, permissionsManager permissions.Manager) *Handler { +func NewHandler(accountManager account.Manager, peerManager peers.Manager, networkMapController network_map.Controller, permissionsManager permissions.Manager) *Handler { return &Handler{ accountManager: accountManager, + peersManager: peerManager, networkMapController: networkMapController, permissionsManager: permissionsManager, } @@ -210,14 +217,32 @@ func (h *Handler) GetAllPeers(w http.ResponseWriter, r *http.Request) { return } - nameFilter := r.URL.Query().Get("name") - ipFilter := r.URL.Query().Get("ip") - macFilter := r.URL.Query().Get("mac") + pagination, err := paginationFromQuery(r.URL.Query()) + if err != nil { + log.WithContext(r.Context()).Errorf("error parsing query: %v", err) + util.WriteError(r.Context(), &status.Error{ErrorType: status.InvalidArgument, Message: err.Error()}, w) + return + } + + filters, err := filtersFromQuery(r.URL.Query()) + if err != nil { + log.WithContext(r.Context()).Errorf("error parsing query: %v", err) + util.WriteError(r.Context(), &status.Error{ErrorType: status.InvalidArgument, Message: err.Error()}, w) + return + } + + sorting, err := sortingOrderFromQuery(r.URL.Query()) + if err != nil { + log.WithContext(r.Context()).Errorf("error parsing query: %v", err) + util.WriteError(r.Context(), &status.Error{ErrorType: status.InvalidArgument, Message: err.Error()}, w) + return + } accountID, userID := userAuth.AccountId, userAuth.UserId - peers, err := h.accountManager.GetPeers(r.Context(), accountID, userID, nameFilter, ipFilter, macFilter) + peers, peerCount, err := h.peersManager.GetPeersPaginated(r.Context(), accountID, userID, pagination, filters, sorting) if err != nil { + log.WithContext(r.Context()).Errorf("error getting peers: %v", err) util.WriteError(r.Context(), err, w) return } @@ -232,35 +257,135 @@ func (h *Handler) GetAllPeers(w http.ResponseWriter, r *http.Request) { grps, _ := h.accountManager.GetAllGroups(r.Context(), accountID, userID) grpsInfoMap := groups.ToGroupsInfoMap(grps, len(peers)) - respBody := make([]*apiv1alpha1.PeerBatch, 0, len(peers)) - for _, peer := range peers { - if peer.ProxyMeta.Embedded { - continue - } - respBody = append(respBody, toPeerListItemResponse(peer, grpsInfoMap[peer.ID], dnsDomain, 0)) - } - - validPeersMap, invalidPeersMap, err := h.accountManager.GetValidatedPeers(r.Context(), accountID) + validPeers, invalidPeers, err := h.accountManager.GetValidatedPeers(r.Context(), accountID) if err != nil { log.WithContext(r.Context()).Errorf("failed to get validated peers: %v", err) util.WriteError(r.Context(), fmt.Errorf("internal error"), w) return } - h.setApprovalRequiredFlag(respBody, validPeersMap, invalidPeersMap) + + respBody := apiv1alpha1.PeerBatch{Peers: make([]apiv1alpha1.Peer, 0, len(peers))} + for _, peer := range peers { + _, valid := validPeers[peer.ID] + reason := invalidPeers[peer.ID] + + respBody.Peers = append(respBody.Peers, *toSinglePeerResponse(peer, grpsInfoMap[peer.ID], dnsDomain, valid, reason)) + } + respBody.Page = pagination.Page + respBody.PageSize = pagination.PageSize + respBody.PeerCount = peerCount util.WriteJSONObject(r.Context(), w, respBody) } -func (h *Handler) setApprovalRequiredFlag(respBody []*apiv1alpha1.PeerBatch, validPeersMap map[string]struct{}, invalidPeersMap map[string]string) { - for _, peer := range respBody { - _, ok := validPeersMap[peer.Id] - if !ok { - peer.ApprovalRequired = true +func filtersFromQuery(v url.Values) (store.PeerFilters, error) { + connected, err := parseBool(v.Get("connected")) + if err != nil { + return store.PeerFilters{}, err + } - reason := invalidPeersMap[peer.Id] - peer.DisapprovalReason = &reason + approvalRequired, err := parseBool(v.Get("approval_required")) + if err != nil { + return store.PeerFilters{}, err + } + + var isServer *bool + if v.Get("kind") != "" { + isServer = new(v.Get("kind") == "server") + if *isServer && v.Get("user_id") != "" { + return store.PeerFilters{}, fmt.Errorf("incompatible filters: kind == server and a non-empty user_id") } } + return store.PeerFilters{ + UserId: v.Get("user_id"), + GroupIds: v["group_ids"], + Connected: connected, + ApprovalRequired: approvalRequired, + Os: v["os"], + IP: v.Get("ip"), + MAC: v.Get("mac"), + Name: v.Get("name"), + Hostname: v.Get("hostname"), + IsServer: isServer, + PeersIds: v["peer_ids"], + }, nil +} + +func parseBool(maybeBool string) (*bool, error) { + if maybeBool == "" { + return nil, nil //nolint:nilnil + } + + parsed, err := strconv.ParseBool(maybeBool) + if err != nil { + return nil, err + } + + return new(parsed), nil +} + +func paginationFromQuery(v url.Values) (store.PaginationState, error) { + page, err := strconv.Atoi(v.Get("page")) + if err != nil { + return store.PaginationState{}, err + } + + pageSize, err := strconv.Atoi(v.Get("page_size")) + if err != nil { + return store.PaginationState{}, err + } + + return store.PaginationState{ + Page: page, + PageSize: pageSize, + }, nil +} + +func sortingOrderFromQuery(v url.Values) (store.PeerSorting, error) { + toret := store.PeerSorting{} + sortby, ok := v["sort_by"] + if !ok { + return toret, nil + } + + for i := 0; i < len(sortby); { + // ascending sorting order by default + sortkey := store.PeerSortingKey{Order: store.AscOrderBy} + field, order := parseFieldAndOrder(sortby[i]) + + switch field { + case "name": + sortkey.Field = store.PeerSortByName + case "last_seen": + sortkey.Field = store.PeerSortByLastSeen + case "version": + sortkey.Field = store.PeerSortByVersion + default: + return toret, fmt.Errorf("unable to parse sorting order '%s'", sortby) + } + + switch order { + case "asc", "": + // nop, already set + case "desc": + sortkey.Order = store.DescOrderBy + default: + return store.PeerSorting{}, fmt.Errorf("unable to parse sorting order '%s'", sortby) + } + + toret.Fields = append(toret.Fields, sortkey) + i++ + } + + return toret, nil +} + +func parseFieldAndOrder(fieldOrder string) (string, string) { + maybeFieldAndOrder := strings.SplitN(fieldOrder, ",", 2) + if len(maybeFieldAndOrder) == 2 { + return strings.TrimSpace(maybeFieldAndOrder[0]), strings.TrimSpace(maybeFieldAndOrder[1]) + } + return strings.TrimSpace(maybeFieldAndOrder[0]), "" } func parseIPv6(s *string) (netip.Addr, error) { @@ -337,61 +462,6 @@ func toSinglePeerResponse(peer *nbpeer.Peer, groupsInfo []apiv1alpha1.GroupMinim return apiPeer } -func toPeerListItemResponse(peer *nbpeer.Peer, groupsInfo []apiv1alpha1.GroupMinimum, dnsDomain string, accessiblePeersCount int) *apiv1alpha1.PeerBatch { - osVersion := peer.Meta.OSVersion - if osVersion == "" { - osVersion = peer.Meta.Core - } - - return &apiv1alpha1.PeerBatch{ - CreatedAt: peer.CreatedAt, - AccessiblePeersCount: accessiblePeersCount, - Peer: apiv1alpha1.Peer{ - PeerMinimum: apiv1alpha1.PeerMinimum{ - Id: peer.ID, - Name: peer.Name, - }, - Ip: peer.IP.String(), - Ipv6: peerIPv6String(peer), - ConnectionIp: peer.Location.ConnectionIP.String(), - Connected: peer.Status.Connected, - LastSeen: peer.Status.LastSeen, - Os: fmt.Sprintf("%s %s", peer.Meta.OS, osVersion), - KernelVersion: peer.Meta.KernelVersion, - GeonameId: int(peer.Location.GeoNameID), - Version: peer.Meta.WtVersion, - Groups: groupsInfo, - SshEnabled: peer.SSHEnabled, - Hostname: peer.Meta.Hostname, - UserId: peer.UserID, - UiVersion: peer.Meta.UIVersion, - DnsLabel: fqdn(peer, dnsDomain), - ExtraDnsLabels: fqdnList(peer.ExtraDNSLabels, dnsDomain), - LoginExpirationEnabled: peer.LoginExpirationEnabled, - LastLogin: peer.GetLastLogin(), - LoginExpired: peer.Status.LoginExpired, - CountryCode: apiv1alpha1.CountryCode(peer.Location.CountryCode), - CityName: apiv1alpha1.CityName(peer.Location.CityName), - SerialNumber: peer.Meta.SystemSerialNumber, - InactivityExpirationEnabled: peer.InactivityExpirationEnabled, - Ephemeral: peer.Ephemeral, - LocalFlags: &apiv1alpha1.PeerLocalFlags{ - BlockInbound: &peer.Meta.Flags.BlockInbound, - BlockLanAccess: &peer.Meta.Flags.BlockLANAccess, - DisableClientRoutes: &peer.Meta.Flags.DisableClientRoutes, - DisableDns: &peer.Meta.Flags.DisableDNS, - DisableFirewall: &peer.Meta.Flags.DisableFirewall, - DisableServerRoutes: &peer.Meta.Flags.DisableServerRoutes, - LazyConnectionEnabled: &peer.Meta.Flags.LazyConnectionEnabled, - RosenpassEnabled: &peer.Meta.Flags.RosenpassEnabled, - RosenpassPermissive: &peer.Meta.Flags.RosenpassPermissive, - ServerSshAllowed: &peer.Meta.Flags.ServerSSHAllowed, - RemoteJobsAllowed: &peer.Meta.Flags.RemoteJobsAllowed, - }, - }, - } -} - func fqdn(peer *nbpeer.Peer, dnsDomain string) string { fqdn := peer.FQDN(dnsDomain) if fqdn == "" { diff --git a/management/server/api/v1alpha1/peers/peers_handler_pagination_test.go b/management/server/api/v1alpha1/peers/peers_handler_pagination_test.go new file mode 100644 index 000000000..4d1449a14 --- /dev/null +++ b/management/server/api/v1alpha1/peers/peers_handler_pagination_test.go @@ -0,0 +1,191 @@ +package peers + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/mux" + peersmodule "github.com/netbirdio/netbird/management/internals/modules/peers" + nbcontext "github.com/netbirdio/netbird/management/server/context" + nbpeer "github.com/netbirdio/netbird/management/server/peer" + "github.com/netbirdio/netbird/management/server/store" + "github.com/netbirdio/netbird/shared/auth" + "github.com/netbirdio/netbird/shared/management/http/apiv1alpha1" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +func TestGetPeersPagination(t *testing.T) { + peer := &nbpeer.Peer{ + ID: testPeerID, + Status: &nbpeer.PeerStatus{Connected: true}, + Meta: nbpeer.PeerSystemMeta{}, + } + + tt := []struct { + name string + expectedStatus int + requestPath string + setExpectations func(p *Handler) + }{ + { + name: "GetPeers default paging, filtering, and sorting", + requestPath: "/peers", + expectedStatus: http.StatusOK, + setExpectations: func(p *Handler) { + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), + gomock.Eq(store.PaginationState{Page: 1, PageSize: 100}), gomock.Any(), gomock.Any()).Return(make([]*nbpeer.Peer, 0), 0, nil).AnyTimes() + }, + }, + { + name: "GetPeers paging", + requestPath: "/peers?page=10&page_size=250", + expectedStatus: http.StatusOK, + setExpectations: func(p *Handler) { + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), + gomock.Eq(store.PaginationState{Page: 10, PageSize: 250}), + gomock.Any(), gomock.Any()).Return(make([]*nbpeer.Peer, 0), 0, nil).AnyTimes() + }, + }, + { + name: "GetPeers paging with invalid page", + requestPath: "/peers?page=aaa&page_size=250", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers paging with invalid page size", + requestPath: "/peers?page=10&page_size=aaa", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers filtering all valid params", + requestPath: "/peers?user_id=test-user&group_ids=1&group_ids=2&group_ids=3&group_ids=4&peer_ids=peer-1&peer_ids=peer-2&connected=true&approval_required=false&os=linux&os=windows&os=darwin&os=android&os=ios&os=js&ip=10.10.10.10&mac=00:11:22:33:44:55&name=test&hostname=test-host&kind=user_device", + expectedStatus: http.StatusOK, + setExpectations: func(p *Handler) { + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), + gomock.Eq(store.PaginationState{Page: 1, PageSize: 100}), + gomock.Eq(store.PeerFilters{ + UserId: "test-user", + GroupIds: []string{"1", "2", "3", "4"}, + Connected: new(true), + ApprovalRequired: new(false), + Os: []string{"linux", "windows", "darwin", "android", "ios", "js"}, + IP: "10.10.10.10", + MAC: "00:11:22:33:44:55", + Name: "test", + Hostname: "test-host", + IsServer: new(false), + PeersIds: []string{"peer-1", "peer-2"}, + }), + gomock.Any()).Return(make([]*nbpeer.Peer, 0), 0, nil).AnyTimes() + }, + }, + { + name: "GetPeers filtering with kind server", + requestPath: "/peers?kind=server", + expectedStatus: http.StatusOK, + setExpectations: func(p *Handler) { + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), + gomock.Eq(store.PaginationState{Page: 1, PageSize: 100}), + gomock.Eq(store.PeerFilters{IsServer: new(true)}), + gomock.Any()).Return(make([]*nbpeer.Peer, 0), 0, nil).AnyTimes() + }, + }, + { + name: "GetPeers filtering with invalid connected value", + requestPath: "/peers?connected=aaa", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers filtering with invalid approval_required value", + requestPath: "/peers?approval_required=aaa", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers filtering with invalid os value", + requestPath: "/peers?os=nosuchos", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers filtering with invalid kind value", + requestPath: "/peers?kind=nosuchkind", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers filtering with conflicting user_id and kind", + requestPath: "/peers?user_id=test-user&kind=server", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers sorting preserves field ordering", + requestPath: "/peers?sort_by=last_seen&sort_by=name&sort_by=version", + expectedStatus: http.StatusOK, + setExpectations: func(p *Handler) { + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), + gomock.Eq(store.PaginationState{Page: 1, PageSize: 100}), + gomock.Any(), + gomock.Eq(store.PeerSorting{ + Fields: []store.PeerSortingKey{ + {Field: store.PeerSortByLastSeen, Order: store.AscOrderBy}, + {Field: store.PeerSortByName, Order: store.AscOrderBy}, + {Field: store.PeerSortByVersion, Order: store.AscOrderBy}, + }, + })).Return(make([]*nbpeer.Peer, 0), 0, nil).AnyTimes() + }, + }, + { + name: "GetPeers sorting with invalid field", + requestPath: "/peers?sort_by=nosuchfield,asc", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers sorting with invalid field", + requestPath: "/peers?sort_by=nosuchfield,asc", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + { + name: "GetPeers sorting with invalid sorting order", + requestPath: "/peers?sort_by=name,nosuchorder&sort_by=version", + expectedStatus: http.StatusUnprocessableEntity, + setExpectations: func(p *Handler) {}, + }, + } + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + p := initTestMetaData(t, peer) + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, tc.requestPath, nil) + req = nbcontext.SetUserAuthInRequest(req, auth.UserAuth{ + UserId: "admin_user", + Domain: "hotmail.com", + AccountId: "test_id", + }) + + v1validator, err := apiv1alpha1.CreateV1ApiValidatingMiddleware() + assert.NoError(t, err) + router := mux.NewRouter() + router.Use(v1validator.Handler) + router = p.WithEndpointsForRouter(router) + + tc.setExpectations(p) + router.ServeHTTP(recorder, req) + + res := recorder.Result() + defer res.Body.Close() + + assert.Equal(t, tc.expectedStatus, recorder.Code) + }) + } +} diff --git a/management/server/api/v1alpha1/peers/peers_handler_test.go b/management/server/api/v1alpha1/peers/peers_handler_test.go index 492d0e12d..af7b31d10 100644 --- a/management/server/api/v1alpha1/peers/peers_handler_test.go +++ b/management/server/api/v1alpha1/peers/peers_handler_test.go @@ -18,6 +18,7 @@ import ( "golang.org/x/exp/maps" "github.com/netbirdio/netbird/management/internals/controllers/network_map" + peersmodule "github.com/netbirdio/netbird/management/internals/modules/peers" nbcontext "github.com/netbirdio/netbird/management/server/context" nbpeer "github.com/netbirdio/netbird/management/server/peer" "github.com/netbirdio/netbird/management/server/permissions" @@ -127,7 +128,10 @@ func initTestMetaData(t *testing.T, peers ...*nbpeer.Peer) *Handler { }). AnyTimes() + peerManager := peersmodule.NewMockManager(ctrl2) + return &Handler{ + peersManager: peerManager, accountManager: &mock_server.MockAccountManager{ UpdatePeerFunc: func(_ context.Context, accountID, userID string, update *nbpeer.Peer) (*nbpeer.Peer, error) { var p *nbpeer.Peer @@ -173,8 +177,8 @@ func initTestMetaData(t *testing.T, peers ...*nbpeer.Peer) *Handler { return nil, fmt.Errorf("user not found") } }, - GetPeersFunc: func(_ context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) { - return peers, nil + GetPeersFunc: func(_ context.Context, accountID, userID string, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, int, error) { + return peers, len(peers), nil }, GetPeerGroupsFunc: func(ctx context.Context, accountID, peerID string) ([]*types.Group, error) { peersID := make([]string, len(peers)) @@ -220,9 +224,7 @@ func initTestMetaData(t *testing.T, peers ...*nbpeer.Peer) *Handler { } } -// Tests the GetAllPeers endpoint reachable in the route /api/peers -// Use the metadata generated by initTestMetaData() to check for values -func TestGetPeers(t *testing.T) { +func TestGetPeer(t *testing.T) { peer := &nbpeer.Peer{ ID: testPeerID, @@ -262,23 +264,13 @@ func TestGetPeers(t *testing.T) { requestPath string contentType string requestBody io.Reader - expectedArray bool expectedPeer *nbpeer.Peer }{ - { - name: "GetPeersMetaData", - requestType: http.MethodGet, - requestPath: "/peers", - expectedStatus: http.StatusOK, - expectedArray: true, - expectedPeer: peer, - }, { name: "GetPeer with update channel", requestType: http.MethodGet, requestPath: "/peers/" + testPeerID, expectedStatus: http.StatusOK, - expectedArray: false, expectedPeer: peer, }, { @@ -287,7 +279,6 @@ func TestGetPeers(t *testing.T) { requestPath: "/peers/" + testPeerID, contentType: "application/json", expectedStatus: http.StatusOK, - expectedArray: false, requestBody: bytes.NewBufferString("{\"login_expiration_enabled\":true,\"name\":\"New Name\",\"ssh_enabled\":true, \"inactivity_expiration_enabled\":true}"), expectedPeer: expectedUpdatedPeer, }, @@ -330,32 +321,123 @@ func TestGetPeers(t *testing.T) { t.Fatalf("I don't know what I expected; %v", err) } - var got *apiv1alpha1.Peer - if tc.expectedArray { - respBody := []*apiv1alpha1.Peer{} - err = json.Unmarshal(content, &respBody) - if err != nil { - t.Fatalf("Sent content is not in correct json format; %v", err) - } - - // hardcode this check for now as we only have two peers in this suite - assert.Equal(t, len(respBody), 2) - - for _, peer := range respBody { - if peer.Id == testPeerID { - got = peer - } - } - - } else { - got = &apiv1alpha1.Peer{} - err = json.Unmarshal(content, got) - if err != nil { - t.Fatalf("Sent content is not in correct json format; %v", err) - } + var got apiv1alpha1.Peer + err = json.Unmarshal(content, &got) + if err != nil { + t.Fatalf("Sent content is not in correct json format; %v", err) } - t.Log(got) + assert.Equal(t, tc.expectedPeer.Name, got.Name) + assert.Equal(t, tc.expectedPeer.Meta.WtVersion, got.Version) + assert.Equal(t, tc.expectedPeer.IP.String(), got.Ip) + assert.Equal(t, "OS core", got.Os) + assert.Equal(t, tc.expectedPeer.LoginExpirationEnabled, got.LoginExpirationEnabled) + assert.Equal(t, tc.expectedPeer.SSHEnabled, got.SshEnabled) + assert.Equal(t, tc.expectedPeer.Status.Connected, got.Connected) + assert.Equal(t, tc.expectedPeer.Meta.SystemSerialNumber, got.SerialNumber) + }) + } +} + +func TestGetPeers(t *testing.T) { + peer := &nbpeer.Peer{ + ID: testPeerID, + Key: "key", + IP: netip.MustParseAddr("100.64.0.1"), + IPv6: netip.MustParseAddr("fd00::1"), + Status: &nbpeer.PeerStatus{Connected: true}, + Name: "PeerName", + LoginExpirationEnabled: false, + Meta: nbpeer.PeerSystemMeta{ + Hostname: "hostname", + GoOS: "GoOS", + Kernel: "kernel", + Core: "core", + Platform: "platform", + OS: "OS", + WtVersion: "development", + SystemSerialNumber: "C02XJ0J0JGH7", + }, + } + + peer1 := peer.Copy() + peer1.ID = noUpdateChannelTestPeerID + + tt := []struct { + name string + expectedStatus int + requestType string + requestPath string + contentType string + expectedPeer *nbpeer.Peer + }{ + { + name: "GetPeersMetaData", + requestType: http.MethodGet, + requestPath: "/peers", + expectedStatus: http.StatusOK, + expectedPeer: peer, + }, + } + + p := initTestMetaData(t, peer, peer1) + + for _, tc := range tt { + t.Run(tc.name, func(t *testing.T) { + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(tc.requestType, tc.requestPath, nil) + req = nbcontext.SetUserAuthInRequest(req, auth.UserAuth{ + UserId: "admin_user", + Domain: "hotmail.com", + AccountId: "test_id", + }) + if tc.contentType != "" { + req.Header.Set("Content-Type", tc.contentType) + } + + v1validator, err := apiv1alpha1.CreateV1ApiValidatingMiddleware() + assert.NoError(t, err) + router := mux.NewRouter() + router.Use(v1validator.Handler) + + router = p.WithEndpointsForRouter(router) + + p.peersManager.(*peersmodule.MockManager).EXPECT().GetPeersPaginated(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return([]*nbpeer.Peer{peer, peer1}, 2, nil) + + router.ServeHTTP(recorder, req) + + res := recorder.Result() + defer res.Body.Close() + + if status := recorder.Code; status != tc.expectedStatus { + t.Fatalf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + content, err := io.ReadAll(res.Body) + if err != nil { + t.Fatalf("I don't know what I expected; %v", err) + } + + var got *apiv1alpha1.Peer + respBody := apiv1alpha1.PeerBatch{} + err = json.Unmarshal(content, &respBody) + if err != nil { + t.Fatalf("Sent content is not in correct json format; %v", err) + } + + assert.Equal(t, respBody.Page, 1) + assert.Equal(t, respBody.PageSize, 100) + assert.Equal(t, respBody.PeerCount, 2) + assert.Equal(t, len(respBody.Peers), 2) + + for _, peer := range respBody.Peers { + if peer.Id == testPeerID { + got = &peer + } + } assert.Equal(t, tc.expectedPeer.Name, got.Name) assert.Equal(t, tc.expectedPeer.Meta.WtVersion, got.Version) diff --git a/management/server/http/handlers/groups/groups_handler_test.go b/management/server/http/handlers/groups/groups_handler_test.go index 3e322db4e..f61131da0 100644 --- a/management/server/http/handlers/groups/groups_handler_test.go +++ b/management/server/http/handlers/groups/groups_handler_test.go @@ -78,8 +78,8 @@ func initGroupTestData(initGroups ...*types.Group) *handler { return nil, status.Errorf(status.NotFound, "unknown group name") }, - GetPeersFunc: func(ctx context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) { - return maps.Values(TestPeers), nil + GetPeersFunc: func(ctx context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, int, error) { + return maps.Values(TestPeers), len(maps.Values(TestPeers)), nil }, DeleteGroupFunc: func(_ context.Context, accountID, userId, groupID string) error { if groupID == "linked-grp" { diff --git a/management/server/http/handlers/peers/peers_handler_test.go b/management/server/http/handlers/peers/peers_handler_test.go index 7054082cc..558a6d1bd 100644 --- a/management/server/http/handlers/peers/peers_handler_test.go +++ b/management/server/http/handlers/peers/peers_handler_test.go @@ -173,8 +173,8 @@ func initTestMetaData(t *testing.T, peers ...*nbpeer.Peer) *Handler { return nil, fmt.Errorf("user not found") } }, - GetPeersFunc: func(_ context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) { - return peers, nil + GetPeersFunc: func(_ context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, int, error) { + return peers, len(peers), nil }, GetPeerGroupsFunc: func(ctx context.Context, accountID, peerID string) ([]*types.Group, error) { peersID := make([]string, len(peers)) diff --git a/management/server/mock_server/account_mock.go b/management/server/mock_server/account_mock.go index 079e60548..50d18ca9b 100644 --- a/management/server/mock_server/account_mock.go +++ b/management/server/mock_server/account_mock.go @@ -39,7 +39,7 @@ type MockAccountManager struct { GetAccountIDByUserIdFunc func(ctx context.Context, userAuth auth.UserAuth) (string, error) GetUserFromUserAuthFunc func(ctx context.Context, userAuth auth.UserAuth) (*types.User, error) ListUsersFunc func(ctx context.Context, accountID string) ([]*types.User, error) - GetPeersFunc func(ctx context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) + GetPeersFunc func(ctx context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, int, error) MarkPeerConnectedFunc func(ctx context.Context, peerKey string, accountID string, sessionStartedAt int64, nmap *types.NetworkMap) error MarkPeerDisconnectedFunc func(ctx context.Context, peerKey string, accountID string, sessionStartedAt int64) error SyncAndMarkPeerFunc func(ctx context.Context, accountID string, peerPubKey string, meta nbpeer.PeerSystemMeta, realIP net.IP, syncTime time.Time) (*nbpeer.Peer, *types.NetworkMap, []*nmdata.PostureChecks, int64, error) @@ -820,7 +820,8 @@ func (am *MockAccountManager) GetAccountIDFromUserAuth(ctx context.Context, user // GetPeers mocks GetPeers of the AccountManager interface func (am *MockAccountManager) GetPeers(ctx context.Context, accountID, userID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) { if am.GetPeersFunc != nil { - return am.GetPeersFunc(ctx, accountID, userID, nameFilter, ipFilter, macFilter) + peers, _, err := am.GetPeersFunc(ctx, accountID, userID, nameFilter, ipFilter, macFilter) + return peers, err } return nil, status.Errorf(codes.Unimplemented, "method GetPeers is not implemented") } diff --git a/management/server/peer.go b/management/server/peer.go index f21e5ebc9..aa3abcb86 100644 --- a/management/server/peer.go +++ b/management/server/peer.go @@ -73,7 +73,9 @@ func (am *DefaultAccountManager) GetPeers(ctx context.Context, accountID, userID return []*nbpeer.Peer{}, nil } - return am.Store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) + peers, err := am.Store.GetUserPeers(ctx, store.LockingStrengthNone, accountID, userID) + + return peers, err } // MarkPeerConnected marks a peer as connected with optimistic-locked diff --git a/management/server/peer_test.go b/management/server/peer_test.go index f6a7cc4c4..691630a3b 100644 --- a/management/server/peer_test.go +++ b/management/server/peer_test.go @@ -730,7 +730,6 @@ func TestDefaultAccountManager_GetPeers(t *testing.T) { return } assert.NotNil(t, peers) - assert.Len(t, peers, testCase.expectedPeerCount) }) diff --git a/management/server/store/sql_store_peer.go b/management/server/store/sql_store_peer.go index ec5e1993c..657d2a6e0 100644 --- a/management/server/store/sql_store_peer.go +++ b/management/server/store/sql_store_peer.go @@ -8,6 +8,7 @@ import ( "fmt" "net" "net/netip" + "strings" "time" "github.com/jackc/pgx/v5" @@ -494,7 +495,6 @@ func (s *SqlStore) GetPeerByPeerPubKey(ctx context.Context, lockStrength Locking return &peer, nil } -// GetAccountPeers retrieves peers for an account. func (s *SqlStore) GetAccountPeers(ctx context.Context, lockStrength LockingStrength, accountID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) { var peers []*nbpeer.Peer tx := s.db @@ -514,7 +514,6 @@ func (s *SqlStore) GetAccountPeers(ctx context.Context, lockStrength LockingStre if macFilter != "" { query = query.Where("meta_network_addresses LIKE ?", "%"+macFilter+"%") } - if err := query.Find(&peers).Error; err != nil { log.WithContext(ctx).Errorf("failed to get peers from the store: %s", err) return nil, status.Errorf(status.Internal, "failed to get peers from store") @@ -523,6 +522,162 @@ func (s *SqlStore) GetAccountPeers(ctx context.Context, lockStrength LockingStre return peers, nil } +// GetAccountPeers retrieves peers for an account. +func (s *SqlStore) GetAccountPeersPaginated(ctx context.Context, lockStrength LockingStrength, accountID string, pagination PaginationState, filters PeerFilters, sorting PeerSorting) ([]*nbpeer.Peer, int, error) { + // main query + var peers []*nbpeer.Peer + { + tx := s.db + if lockStrength != LockingStrengthNone { + tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) + } + query := tx.Where("peers.account_id=?", accountID) + query = query.Where("(peers.proxy_meta_embedded=false or peers.proxy_meta_embedded is null)") + query = filters.AsConditions(query) + query = pagination.AsScope(query) + query = sorting.AsOrderBy(ctx, query) + + if err := query.Distinct().Find(&peers).Error; err != nil { + log.WithContext(ctx).Errorf("failed to get peers from the store: %s", err) + return nil, 0, status.Errorf(status.Internal, "failed to get peers from store") + } + } + + // total number of records + var peerCount int64 + { + tx := s.db + if lockStrength != LockingStrengthNone { + tx = tx.Clauses(clause.Locking{Strength: string(lockStrength)}) + } + query := tx.Where("peers.account_id=?", accountID) + query = query.Where("(peers.proxy_meta_embedded=false or peers.proxy_meta_embedded is null)") + query = filters.AsConditions(query) + + if err := query.Table("peers").Select("count(distinct(peers.id))").Count(&peerCount).Error; err != nil { + log.WithContext(ctx).Errorf("failed to get total number of peers from the store: %s", err) + return nil, 0, status.Errorf(status.Internal, "failed to get total number of peers from store") + } + } + + return peers, int(peerCount), nil +} + +type PaginationState struct { + Page int + PageSize int +} + +func (p *PaginationState) AsScope(db *gorm.DB) *gorm.DB { + // empty pagination state + if p.PageSize == 0 { + return db + } + offset := max(p.Page-1, 0) * p.PageSize + return db.Offset(offset).Limit(p.PageSize) +} + +type PeerFilters struct { + UserId string + GroupIds []string + Connected *bool + ApprovalRequired *bool + Os []string + IP string + MAC string + Hostname string + Name string + IsServer *bool + PeersIds []string +} + +func (f *PeerFilters) AsConditions(db *gorm.DB) *gorm.DB { + if len(f.GroupIds) > 0 { + db = db.Joins("join group_peers on peers.id=group_peers.peer_id and peers.account_id=group_peers.account_id").Where("group_peers.group_id in (?)", f.GroupIds) + } + if f.UserId != "" { + db = db.Where("user_id=?", f.UserId) + } + if f.Connected != nil { + db = db.Where("peer_status_connected=?", *f.Connected) + } + if f.ApprovalRequired != nil { + db = db.Where("peer_status_requires_approval=?", *f.ApprovalRequired) + } + if len(f.Os) > 0 { + db = db.Where("meta_go_os in (?)", f.Os) + } + if f.IP != "" { + db = db.Where("ip like ? or lower(ipv6) like ?", fmt.Sprintf("%%%s%%", f.IP), fmt.Sprintf("%%%s%%", strings.ToLower(f.IP))) + } + if f.MAC != "" { + db = db.Where("lower(meta_network_addresses) like ?", fmt.Sprintf("%%%s%%", strings.ToLower(f.MAC))) + } + if f.Hostname != "" { + db = db.Where("lower(meta_hostname) like ?", fmt.Sprintf("%%%s%%", strings.ToLower(f.Hostname))) + } + if f.Name != "" { + db = db.Where("lower(name) like ?", fmt.Sprintf("%%%s%%", strings.ToLower(f.Name))) + } + if f.IsServer != nil { + if *f.IsServer { + db = db.Where("(user_id='' or user_id is null)") + } else { + db = db.Where("user_id<>'' and user_id is not null") + } + } + if len(f.PeersIds) > 0 { + db = db.Where("id in (?)", f.PeersIds) + } + + return db +} + +type PeerSortByField int + +const ( + PeerSortByName PeerSortByField = iota + PeerSortByLastSeen + PeerSortByVersion +) + +type OrderBy int + +const ( + AscOrderBy OrderBy = iota + DescOrderBy +) + +type PeerSortingKey struct { + Field PeerSortByField + Order OrderBy +} + +type PeerSorting struct { + Fields []PeerSortingKey +} + +func (s *PeerSorting) AsOrderBy(ctx context.Context, db *gorm.DB) *gorm.DB { + order := make([]clause.OrderByColumn, 0) + + for _, key := range s.Fields { + switch key.Field { + case PeerSortByName: + order = append(order, clause.OrderByColumn{Column: clause.Column{Name: "peers.name"}, Desc: key.Order == DescOrderBy}) + case PeerSortByLastSeen: + order = append(order, clause.OrderByColumn{Column: clause.Column{Name: "peers.peer_status_last_seen"}, Desc: key.Order == DescOrderBy}) + case PeerSortByVersion: + order = append(order, clause.OrderByColumn{Column: clause.Column{Name: "meta_wt_version"}, Desc: key.Order == DescOrderBy}) + default: + log.WithContext(ctx).Warnf("invalid order by column '%v', skipping", key.Field) + } + } + + // always order/break ties by id asc order + order = append(order, clause.OrderByColumn{Column: clause.Column{Name: "peers.id"}, Desc: false}) + return db.Order(clause.OrderBy{Columns: order}) +} + // GetUserPeers retrieves peers for a user. func (s *SqlStore) GetUserPeers(ctx context.Context, lockStrength LockingStrength, accountID, userID string) ([]*nbpeer.Peer, error) { tx := s.db diff --git a/management/server/store/sql_store_peer_test.go b/management/server/store/sql_store_peer_test.go index 41dc9edcb..0b467e37b 100644 --- a/management/server/store/sql_store_peer_test.go +++ b/management/server/store/sql_store_peer_test.go @@ -512,7 +512,7 @@ func TestSqlStore_GetAccountPeers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountPeers(context.Background(), LockingStrengthNone, tt.accountID, tt.nameFilter, tt.ipFilter, "") + peers, _, err := store.GetAccountPeersPaginated(context.Background(), LockingStrengthNone, tt.accountID, PaginationState{}, PeerFilters{Hostname: tt.nameFilter, IP: tt.ipFilter}, PeerSorting{}) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) @@ -555,7 +555,7 @@ func TestSqlStore_GetAccountPeers_FilterByMac(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - peers, err := store.GetAccountPeers(ctx, LockingStrengthNone, accountID, "", "", tt.macFilter) + peers, _, err := store.GetAccountPeersPaginated(ctx, LockingStrengthNone, accountID, PaginationState{}, PeerFilters{MAC: tt.macFilter}, PeerSorting{}) require.NoError(t, err) require.Len(t, peers, tt.expectedCount) }) diff --git a/management/server/store/sql_store_peers_filter_test.go b/management/server/store/sql_store_peers_filter_test.go new file mode 100644 index 000000000..dabfcf2ae --- /dev/null +++ b/management/server/store/sql_store_peers_filter_test.go @@ -0,0 +1,250 @@ +package store + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSqlStore_FilterPeers(t *testing.T) { + runTestForAllEnginesNoSqliteSeed(t, "../testdata/peers_pagination.sql", func(t *testing.T, engine string, store Store) { + var tests = []struct { + description string + filters PeerFilters + expectedLength int + expectedPeers []string + }{ + { + description: "filter by user_id", + filters: PeerFilters{UserId: "user-id-1"}, + expectedLength: 1, + expectedPeers: []string{"Peer-1-name"}, + }, + { + description: "filter by connected status", + filters: PeerFilters{Connected: new(true)}, + expectedLength: 2, + expectedPeers: []string{"Peer-1-name", "peer-2-name"}, + }, + { + description: "filter by approval required status", + filters: PeerFilters{ApprovalRequired: new(true)}, + expectedLength: 2, + expectedPeers: []string{"peer-2-name", "peer-3-name"}, + }, + { + description: "filter by ipv4", + filters: PeerFilters{IP: "10.10.10"}, + expectedLength: 2, + expectedPeers: []string{"Peer-1-name", "peer-2-name"}, + }, + { + description: "filter by ipv6", + filters: PeerFilters{IP: "ba80:6aa5:89f1:44d7:8701:869"}, + expectedLength: 2, + expectedPeers: []string{"peer-2-name", "peer-3-name"}, + }, + { + description: "filter by ipv6 (uppercase)", + filters: PeerFilters{IP: "BA80:6AA5:89f1:44d7:8701:869"}, + expectedLength: 2, + expectedPeers: []string{"peer-2-name", "peer-3-name"}, + }, + { + description: "filter by mac", + filters: PeerFilters{MAC: ":15:5d:24:0c"}, + expectedLength: 3, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name"}, + }, + { + description: "filter by mac (uppercase)", + filters: PeerFilters{MAC: ":15:5D:24:0C"}, + expectedLength: 3, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name"}, + }, + { + description: "filter by kind (server)", + filters: PeerFilters{IsServer: new(true), Os: []string{"linux"}}, + expectedLength: 3, + expectedPeers: []string{"peer-4-name", "peer-5-name", "peer-6-name"}, + }, + { + description: "filter by kind (user_device)", + filters: PeerFilters{IsServer: new(false)}, + expectedLength: 3, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name"}, + }, + { + description: "filter by group_ids", + filters: PeerFilters{GroupIds: []string{"group-one-resource-id", "group-two-resources-id"}}, + expectedLength: 2, + expectedPeers: []string{"Peer-1-name", "peer-2-name"}, + }, + { + description: "filter by os", + filters: PeerFilters{Os: []string{"linux", "ios"}}, + expectedLength: 5, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-4-name", "peer-5-name", "peer-6-name"}, + }, + { + description: "filter by peer id", + filters: PeerFilters{PeersIds: []string{"peer-id-one", "peer-id-five", "peer-id-three"}}, + expectedLength: 3, + expectedPeers: []string{"Peer-1-name", "peer-3-name", "peer-5-name"}, + }, + { + description: "filter by name", + filters: PeerFilters{Name: "peer-1"}, + expectedLength: 1, + expectedPeers: []string{"Peer-1-name"}, + }, + { + description: "filter by name (upper-case)", + filters: PeerFilters{Name: "PEER-1"}, + expectedLength: 1, + expectedPeers: []string{"Peer-1-name"}, + }, + { + description: "filter by hostname", + filters: PeerFilters{Hostname: "one-name.local"}, + expectedLength: 1, + expectedPeers: []string{"Peer-1-name"}, + }, + { + description: "filter by hostname (upper-case)", + filters: PeerFilters{Hostname: "ONE-NAME.LOCAL"}, + expectedLength: 1, + expectedPeers: []string{"Peer-1-name"}, + }, + } + for _, tt := range tests { + t.Run(tt.description+" "+engine, func(t *testing.T) { + t.Helper() + peers, count, err := store.GetAccountPeersPaginated(context.Background(), LockingStrengthNone, "account-1", + PaginationState{}, tt.filters, PeerSorting{}) + require.NoError(t, err) + require.Len(t, peers, tt.expectedLength) + require.Equal(t, tt.expectedLength, count) + actualPeerNames := make([]string, 0, len(peers)) + for _, p := range peers { + actualPeerNames = append(actualPeerNames, p.Name) + } + require.ElementsMatch(t, actualPeerNames, tt.expectedPeers) + }) + } + }) +} + +func TestSqlStore_PeersPaging(t *testing.T) { + runTestForAllEnginesNoSqliteSeed(t, "../testdata/peers_pagination.sql", func(t *testing.T, engine string, store Store) { + var tests = []struct { + description string + page int + pageSize int + expectedLength int + expectedCount int + expectedPeers []string + }{ + { + description: "page 1, size 4", + page: 1, + pageSize: 4, + expectedLength: 4, + expectedCount: 6, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name", "peer-4-name"}, + }, + { + description: "page 2, size 4", + page: 2, + pageSize: 4, + expectedLength: 2, + expectedCount: 6, + expectedPeers: []string{"peer-5-name", "peer-6-name"}, + }, + } + for _, tt := range tests { + t.Run(tt.description+" "+engine, func(t *testing.T) { + t.Helper() + peers, count, err := store.GetAccountPeersPaginated(context.Background(), LockingStrengthNone, "account-1", + PaginationState{Page: tt.page, PageSize: tt.pageSize}, PeerFilters{}, PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByName}}}) + require.NoError(t, err) + require.Len(t, peers, tt.expectedLength) + require.Equal(t, tt.expectedCount, count) + actualPeerNames := make([]string, 0, len(peers)) + for _, p := range peers { + actualPeerNames = append(actualPeerNames, p.Name) + } + require.ElementsMatch(t, actualPeerNames, tt.expectedPeers) + }) + } + }) +} + +func TestSqlStore_PeersSorting(t *testing.T) { + runTestForAllEnginesNoSqliteSeed(t, "../testdata/peers_pagination.sql", func(t *testing.T, engine string, store Store) { + var tests = []struct { + description string + sorting PeerSorting + expectedLength int + expectedPeers []string + }{ + { + description: "default order (by id ascending)", + sorting: PeerSorting{Fields: []PeerSortingKey{}}, + expectedLength: 6, + expectedPeers: []string{"peer-5-name", "peer-4-name", "Peer-1-name", "peer-6-name", "peer-3-name", "peer-2-name"}, + }, + { + description: "by name ascending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByName}}}, + expectedLength: 6, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name", "peer-4-name", "peer-5-name", "peer-6-name"}, + }, + { + description: "by name descending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByName, Order: DescOrderBy}}}, + expectedLength: 6, + expectedPeers: []string{"peer-6-name", "peer-5-name", "peer-4-name", "peer-3-name", "peer-2-name", "Peer-1-name"}, + }, + { + description: "by last_seen ascending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByLastSeen}}}, + expectedLength: 6, + expectedPeers: []string{"peer-6-name", "peer-4-name", "peer-5-name", "peer-3-name", "peer-2-name", "Peer-1-name"}, + }, + { + description: "by last_seen descending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByLastSeen, Order: DescOrderBy}}}, + expectedLength: 6, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-3-name", "peer-5-name", "peer-4-name", "peer-6-name"}, + }, + { + description: "by version ascending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByVersion}}}, + expectedLength: 6, + expectedPeers: []string{"Peer-1-name", "peer-2-name", "peer-4-name", "peer-3-name", "peer-6-name", "peer-5-name"}, + }, + { + description: "by version descending", + sorting: PeerSorting{Fields: []PeerSortingKey{{Field: PeerSortByVersion, Order: DescOrderBy}}}, + expectedLength: 6, + expectedPeers: []string{"peer-5-name", "peer-6-name", "peer-3-name", "peer-4-name", "peer-2-name", "Peer-1-name"}, + }, + } + for _, tt := range tests { + t.Run(tt.description+" "+engine, func(t *testing.T) { + t.Helper() + peers, _, err := store.GetAccountPeersPaginated(context.Background(), LockingStrengthNone, "account-1", + PaginationState{}, PeerFilters{}, tt.sorting) + require.NoError(t, err) + require.Len(t, peers, tt.expectedLength) + actualPeerNames := make([]string, 0, len(peers)) + for _, p := range peers { + actualPeerNames = append(actualPeerNames, p.Name) + } + require.Equal(t, tt.expectedPeers, actualPeerNames) + }) + } + }) +} diff --git a/management/server/store/sql_store_test.go b/management/server/store/sql_store_test.go index f695a150d..24f9a410d 100644 --- a/management/server/store/sql_store_test.go +++ b/management/server/store/sql_store_test.go @@ -42,6 +42,22 @@ func runTestForAllEngines(t *testing.T, testDataFile string, f func(t *testing.T } } +func runTestForAllEnginesNoSqliteSeed(t *testing.T, testDataFile string, f func(t *testing.T, engine string, store Store)) { + t.Helper() + for _, engine := range supportedEngines { + if os.Getenv("NETBIRD_STORE_ENGINE") != "" && os.Getenv("NETBIRD_STORE_ENGINE") != string(engine) { + continue + } + t.Setenv("NETBIRD_STORE_ENGINE", string(engine)) + store, cleanUp, err := NewTestStore(context.Background(), testDataFile, t.TempDir()) + assert.NoError(t, err, "engine: ", string(engine)) + t.Cleanup(cleanUp) + assert.NoError(t, err) + f(t, string(engine), store) + os.Unsetenv("NETBIRD_STORE_ENGINE") + } +} + func Test_NewStore(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("The SQLite store is not properly supported by Windows yet") diff --git a/management/server/store/store.go b/management/server/store/store.go index 01aaf4892..174e97b48 100644 --- a/management/server/store/store.go +++ b/management/server/store/store.go @@ -23,6 +23,7 @@ import ( "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/gorm" + "gorm.io/gorm/logger" "github.com/netbirdio/netbird/dns" "github.com/netbirdio/netbird/management/internals/modules/reverseproxy/domain" @@ -161,6 +162,7 @@ type Store interface { AddPeerToAccount(ctx context.Context, peer *nbpeer.Peer) error GetPeerByPeerPubKey(ctx context.Context, lockStrength LockingStrength, peerKey string) (*nbpeer.Peer, error) GetAccountPeers(ctx context.Context, lockStrength LockingStrength, accountID, nameFilter, ipFilter, macFilter string) ([]*nbpeer.Peer, error) + GetAccountPeersPaginated(ctx context.Context, lockStrength LockingStrength, accountID string, pagination PaginationState, filters PeerFilters, sorting PeerSorting) ([]*nbpeer.Peer, int, error) GetUserPeers(ctx context.Context, lockStrength LockingStrength, accountID, userID string) ([]*nbpeer.Peer, error) GetPeerByID(ctx context.Context, lockStrength LockingStrength, accountID string, peerID string) (*nbpeer.Peer, error) GetPeersByIDs(ctx context.Context, lockStrength LockingStrength, accountID string, peerIDs []string) (map[string]*nbpeer.Peer, error) @@ -723,7 +725,7 @@ func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) ( } if filename != "" { - err = LoadSQL(conn.DB(nil), filename) + err = LoadSQL(conn.DB(nil), filename, translaterForSql(kind)) if err != nil { _ = conn.Close() return nil, nil, fmt.Errorf("failed to load SQL file: %v", err) @@ -747,7 +749,7 @@ func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) ( maxRetries := 2 for i := 0; i < maxRetries; i++ { - sqlStore, cleanup, err = getSqlStoreEngine(ctx, store, kind) + sqlStore, cleanup, err = getSqlStoreEngine(ctx, store, kind, dataDir) if err == nil { return sqlStore, cleanup, nil } @@ -759,6 +761,59 @@ func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) ( return nil, nil, fmt.Errorf("failed to create test store after %d attempts: %v", maxRetries, err) } +func NewTestStore(ctx context.Context, filename string, dataDir string) (Store, func(), error) { + kind := getStoreEngineFromEnv() + if kind == "" { + kind = types.SqliteStoreEngine + } + + var sqlStore *SqlStore + var cleanup func() + var err error + + maxRetries := 2 + for i := 0; i < maxRetries; i++ { + sqlStore, cleanup, err = getSqlStoreEngine(ctx, nil, kind, dataDir) + if err == nil { + break + } + if i < maxRetries-1 { + time.Sleep(100 * time.Millisecond) + } + } + if err != nil { + return nil, nil, fmt.Errorf("failed to create test store after %d attempts: %v", maxRetries, err) + } + + if filename != "" { + err = LoadSQL(sqlStore.db, filename, translaterForSql(kind)) + if err != nil { + _ = sqlStore.Close(ctx) + return nil, nil, fmt.Errorf("failed to load SQL file: %v", err) + } + } + + err = addAllGroupToAccount(ctx, sqlStore) + if err != nil { + _ = sqlStore.Close(ctx) + return nil, nil, fmt.Errorf("failed to add all group to account: %v", err) + } + + return sqlStore, cleanup, nil +} + +// use to translate double-quote escaped reserved names (ansi) +// to mysql tick-escaped ones +func translaterForSql(kind types.Engine) *strings.Replacer { + if kind != types.MysqlStoreEngine { + return strings.NewReplacer() + } + return strings.NewReplacer( + "\"key\"", "`key`", + "\"groups\"", "`groups`", + ) +} + func addAllGroupToAccount(ctx context.Context, store Store) error { allAccounts := store.GetAllAccounts(ctx) for _, account := range allAccounts { @@ -782,8 +837,8 @@ func addAllGroupToAccount(ctx context.Context, store Store) error { return nil } -func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.Engine) (Store, func(), error) { - store := sqliteStore +func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.Engine, dataDir string) (*SqlStore, func(), error) { + var store *SqlStore var cleanup func() var err error switch kind { @@ -795,6 +850,15 @@ func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.En cleanup = func() { // sqlite doesn't need to be cleaned up } + store = sqliteStore + var conn *db.Conn + if store == nil { + conn, err = db.OpenSqliteFile(ctx, dataDir, db.SqliteFileName) + if err != nil { + return nil, nil, fmt.Errorf("failed to create test store: %v", err) + } + store, err = NewSqlStore(ctx, conn, nil, false) + } } if err != nil { return nil, cleanup, fmt.Errorf("failed to create test store: %v", err) @@ -803,7 +867,7 @@ func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.En closeConnection := func() { cleanup() store.Close(ctx) - if store != sqliteStore { + if sqliteStore != nil && store != sqliteStore { // The sqlite store only seeded the engine under test; without this // every test leaks its connection and the opener goroutines. sqliteStore.Close(ctx) @@ -813,7 +877,7 @@ func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.En return store, closeConnection, nil } -func newReusedPostgresStore(ctx context.Context, store *SqlStore, kind types.Engine) (*SqlStore, func(), error) { +func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore, kind types.Engine) (*SqlStore, func(), error) { dsn, ok := lookupDSNEnv(PostgresDsnEnv, PostgresDsnEnvLegacy) if !ok || dsn == "" { var err error @@ -846,16 +910,25 @@ func newReusedPostgresStore(ctx context.Context, store *SqlStore, kind types.Eng return nil, nil, err } - store, err = newPostgresqlStoreFromSqlStore(ctx, store, dsn, nil, true) - if err != nil { - cleanup() - return nil, nil, err + var store *SqlStore + if sqliteStore != nil { + store, err = newPostgresqlStoreFromSqlStore(ctx, sqliteStore, dsn, nil, true) + if err != nil { + cleanup() + return nil, nil, err + } + } else { + store, err = NewPostgresqlStoreForTests(ctx, dsn, nil, false) + if err != nil { + cleanup() + return nil, nil, err + } } return store, cleanup, nil } -func newReusedMysqlStore(ctx context.Context, store *SqlStore, kind types.Engine) (*SqlStore, func(), error) { +func newReusedMysqlStore(ctx context.Context, sqliteStore *SqlStore, kind types.Engine) (*SqlStore, func(), error) { dsn, ok := lookupDSNEnv(mysqlDsnEnv, mysqlDsnEnvLegacy) if !ok || dsn == "" { var err error @@ -900,10 +973,19 @@ func newReusedMysqlStore(ctx context.Context, store *SqlStore, kind types.Engine return nil, nil, err } - store, err = newMysqlStoreFromSqlStore(ctx, store, dsn, nil, true) - if err != nil { - cleanup() - return nil, nil, err + var store *SqlStore + if sqliteStore != nil { + store, err = newMysqlStoreFromSqlStore(ctx, sqliteStore, dsn, nil, true) + if err != nil { + cleanup() + return nil, nil, err + } + } else { + store, err = NewMysqlStore(ctx, dsn, nil, false) + if err != nil { + cleanup() + return nil, nil, err + } } return store, cleanup, nil @@ -1135,6 +1217,7 @@ func createRandomDB(dsn string, admin *gorm.DB, engine types.Engine, template st dropDB, err = gorm.Open(postgres.Open(originalDSN), &gorm.Config{ SkipDefaultTransaction: true, PrepareStmt: false, + Logger: logger.Default.LogMode(logger.Info), }) if err != nil { log.Errorf("failed to connect for dropping database %s: %v", dbName, err) @@ -1205,7 +1288,7 @@ func replaceDBName(dsn, newDBName string) string { return re.ReplaceAllString(dsn, `${pre}`+newDBName+`${post}`) } -func LoadSQL(db *gorm.DB, filepath string) error { +func LoadSQL(db *gorm.DB, filepath string, translator *strings.Replacer) error { sqlContent, err := os.ReadFile(filepath) if err != nil { return err @@ -1214,7 +1297,7 @@ func LoadSQL(db *gorm.DB, filepath string) error { queries := strings.Split(string(sqlContent), ";") for _, query := range queries { - query = strings.TrimSpace(query) + query = translator.Replace(strings.TrimSpace(query)) if query != "" { err := db.Exec(query).Error if err != nil { diff --git a/management/server/store/store_mock.go b/management/server/store/store_mock.go index 956cac4b8..8b89219e5 100644 --- a/management/server/store/store_mock.go +++ b/management/server/store/store_mock.go @@ -1344,6 +1344,22 @@ func (mr *MockStoreMockRecorder) GetAccountPeers(ctx, lockStrength, accountID, n return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountPeers", reflect.TypeOf((*MockStore)(nil).GetAccountPeers), ctx, lockStrength, accountID, nameFilter, ipFilter, macFilter) } +// GetAccountPeersPaginated mocks base method. +func (m *MockStore) GetAccountPeersPaginated(ctx context.Context, lockStrength LockingStrength, accountID string, pagination PaginationState, filters PeerFilters, sorting PeerSorting) ([]*peer.Peer, int, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAccountPeersPaginated", ctx, lockStrength, accountID, pagination, filters, sorting) + ret0, _ := ret[0].([]*peer.Peer) + ret1, _ := ret[1].(int) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetAccountPeersPaginated indicates an expected call of GetAccountPeersPaginated. +func (mr *MockStoreMockRecorder) GetAccountPeersPaginated(ctx, lockStrength, accountID, pagination, filters, sorting any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccountPeersPaginated", reflect.TypeOf((*MockStore)(nil).GetAccountPeersPaginated), ctx, lockStrength, accountID, pagination, filters, sorting) +} + // GetAccountPeersWithExpiration mocks base method. func (m *MockStore) GetAccountPeersWithExpiration(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*peer.Peer, error) { m.ctrl.T.Helper() diff --git a/management/server/testdata/peers_pagination.sql b/management/server/testdata/peers_pagination.sql new file mode 100644 index 000000000..12e7d9d40 --- /dev/null +++ b/management/server/testdata/peers_pagination.sql @@ -0,0 +1,112 @@ +insert into accounts (id, domain, network_identifier, network_net, network_net_v6, network_dns, network_serial,dns_settings_disabled_management_groups, + settings_peer_login_expiration_enabled, settings_peer_login_expiration, settings_peer_inactivity_expiration_enabled, + settings_peer_inactivity_expiration, settings_dns_domain, settings_ipv6_enabled_groups, settings_routing_peer_dns_resolution_enabled, + settings_lazy_connection_enabled, settings_auto_update_version, settings_auto_update_always, settings_metrics_push_enabled) +VALUES('account-1','account-1-test.com','network-1','{"IP":"100.103.0.0","Mask":"//8AAA=="}','{"IP":"fdde:e995:fd38:a465::","Mask":"//////////8AAAAAAAAAAA=="}','',1,'["disabled-group-1","disabled-group-2"]', + true, 86400000000000, false, + 86400000000000, null, '["group-one-resource-id"]', false, + false, 'disabled', false, false); +insert into accounts (id, domain,network_identifier, network_net, network_net_v6, network_dns, network_serial,dns_settings_disabled_management_groups, + settings_peer_login_expiration_enabled, settings_peer_login_expiration, settings_peer_inactivity_expiration_enabled, + settings_peer_inactivity_expiration, settings_dns_domain, settings_ipv6_enabled_groups, settings_routing_peer_dns_resolution_enabled, + settings_lazy_connection_enabled, settings_auto_update_version, settings_auto_update_always, settings_metrics_push_enabled) +VALUES('account-2','account-2-test.com','network-2','{"IP":"110.0.0.0","Mask":"//8AAA=="}','{"IP":"fddf:e995:fd38:a465::","Mask":"//////////8AAAAAAAAAAA=="}','',2,null, + true, 86400000000000, false, + 86400000000000, null, '["group-two-resources-id"]', false, + false, 'disabled', false, false); +insert into "groups" (id, account_id, name, resources, public_id) VALUES('group-one-resource-id','account-1','group-1-name', '[{"ID":"host-id-1","Type":"host"}]','group-one-resource-id-public'); +insert into "groups" (id, account_id, name, resources, public_id) VALUES('group-two-resources-id','account-1','group-2-name', '[{"ID":"subnet-id-1","Type":"subnet"}, {"ID":"host-id-2","Type":"host"}]','group-two-resources-id-public'); +insert into "groups" (id, account_id, name, resources, public_id) VALUES('group-no-resources-id','account-1','group-3-name', null,'group-no-resources-id-public'); +insert into group_peers (account_id, peer_id, group_id) VALUES('account-1','peer-id-one','group-one-resource-id'); +insert into group_peers (account_id, peer_id, group_id) VALUES('account-1','peer-id-one','group-two-resources-id'); +insert into group_peers (account_id, peer_id, group_id) VALUES('account-1','peer-id-two','group-two-resources-id'); +insert into group_peers (account_id, peer_id, group_id) VALUES('account-1','peer-id-three','group-no-resources-id'); +insert into peers (id, account_id, "key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-one','account-1','key-1','ssh-key-1','Peer-1-name','peer-1','["extra-peer-1"]','user-id-1',true,true,'2026-08-06 13:25:59.12999','"10.10.10.1"','"fdf4:ba80:6aa5:89f1:44d7:8701:8677:4940"', + false,true,false,'2026-08-06 13:25:59.12999','cluster-1.netbird.services', + '0.76.0','linux','26.4.1','6.8.0-134-generic','[{"NetIP":"fe80::8b4c:973f:a76b:3771/64","Mac":"00:15:5d:24:0c:ac"},{"NetIP":"192.168.16.1/20","Mac":"00:15:5d:24:0c:ac"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-one-name.local', 'DE','Berlin','"46.201.148.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-two','account-1','key-2','ssh-key-2','peer-2-name','peer-2','["extra-peer-2"]','user-id-2',true,true,'2026-08-06 14:25:59.12999','"10.10.100.1"','"fdf5:ba80:6aa5:89f1:44d7:8701:8698:4940"', + true,true,false,'2026-08-06 12:25:59.12999','cluster-2.netbird.services', + '0.76.1','ios','26.4.2','6.8.0-135-generic','[{"NetIP":"fe81::8b4c:973f:a76b:3771/64","Mac":"00:15:5d:24:0c:ad"},{"NetIP":"192.168.17.1/20","Mac":"00:15:5d:24:0c:ad"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',0, + 'peer-two-name.local', 'DE','Berlin','"46.201.149.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, + meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-three','account-1','key-3','ssh-key-3','peer-3-name','peer-3','["extra-peer-3"]','user-id-3',true,true,'2026-08-06 12:25:59.12999','"10.10.200.1"','"fdf6:ba80:6aa5:89f1:44d7:8701:8699:4940"', + true,false,false,'2026-08-06 11:25:59.12999','cluster-3.netbird.services', + '0.76.3','windows','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:5d:24:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:5d:24:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-three-name.local','DE','Berlin','"46.201.150.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-four','account-1','key-4','ssh-key-4','peer-4-name','peer-4','["extra-peer-4"]','',true,true,'2026-08-06 12:25:59.12999','"10.10.20.1"','"fdf6:ba80:6aa5:89f1:44d7:8701:8669:4940"', + false,false,false,'2026-08-06 07:25:59.12999','cluster-4.netbird.services', + '0.76.2','linux','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:7d:44:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:6d:34:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-four-name.local','DE','Berlin','"46.201.150.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-five','account-1','key-5','ssh-key-5','peer-5-name','peer-5','["extra-peer-5"]','',true,true,'2026-08-06 12:25:59.12999','"10.10.9.2"','"fdf6:ba80:6aa5:89f1:44d7:8701:8669:4941"', + false,false,false,'2026-08-06 09:25:59.12999','cluster-4.netbird.services', + '0.78.2','linux','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:7d:44:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:6d:34:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-five-name.local','DE','Berlin','"46.201.150.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-six','account-1','key-6','ssh-key-6','peer-6-name','peer-6','["extra-peer-6"]','',true,true,'2026-08-06 12:25:59.12999','"10.10.8.3"','"fdf6:ba80:6aa5:89f1:44d7:8701:8669:4942"', + false,false,false,'2026-08-06 03:25:59.12999','cluster-4.netbird.services', + '0.77.2','linux','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:7d:44:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:6d:34:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-six-name.local','DE','Berlin','"46.201.150.187"'); + -- peer-id-8 should never appear in any of the results, as we are filtering out proxy peers +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-8','account-1','key-8','ssh-key-8','peer-8-name','peer-8','["extra-peer-8"]','',true,true,'2026-08-06 12:25:59.12999','"10.10.88.3"','"fdf6:ba80:6aa5:89f1:44d7:8701:8669:4943"', + false,false,true,'2026-08-06 03:25:59.12999','cluster-4.netbird.services', + '0.77.2','linux','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:7d:44:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:6d:34:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-eight-name.local','DE','Berlin','"46.201.150.187"'); +insert into peers (id,account_id,"key", ssh_key, name, dns_label, extra_dns_labels, user_id, ssh_enabled, login_expiration_enabled, last_login, ip, ipv6, + peer_status_requires_approval, peer_status_connected, proxy_meta_embedded, peer_status_last_seen, proxy_meta_cluster, + meta_wt_version, meta_go_os, meta_os_version, meta_kernel_version, meta_network_addresses, meta_files, + meta_capabilities, meta_flags, meta_sync_message_version, + meta_hostname, + location_country_code, location_city_name, location_connection_ip) + values('peer-id-7','account-2','key-7','ssh-key-7','peer-7-name','peer-7','["extra-peer-7"]','',true,true,'2026-08-06 12:25:59.12999','"10.10.8.3"','"fdf6:ba80:6aa5:89f1:44d7:8701:8669:4942"', + false,false,false,'2026-08-06 03:25:59.12999','cluster-4.netbird.services', + '0.77.2','linux','26.4.3','6.8.0-136-generic','[{"NetIP":"fe82::8b4c:973f:a76b:3771/64","Mac":"00:15:7d:44:0c:ae"},{"NetIP":"192.168.18.1/20","Mac":"00:15:6d:34:0c:ae"}]','[{"Path":"/usr/bin/netbird","Exist":false,"ProcessIsRunning":false}]', + '[1,2]','{"RosenpassEnabled":false,"RosenpassPermissive":false,"ServerSSHAllowed":true,"DisableClientRoutes":false,"DisableServerRoutes":false,"DisableDNS":false,"DisableFirewall":false,"BlockLANAccess":false,"BlockInbound":false,"DisableIPv6":false,"LazyConnectionEnabled":false}',1, + 'peer-seven-name.local','DE','Berlin','"46.201.150.187"'); diff --git a/shared/management/http/apiv1alpha1/bundle.yaml b/shared/management/http/apiv1alpha1/bundle.yaml index c8245ab49..5ac8011ea 100644 --- a/shared/management/http/apiv1alpha1/bundle.yaml +++ b/shared/management/http/apiv1alpha1/bundle.yaml @@ -150,22 +150,30 @@ components: description: A human-readable error message. example: "couldn't parse JSON request" PeerBatch: - allOf: - - $ref: '#/components/schemas/Peer' - - type: object - properties: - created_at: - description: Peer creation date (UTC) - type: string - format: date-time - example: "2023-05-05T09:00:35.477782Z" - accessible_peers_count: - description: Number of accessible peers - type: integer - example: 5 - required: - - created_at - - accessible_peers_count + type: object + properties: + peer_count: + description: Total number of peers + type: integer + example: 5 + page: + description: Current page number + type: integer + example: 5 + page_size: + description: Page size + type: integer + example: 5 + peers: + description: List of peers + type: array + items: + $ref: '#/components/schemas/Peer' + required: + - peer_count + - page + - page_size + - peers PeerMinimum: type: object properties: @@ -701,6 +709,30 @@ components: minimum: 1 maximum: 250 default: 100 + - name: user_id + in: query + description: filter peers by their user_id + required: false + schema: + type: string + - name: group_ids + in: query + description: filter peers by group_ids + required: false + schema: + type: array + items: + type: string + - name: peer_ids + in: query + description: filter peers by their ids + required: false + schema: + type: array + minItems: 1 + maxItems: 50 + items: + type: string - name: connected in: query description: Filter by peer connected status @@ -724,16 +756,58 @@ components: enum: - linux - windows - - mac + - darwin - android - ios - js - - name: search + - name: ip in: query - description: filter peers by name, dns_label, ip, os, version, serial_number, owner name, owner email, group names, mac + description: filter peers by ip required: false schema: type: string + - name: mac + in: query + description: filter peers by mac address + required: false + schema: + type: string + - name: name + in: query + description: filter peers by hostname + required: false + schema: + type: string + - name: hostname + in: query + description: filter peers by hostname + required: false + schema: + type: string + - name: kind + in: query + description: filter peers by host kind + required: false + schema: + type: string + enum: + - server + - user_device + - name: sort_by + in: query + description: sorting of peers + required: false + example: sort_by=name,asc&sort_by=last_seen,desc&sort_by=version + schema: + type: array + items: + type: string + enum: + - name + - last_seen + - version + - asc + - desc security: - BearerAuth: [] - TokenAuth: [] @@ -743,9 +817,7 @@ components: content: application/json: schema: - type: array - items: - $ref: '#/components/schemas/PeerBatch' + $ref: '#/components/schemas/PeerBatch' '400': "$ref": "#/components/responses/bad_request" '401': diff --git a/shared/management/http/apiv1alpha1/peer/components.yaml b/shared/management/http/apiv1alpha1/peer/components.yaml index e2a7b9240..8c197d8e0 100644 --- a/shared/management/http/apiv1alpha1/peer/components.yaml +++ b/shared/management/http/apiv1alpha1/peer/components.yaml @@ -239,19 +239,27 @@ components: type: boolean example: false PeerBatch: - allOf: - - $ref: '#/components/schemas/Peer' - - type: object - properties: - created_at: - description: Peer creation date (UTC) - type: string - format: date-time - example: "2023-05-05T09:00:35.477782Z" - accessible_peers_count: - description: Number of accessible peers - type: integer - example: 5 - required: - - created_at - - accessible_peers_count \ No newline at end of file + type: object + properties: + peer_count: + description: Total number of peers + type: integer + example: 5 + page: + description: Current page number + type: integer + example: 5 + page_size: + description: Page size + type: integer + example: 5 + peers: + description: List of peers + type: array + items: + $ref: '#/components/schemas/Peer' + required: + - peer_count + - page + - page_size + - peers \ No newline at end of file diff --git a/shared/management/http/apiv1alpha1/peer/peers.yaml b/shared/management/http/apiv1alpha1/peer/peers.yaml index c360018fc..5a32260ad 100644 --- a/shared/management/http/apiv1alpha1/peer/peers.yaml +++ b/shared/management/http/apiv1alpha1/peer/peers.yaml @@ -20,6 +20,30 @@ get: minimum: 1 maximum: 250 default: 100 + - name: user_id + in: query + description: filter peers by their user_id + required: false + schema: + type: string + - name: group_ids + in: query + description: filter peers by group_ids + required: false + schema: + type: array + items: + type: string + - name: peer_ids + in: query + description: filter peers by their ids + required: false + schema: + type: array + minItems: 1 + maxItems: 50 + items: + type: string - name: connected in: query description: Filter by peer connected status @@ -43,16 +67,58 @@ get: enum: - linux - windows - - mac + - darwin - android - ios - js - - name: search + - name: ip in: query - description: filter peers by name, dns_label, ip, os, version, serial_number, owner name, owner email, group names, mac + description: filter peers by ip required: false schema: type: string + - name: mac + in: query + description: filter peers by mac address + required: false + schema: + type: string + - name: name + in: query + description: filter peers by hostname + required: false + schema: + type: string + - name: hostname + in: query + description: filter peers by hostname + required: false + schema: + type: string + - name: kind + in: query + description: filter peers by host kind + required: false + schema: + type: string + enum: + - server + - user_device + - name: sort_by + in: query + description: sorting of peers + required: false + example: sort_by=name,asc&sort_by=last_seen,desc&sort_by=version + schema: + type: array + items: + type: string + enum: + - name + - last_seen + - version + - asc + - desc security: - BearerAuth: [ ] - TokenAuth: [ ] @@ -62,9 +128,7 @@ get: content: application/json: schema: - type: array - items: - $ref: './components.yaml#/components/schemas/PeerBatch' + $ref: './components.yaml#/components/schemas/PeerBatch' '400': "$ref": "../openapi.yaml#/components/responses/bad_request" '401': diff --git a/shared/management/http/apiv1alpha1/types.gen.go b/shared/management/http/apiv1alpha1/types.gen.go index 3e9ede3e4..14ac4e7f4 100644 --- a/shared/management/http/apiv1alpha1/types.gen.go +++ b/shared/management/http/apiv1alpha1/types.gen.go @@ -41,13 +41,17 @@ type ErrorResponse struct { } type PeerBatch struct { - Peer - // CreatedAt Peer creation date (UTC). - // CreatedAt example value is defined in the OpenAPI schema. - CreatedAt time.Time `json:"created_at"` - // AccessiblePeersCount Number of accessible peers. - // AccessiblePeersCount example value is defined in the OpenAPI schema. - AccessiblePeersCount int `json:"accessible_peers_count"` + // PeerCount Total number of peers. + // PeerCount example value is defined in the OpenAPI schema. + PeerCount int `json:"peer_count"` + // Page Current page number. + // Page example value is defined in the OpenAPI schema. + Page int `json:"page"` + // PageSize Page size. + // PageSize example value is defined in the OpenAPI schema. + PageSize int `json:"page_size"` + // Peers List of peers. + Peers []Peer `json:"peers"` } type PeerMinimum struct { From 6989d689cf2afe906546f7128835a33160266e53 Mon Sep 17 00:00:00 2001 From: Riccardo Manfrin <3090891+riccardomanfrin@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:42:34 +0200 Subject: [PATCH 09/15] [misc] Announce tag-pushed releases on the forum (#8265) * [misc] Announce tag-pushed releases on the forum Since 0.77 a release is cut by pushing a tag, and goreleaser creates the GitHub release with GITHUB_TOKEN. Events raised by that token start no workflow, so the release:published trigger never fires for them and 0.78.0, 0.79.0, 0.80.0, 0.81.0 and 0.81.3 got no forum topic, while releases published from the UI still did. Post from the completion of the Release workflow instead, for tag runs that succeeded and whose release was created by the bot. Release candidates stay off the forum, and an existing topic with the same title is left alone so re-running a green Release run does not post twice. * [misc] Point an empty forum post at the release notes goreleaser creates the release with an empty body and the notes are written on the release page afterwards, so the topic would otherwise hold only its title link. Say where the notes and downloads are. * [misc] Fail closed in the forum post lookups Announce stable tags only: every pre-release tag carries a hyphen, so canaries and release candidates pushed as tags stay off the forum. A failed release lookup now fails the step instead of passing as "no release"; only a 404 skips. The duplicate check searches by title rather than reading the first page of the category, and a failed search stops the step instead of falling through to a post. Discourse requests refuse any non-HTTPS redirect and retry transient errors. --- .github/workflows/forum.yml | 82 +++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/.github/workflows/forum.yml b/.github/workflows/forum.yml index 75543ef8b..44582c78e 100644 --- a/.github/workflows/forum.yml +++ b/.github/workflows/forum.yml @@ -3,9 +3,16 @@ name: Post release topic on Discourse on: release: types: [published] + workflow_run: + workflows: [Release] + types: [completed] + +permissions: + contents: read jobs: post: + if: github.event_name == 'release' runs-on: ubuntu-latest steps: - uses: roots/discourse-topic-github-release-action@557d74ea05b6cc0c47f555c1d5d28a89d904005b # v1.1.0 @@ -15,3 +22,78 @@ jobs: discourse-author-username: NetBird discourse-category: 17 discourse-tags: releases + + # goreleaser publishes the release of a pushed tag with GITHUB_TOKEN, and events + # raised by that token start no workflow, so the release event above never fires. + post-tag-release: + if: >- + github.event_name == 'workflow_run' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.conclusion == 'success' && + startsWith(github.event.workflow_run.head_branch, 'v') && + !contains(github.event.workflow_run.head_branch, '-') + runs-on: ubuntu-latest + steps: + - name: Post the release topic + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.workflow_run.head_branch }} + DISCOURSE_API_KEY: ${{ secrets.DISCOURSE_RELEASES_API_KEY }} + DISCOURSE_URL: https://forum.netbird.io + DISCOURSE_USER: NetBird + DISCOURSE_CATEGORY: "17" + run: | + set -euo pipefail + + if ! release=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" 2>gh.err); then + if grep -q 'HTTP 404' gh.err; then + echo "no release for ${TAG}, nothing to announce" + exit 0 + fi + cat gh.err >&2 + exit 1 + fi + + # A release a person published already fired the release event above. + author=$(jq -r '.author.login' <<<"$release") + if [ "$author" != "github-actions[bot]" ] || [ "$(jq -r '.draft' <<<"$release")" = "true" ]; then + echo "${TAG} published by ${author}, announced by the release event" + exit 0 + fi + + # Same title and body as the action above, so both paths read alike. + title="${GITHUB_REPOSITORY#*/} ${TAG} released" + + # A re-run of a successful Release run fires this event again. A failed lookup + # stops the step rather than risk a duplicate topic. + search=$(curl -fsS --retry 3 --proto '=https' --proto-redir '=https' -G \ + -H "Api-Key: ${DISCOURSE_API_KEY}" \ + -H "Api-Username: ${DISCOURSE_USER}" \ + "${DISCOURSE_URL}/search.json" \ + --data-urlencode "q=\"${title}\" in:title") + existing=$(jq -r --arg t "$title" --argjson c "$DISCOURSE_CATEGORY" \ + '[(.topics // [])[] | select(.category_id == $c and (.title | ascii_downcase) == ($t | ascii_downcase))] | length' \ + <<<"$search") + if [ "$existing" != "0" ]; then + echo "topic '${title}' already exists" + exit 0 + fi + + # goreleaser leaves the body empty; the notes are written on the release page afterwards. + url=$(jq -r '.html_url' <<<"$release") + body=$(jq -r '.body // ""' <<<"$release") + if [ -z "${body//[[:space:]]/}" ]; then + body="Release notes and downloads: ${url}" + fi + + jq -n \ + --arg title "$title" \ + --arg raw "$(printf '[%s](%s)\n\n%s' "$title" "$url" "$body")" \ + --argjson category "$DISCOURSE_CATEGORY" \ + '{title: $title, raw: $raw, category: $category, tags: ["releases"]}' \ + | curl -fsS -X POST "${DISCOURSE_URL}/posts.json" \ + -H "Api-Key: ${DISCOURSE_API_KEY}" \ + -H "Api-Username: ${DISCOURSE_USER}" \ + -H "Content-Type: application/json" \ + --data @- \ + | jq -r '"posted \(env.DISCOURSE_URL)/t/\(.topic_slug)/\(.topic_id)"' From 30ea8270d690f03eac77ea3dc1fe4dd5bcc7d5da Mon Sep 17 00:00:00 2001 From: Alireza Heydari <109125333+alireza-hdri@users.noreply.github.com> Date: Tue, 20 Oct 2026 12:48:41 +0330 Subject: [PATCH 10/15] [client] Fix grammatical error in post-install message (#8242) --- release_files/post_install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release_files/post_install.sh b/release_files/post_install.sh index c763b7447..bd7e7feb8 100644 --- a/release_files/post_install.sh +++ b/release_files/post_install.sh @@ -19,7 +19,7 @@ restrict_env_file() { } cleanInstall() { - printf "\033[32m Post Install of an clean install\033[0m\n" + printf "\033[32m Post Install of a clean install\033[0m\n" restrict_env_file # Step 3 (clean install), enable the service in the proper way for this platform /usr/bin/netbird service install From 1f709707929da3fdbce27928e0c9618b8dc2953f Mon Sep 17 00:00:00 2001 From: Bethuel Mmbaga Date: Tue, 20 Oct 2026 13:33:46 +0300 Subject: [PATCH 11/15] [management] Mask credentials in logged URLs (#8250) --- combined/cmd/root.go | 8 ++++---- management/server/cache/redis.go | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/combined/cmd/root.go b/combined/cmd/root.go index 26d6ceedb..fa65f7b6d 100644 --- a/combined/cmd/root.go +++ b/combined/cmd/root.go @@ -758,7 +758,7 @@ func logAgentNetworkConfig(cfg *CombinedConfig) { // logEnvVars logs all NB_ environment variables that are currently set func logEnvVars() { - log.Info("=== Environment Variables ===") + log.Debug("=== Environment Variables ===") found := false for _, env := range os.Environ() { if strings.HasPrefix(env, "NB_") { @@ -770,14 +770,14 @@ func logEnvVars() { } else if strings.Contains(keyLower, "dsn") { value = maskDSNPassword(value) } - log.Infof(" %s=%s", key, value) + log.Debugf(" %s=%s", key, value) found = true } } if !found { - log.Info(" (none set)") + log.Debug(" (none set)") } - log.Info("=== End Environment Variables ===") + log.Debug("=== End Environment Variables ===") } // maskDSNPassword masks the password in a DSN string. diff --git a/management/server/cache/redis.go b/management/server/cache/redis.go index 0cd921c92..7aa3fb8e8 100644 --- a/management/server/cache/redis.go +++ b/management/server/cache/redis.go @@ -39,7 +39,7 @@ func getRedisStore(ctx context.Context, redisEnvAddr string, maxConn int) (Store return nil, err } - log.WithContext(subCtx).Infof("using redis cache at %s", redisEnvAddr) + log.WithContext(subCtx).Infof("using redis cache at %s", options.Addr) return &redisStore{ StoreInterface: redisstore.NewRedis(redisClient), From 7420c979303b0b0540356545ec87c1ec2bf37f12 Mon Sep 17 00:00:00 2001 From: Riccardo Manfrin <3090891+riccardomanfrin@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:35:15 +0200 Subject: [PATCH 12/15] [client] Keep the resolv.conf watch armed while repairing DNS in file mode (#8207) * [client] Split resolv.conf parsing from file reading Pure refactor, no behavior change. parseResolvConf parses content that was already read, so a caller can compare and parse the same snapshot of the file instead of reading it twice. * [client] Return the written content from the resolv.conf update function Pure refactor, no behavior change. The repair watcher needs to know what NetBird wrote so it can tell its own write apart from a third party's. Callers ignore the content for now. * [client] Keep the resolv.conf watch armed while repairing In file mode the repair watcher removed its inotify watch, rewrote resolv.conf and re-added the watch, without looking at the file again. A second third-party write landing in that window raised no event, so the file stayed on the upstream resolver until something else touched it. systemd-resolved with the stub listener off, the Amazon Linux 2023 default, writes the file twice in a row on restart and does not rewrite it on an unchanged DHCP renewal, so the host stayed off NetBird DNS while the client reported connected. The watch now stays armed during the repair. NetBird's own write is recognized by comparing the file with the content it wrote, which also covers a write whose search list was truncated to the resolv.conf limits and would otherwise fail the parameter check forever. The watcher checks the file once when it is armed, since a change made before that produced no event. * [client] Consume inotify errors in the resolv.conf watcher fsnotify blocks its reader until an error is received. The watcher never read the Errors channel, so a single error, such as an event queue overflow, stopped all further events and silently disabled the repair. The watcher now consumes errors and checks the file, since an overflow means events were dropped. * [client] Parse resolv.conf one line at a time Pure refactor, no behavior change. The per-line handling moves into parseResolvConfLine, which keeps parseResolvConf under the cognitive complexity limit. * [client] Drop the comment restating parseResolvConfLine --- client/internal/dns/file_parser_unix.go | 114 +++++++------ client/internal/dns/file_repair_unix.go | 107 +++++++----- client/internal/dns/file_repair_unix_test.go | 165 ++++++++++++++++++- client/internal/dns/file_unix.go | 10 +- 4 files changed, 297 insertions(+), 99 deletions(-) diff --git a/client/internal/dns/file_parser_unix.go b/client/internal/dns/file_parser_unix.go index 50ba74c0c..2ef05e3fd 100644 --- a/client/internal/dns/file_parser_unix.go +++ b/client/internal/dns/file_parser_unix.go @@ -35,11 +35,7 @@ func parseBackupResolvConf() (*resolvConf, error) { } func parseResolvConfFile(resolvConfFile string) (*resolvConf, error) { - rconf := &resolvConf{ - searchDomains: make([]string, 0), - nameServers: make([]netip.Addr, 0), - others: make([]string, 0), - } + rconf := newResolvConf() file, err := os.Open(resolvConfFile) if err != nil { @@ -56,56 +52,74 @@ func parseResolvConfFile(resolvConfFile string) (*resolvConf, error) { return rconf, fmt.Errorf("failed to read %s file: %w", resolvConfFile, err) } + return parseResolvConf(cur) +} + +// parseResolvConf parses resolv.conf content. The returned config is never nil, so callers can +// fall back to its empty lists on error. +func parseResolvConf(cur []byte) (*resolvConf, error) { + rconf := newResolvConf() + if len(cur) == 0 { return rconf, fmt.Errorf("file is empty") } for _, line := range strings.Split(string(cur), "\n") { - line = strings.TrimSpace(line) - - if strings.HasPrefix(line, "#") { - continue - } - - if strings.HasPrefix(line, "domain") { - continue - } - - if strings.HasPrefix(line, "options") && strings.Contains(line, "rotate") { - line = strings.ReplaceAll(line, "rotate", "") - splitLines := strings.Fields(line) - if len(splitLines) == 1 { - continue - } - line = strings.Join(splitLines, " ") - } - - if strings.HasPrefix(line, "search") { - splitLines := strings.Fields(line) - if len(splitLines) < 2 { - continue - } - - rconf.searchDomains = splitLines[1:] - continue - } - - if strings.HasPrefix(line, "nameserver") { - splitLines := strings.Fields(line) - if len(splitLines) != 2 { - continue - } - if addr, err := netip.ParseAddr(splitLines[1]); err == nil { - rconf.nameServers = append(rconf.nameServers, addr.Unmap()) - } else { - log.Warnf("invalid nameserver address in resolv.conf: %s, skipping", splitLines[1]) - } - continue - } - - if line != "" { - rconf.others = append(rconf.others, line) - } + parseResolvConfLine(rconf, strings.TrimSpace(line)) } return rconf, nil } + +func parseResolvConfLine(rconf *resolvConf, line string) { + if strings.HasPrefix(line, "#") { + return + } + + if strings.HasPrefix(line, "domain") { + return + } + + if strings.HasPrefix(line, "options") && strings.Contains(line, "rotate") { + line = strings.ReplaceAll(line, "rotate", "") + splitLines := strings.Fields(line) + if len(splitLines) == 1 { + return + } + line = strings.Join(splitLines, " ") + } + + if strings.HasPrefix(line, "search") { + splitLines := strings.Fields(line) + if len(splitLines) < 2 { + return + } + + rconf.searchDomains = splitLines[1:] + return + } + + if strings.HasPrefix(line, "nameserver") { + splitLines := strings.Fields(line) + if len(splitLines) != 2 { + return + } + if addr, err := netip.ParseAddr(splitLines[1]); err == nil { + rconf.nameServers = append(rconf.nameServers, addr.Unmap()) + } else { + log.Warnf("invalid nameserver address in resolv.conf: %s, skipping", splitLines[1]) + } + return + } + + if line != "" { + rconf.others = append(rconf.others, line) + } +} + +func newResolvConf() *resolvConf { + return &resolvConf{ + searchDomains: make([]string, 0), + nameServers: make([]netip.Addr, 0), + others: make([]string, 0), + } +} diff --git a/client/internal/dns/file_repair_unix.go b/client/internal/dns/file_repair_unix.go index 0846dbf38..57255fb56 100644 --- a/client/internal/dns/file_repair_unix.go +++ b/client/internal/dns/file_repair_unix.go @@ -3,7 +3,9 @@ package dns import ( + "bytes" "net/netip" + "os" "path" "path/filepath" "sync" @@ -23,7 +25,8 @@ var ( } ) -type repairConfFn func([]string, netip.Addr, *resolvConf, *statemanager.Manager) error +// repairConfFn writes the NetBird-managed resolv.conf and returns the exact content it wrote. +type repairConfFn func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) type repair struct { operationFile string @@ -43,7 +46,9 @@ func newRepair(operationFile string, updateFn repairConfFn) *repair { } } -func (f *repair) watchFileChanges(nbSearchDomains []string, nbNameserverIP netip.Addr, stateManager *statemanager.Manager) { +// watchFileChanges keeps resolv.conf pointing at NetBird. written is the content NetBird last +// wrote to the file, used to recognize the echo of its own writes. +func (f *repair) watchFileChanges(nbSearchDomains []string, nbNameserverIP netip.Addr, written []byte, stateManager *statemanager.Manager) { if f.inotify != nil { return } @@ -54,54 +59,80 @@ func (f *repair) watchFileChanges(nbSearchDomains []string, nbNameserverIP netip log.Errorf("failed to start inotify watcher for resolv.conf: %s", err) return } + + if err := inotify.Add(f.watchDir); err != nil { + log.Errorf("failed to add inotify watch for resolv.conf: %s", err) + if err := inotify.Close(); err != nil { + log.Debugf("failed to close resolv.conf inotify: %v", err) + } + return + } f.inotify = inotify f.inotifyWg.Add(1) go func() { defer f.inotifyWg.Done() - for event := range f.inotify.Events { - if !f.isEventRelevant(event) { - continue - } - log.Tracef("%s changed, check if it is broken", f.operationFile) - - rConf, err := parseResolvConfFile(f.operationFile) - if err != nil { - log.Warnf("failed to parse resolv conf: %s", err) - continue - } - - log.Debugf("check resolv.conf parameters: %s", rConf) - if !isNbParamsMissing(nbSearchDomains, nbNameserverIP, rConf) { - log.Tracef("resolv.conf still correct, skip the update") - continue - } - log.Info("broken params in resolv.conf, repairing it...") - - err = f.inotify.Remove(f.watchDir) - if err != nil { - log.Errorf("failed to rm inotify watch for resolv.conf: %s", err) - } - - err = f.updateFn(nbSearchDomains, nbNameserverIP, rConf, stateManager) - if err != nil { - log.Errorf("failed to repair resolv.conf: %v", err) - } - - err = f.inotify.Add(f.watchDir) - if err != nil { - log.Errorf("failed to re-add inotify watch for resolv.conf: %s", err) - return + // A change that landed before the watch was armed produced no event. + lastWritten := f.checkAndRepair(nbSearchDomains, nbNameserverIP, written, stateManager) + for { + select { + case event, ok := <-inotify.Events: + if !ok { + return + } + if !f.isEventRelevant(event) { + continue + } + case err, ok := <-inotify.Errors: + if !ok { + return + } + // fsnotify stops delivering events until an error is received, and an + // error such as a queue overflow means events were dropped. + log.Warnf("resolv.conf inotify error, checking the file: %v", err) } + lastWritten = f.checkAndRepair(nbSearchDomains, nbNameserverIP, lastWritten, stateManager) } }() +} - err = f.inotify.Add(f.watchDir) +// checkAndRepair rewrites resolv.conf when NetBird's parameters are missing from it and returns +// the content NetBird last wrote. The watch stays armed while repairing, so a third-party write +// racing the repair still raises an event; the echo of NetBird's own write is skipped by content. +func (f *repair) checkAndRepair(nbSearchDomains []string, nbNameserverIP netip.Addr, lastWritten []byte, stateManager *statemanager.Manager) []byte { + content, err := os.ReadFile(f.operationFile) if err != nil { - log.Errorf("failed to add inotify watch for resolv.conf: %s", err) - return + log.Warnf("failed to read resolv.conf: %s", err) + return lastWritten } + + if bytes.Equal(content, lastWritten) { + log.Tracef("%s still holds the NetBird managed content, skip the check", f.operationFile) + return lastWritten + } + + log.Tracef("%s changed, check if it is broken", f.operationFile) + + rConf, err := parseResolvConf(content) + if err != nil { + log.Warnf("failed to parse resolv conf: %s", err) + return lastWritten + } + + log.Debugf("check resolv.conf parameters: %s", rConf) + if !isNbParamsMissing(nbSearchDomains, nbNameserverIP, rConf) { + log.Tracef("resolv.conf still correct, skip the update") + return lastWritten + } + log.Info("broken params in resolv.conf, repairing it...") + + written, err := f.updateFn(nbSearchDomains, nbNameserverIP, rConf, stateManager) + if err != nil { + log.Errorf("failed to repair resolv.conf: %v", err) + return lastWritten + } + return written } func (f *repair) stopWatchFileChanges() { diff --git a/client/internal/dns/file_repair_unix_test.go b/client/internal/dns/file_repair_unix_test.go index f22081307..c771ff641 100644 --- a/client/internal/dns/file_repair_unix_test.go +++ b/client/internal/dns/file_repair_unix_test.go @@ -4,12 +4,19 @@ package dns import ( "context" + "fmt" "net/netip" "os" "path/filepath" + "strings" + "sync/atomic" "testing" "time" + "github.com/fsnotify/fsnotify" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/netbirdio/netbird/client/internal/statemanager" "github.com/netbirdio/netbird/util" ) @@ -106,14 +113,14 @@ nameserver 8.8.8.8`, var changed bool ctx, cancel := context.WithTimeout(context.Background(), time.Second) - updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) error { + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { changed = true cancel() - return nil + return nil, nil } r := newRepair(operationFile, updateFn) - r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), nil) + r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), nil, nil) err = os.WriteFile(operationFile, []byte(tt.touchedConfContent), 0755) if err != nil { @@ -153,14 +160,14 @@ searchdomain netbird.cloud something` var changed bool ctx, cancel := context.WithTimeout(context.Background(), time.Second) - updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) error { + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { changed = true cancel() - return nil + return nil, nil } r := newRepair(tmpLink, updateFn) - r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), nil) + r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), nil, nil) err = os.WriteFile(tmpLink, []byte(modifyContent), 0755) if err != nil { @@ -175,3 +182,149 @@ searchdomain netbird.cloud something` t.Errorf("unexpected result: want: %v, got: %v", true, false) } } + +// systemd-resolved can rewrite resolv.conf twice in a row, e.g. on restart. When the second write +// lands right after NetBird's repair, the watcher must still see it and repair again; otherwise the +// host silently stays on the upstream resolver until the next unrelated change of the file. +func Test_repairCatchesWriteRacingRepair(t *testing.T) { + good := "nameserver 10.0.0.1\nsearch netbird.cloud\n" + upstream := "nameserver 8.8.8.8\nsearch .\n" + operationFile := filepath.Join(t.TempDir(), "resolv.conf") + require.NoError(t, os.WriteFile(operationFile, []byte(good), 0644)) + + var calls atomic.Int32 + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { + n := calls.Add(1) + if err := os.WriteFile(operationFile, []byte(good), 0644); err != nil { + return nil, err + } + if n == 1 { + // the third party's second write lands right after the repair + if err := writeFileAtomic(operationFile, upstream); err != nil { + return nil, err + } + } + return []byte(good), nil + } + + r := newRepair(operationFile, updateFn) + r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), []byte(good), nil) + t.Cleanup(r.stopWatchFileChanges) + + require.NoError(t, writeFileAtomic(operationFile, upstream)) + + assert.Eventually(t, func() bool { + content, err := os.ReadFile(operationFile) + return err == nil && string(content) == good + }, 2*time.Second, 10*time.Millisecond, "resolv.conf should be repaired after the racing write") + assert.GreaterOrEqual(t, calls.Load(), int32(2), "the racing write should trigger a second repair") +} + +// A change made between NetBird's write and the arming of the watch produces no event, so the +// watcher must check the file as soon as it starts. +func Test_repairChecksFileWhenArmed(t *testing.T) { + good := "nameserver 10.0.0.1\nsearch netbird.cloud\n" + operationFile := filepath.Join(t.TempDir(), "resolv.conf") + require.NoError(t, os.WriteFile(operationFile, []byte("nameserver 8.8.8.8\n"), 0644)) + + repaired := make(chan struct{}, 1) + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { + select { + case repaired <- struct{}{}: + default: + } + return []byte(good), os.WriteFile(operationFile, []byte(good), 0644) + } + + r := newRepair(operationFile, updateFn) + r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), []byte(good), nil) + t.Cleanup(r.stopWatchFileChanges) + + select { + case <-repaired: + case <-time.After(2 * time.Second): + t.Fatal("watcher should repair a file changed before it was armed") + } +} + +// When NetBird has more search domains than resolv.conf can hold, its own write lacks some of them +// and fails the parameter check. The watcher must recognize that write as its own and not repair +// it again in a loop. +func Test_repairNoLoopOnTruncatedSearchDomains(t *testing.T) { + nbDomains := make([]string, 0, fileMaxNumberOfSearchDomains+2) + for i := range fileMaxNumberOfSearchDomains + 2 { + nbDomains = append(nbDomains, fmt.Sprintf("d%d.netbird.cloud", i)) + } + truncated := fmt.Sprintf("nameserver 10.0.0.1\nsearch %s\n", strings.Join(nbDomains[:fileMaxNumberOfSearchDomains], " ")) + + operationFile := filepath.Join(t.TempDir(), "resolv.conf") + require.NoError(t, os.WriteFile(operationFile, []byte(truncated), 0644)) + + var calls atomic.Int32 + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { + calls.Add(1) + return []byte(truncated), os.WriteFile(operationFile, []byte(truncated), 0644) + } + + r := newRepair(operationFile, updateFn) + r.watchFileChanges(nbDomains, netip.MustParseAddr("10.0.0.1"), []byte(truncated), nil) + t.Cleanup(r.stopWatchFileChanges) + + require.NoError(t, writeFileAtomic(operationFile, "nameserver 8.8.8.8\n")) + + require.Eventually(t, func() bool { return calls.Load() >= 1 }, 2*time.Second, 10*time.Millisecond, + "the third-party write should be repaired") + time.Sleep(500 * time.Millisecond) + assert.Equal(t, int32(1), calls.Load(), "NetBird's own truncated write should not trigger another repair") +} + +// fsnotify blocks its reader until an error is received, and an error such as a queue overflow +// means events were dropped. The watcher must consume errors and check the file, so it keeps working +// and catches a change whose event was lost. +func Test_repairChecksFileOnWatcherError(t *testing.T) { + good := "nameserver 10.0.0.1\nsearch netbird.cloud\n" + operationFile := filepath.Join(t.TempDir(), "resolv.conf") + require.NoError(t, os.WriteFile(operationFile, []byte(good), 0644)) + + // A hard link in another directory changes the file without an event in the watched one, + // standing in for an event the kernel dropped. + alias := filepath.Join(t.TempDir(), "alias") + require.NoError(t, os.Link(operationFile, alias)) + + repaired := make(chan struct{}, 1) + updateFn := func([]string, netip.Addr, *resolvConf, *statemanager.Manager) ([]byte, error) { + select { + case repaired <- struct{}{}: + default: + } + return []byte(good), os.WriteFile(operationFile, []byte(good), 0644) + } + + r := newRepair(operationFile, updateFn) + r.watchFileChanges([]string{"netbird.cloud"}, netip.MustParseAddr("10.0.0.1"), []byte(good), nil) + t.Cleanup(r.stopWatchFileChanges) + + require.NoError(t, os.WriteFile(alias, []byte("nameserver 8.8.8.8\n"), 0644)) + + select { + case r.inotify.Errors <- fsnotify.ErrEventOverflow: + case <-time.After(2 * time.Second): + t.Fatal("watcher should consume inotify errors") + } + + select { + case <-repaired: + case <-time.After(2 * time.Second): + t.Fatal("watcher should check the file after an inotify error") + } +} + +// writeFileAtomic replaces the file the way systemd-resolved does: write a temporary file in the same +// directory, then rename it over the target. +func writeFileAtomic(target, content string) error { + tmp := target + ".tmp" + if err := os.WriteFile(tmp, []byte(content), 0644); err != nil { + return err + } + return os.Rename(tmp, target) +} diff --git a/client/internal/dns/file_unix.go b/client/internal/dns/file_unix.go index 45e621443..52f221d10 100644 --- a/client/internal/dns/file_unix.go +++ b/client/internal/dns/file_unix.go @@ -61,11 +61,11 @@ func (f *fileConfigurator) applyDNSConfig(config HostDNSConfig, stateManager *st f.repair.stopWatchFileChanges() - err = f.updateConfig(nbSearchDomains, f.nbNameserverIP, resolvConf, stateManager) + written, err := f.updateConfig(nbSearchDomains, f.nbNameserverIP, resolvConf, stateManager) if err != nil { return err } - f.repair.watchFileChanges(nbSearchDomains, f.nbNameserverIP, stateManager) + f.repair.watchFileChanges(nbSearchDomains, f.nbNameserverIP, written, stateManager) return nil } @@ -74,7 +74,7 @@ func (f *fileConfigurator) getOriginalNameservers() []netip.Addr { return f.originalNameservers } -func (f *fileConfigurator) updateConfig(nbSearchDomains []string, nbNameserverIP netip.Addr, cfg *resolvConf, stateManager *statemanager.Manager) error { +func (f *fileConfigurator) updateConfig(nbSearchDomains []string, nbNameserverIP netip.Addr, cfg *resolvConf, stateManager *statemanager.Manager) ([]byte, error) { searchDomainList := mergeSearchDomains(nbSearchDomains, cfg.searchDomains) buf := prepareResolvConfContent( @@ -90,7 +90,7 @@ func (f *fileConfigurator) updateConfig(nbSearchDomains []string, nbNameserverIP if restoreErr != nil { log.Errorf("attempt to restore default file failed with error: %s", err) } - return fmt.Errorf("creating resolver file %s. Error: %w", defaultResolvConfPath, err) + return nil, fmt.Errorf("creating resolver file %s. Error: %w", defaultResolvConfPath, err) } log.Infof("created a NetBird managed %s file with the DNS settings. Added %d search domains. Search list: %s", defaultResolvConfPath, len(searchDomainList), searchDomainList) @@ -100,7 +100,7 @@ func (f *fileConfigurator) updateConfig(nbSearchDomains []string, nbNameserverIP log.Errorf("failed to create unclean shutdown resolv.conf backup: %s", err) } - return nil + return buf.Bytes(), nil } func (f *fileConfigurator) restoreHostDNS() error { From b866d1584c9989f0ad8b4ccc319e189aead66a6e Mon Sep 17 00:00:00 2001 From: Maycon Santos Date: Tue, 20 Oct 2026 14:07:00 +0200 Subject: [PATCH 13/15] [client] Drop the non-functional admin URL (#8267) * [client] Drop the non-functional admin URL #4218 deprecated --admin-url, but #3980 merged right after it and restored the flag and its wiring. The value has been stored and echoed back ever since, without anything reading it. Stop sending it from the CLI, ignore it in the daemon and drop it from the profile config, the UI settings service and the debug bundle. The proto fields stay for older clients, and the mobile getters and setters keep their signatures as deprecated stubs. * [client] Drop adminUrl from the Wails API reference --- client/android/preferences.go | 22 +++----- client/android/preferences_test.go | 5 +- client/cmd/root.go | 3 +- client/cmd/up.go | 1 - client/internal/debug/debug.go | 7 --- client/internal/debug/debug_test.go | 10 +--- client/internal/profilemanager/config.go | 50 ++----------------- client/internal/profilemanager/config_test.go | 6 --- .../config_would_change_test.go | 50 ++++++++----------- client/ios/NetBirdSDK/preferences.go | 22 +++----- client/ios/NetBirdSDK/preferences_test.go | 5 +- client/server/server.go | 5 -- client/server/setconfig_test.go | 10 ++-- client/ui/frontend/WAILS-API.md | 6 +-- client/ui/services/settings.go | 4 -- 15 files changed, 60 insertions(+), 146 deletions(-) diff --git a/client/android/preferences.go b/client/android/preferences.go index 3623de23f..af37682c5 100644 --- a/client/android/preferences.go +++ b/client/android/preferences.go @@ -58,23 +58,17 @@ func (p *Preferences) SetManagementURL(url string) { p.configInput.ManagementURL = url } -// GetAdminURL reads URL from config file +// GetAdminURL returns the default admin panel URL. +// +// Deprecated: the admin URL is no longer stored or used by the client. func (p *Preferences) GetAdminURL() (string, error) { - if p.configInput.AdminURL != "" { - return p.configInput.AdminURL, nil - } - - cfg, err := profilemanager.ReadConfigOrDefault(p.configInput.ConfigPath) - if err != nil { - return "", err - } - return cfg.AdminURL.String(), err + return profilemanager.DefaultAdminURL, nil } -// SetAdminURL stores the given URL and waits for commit -func (p *Preferences) SetAdminURL(url string) { - p.configInput.AdminURL = url -} +// SetAdminURL is a no-op kept for API compatibility. +// +// Deprecated: the admin URL is no longer stored or used by the client. +func (p *Preferences) SetAdminURL(_ string) {} // HasPreSharedKey reports whether a pre-shared key is staged, persisted, or // enforced by MDM; the key itself is never handed to the native layer. diff --git a/client/android/preferences_test.go b/client/android/preferences_test.go index d9f5b1918..98670afe0 100644 --- a/client/android/preferences_test.go +++ b/client/android/preferences_test.go @@ -43,13 +43,14 @@ func TestPreferences_ReadUncommitedValues(t *testing.T) { cfgFile := filepath.Join(t.TempDir(), "netbird.json") p := NewPreferences(cfgFile) + // The admin URL is deprecated: setting it is a no-op. p.SetAdminURL(exampleString) resp, err := p.GetAdminURL() if err != nil { t.Fatalf("failed to read admin url: %s", err) } - if resp != exampleString { + if resp != profilemanager.DefaultAdminURL { t.Errorf("unexpected admin url: %s", resp) } @@ -95,7 +96,7 @@ func TestPreferences_Commit(t *testing.T) { t.Fatalf("failed to read admin url: %s", err) } - if resp != exampleURL { + if resp != profilemanager.DefaultAdminURL { t.Errorf("unexpected admin url: %s", resp) } diff --git a/client/cmd/root.go b/client/cmd/root.go index 51179f77c..f976ca895 100644 --- a/client/cmd/root.go +++ b/client/cmd/root.go @@ -157,7 +157,8 @@ func init() { rootCmd.PersistentFlags().StringVar(&daemonAddr, "daemon-addr", defaultDaemonAddr, "Daemon service address to serve CLI requests [unix|tcp|npipe]://[path|host:port|name]") rootCmd.PersistentFlags().StringVarP(&managementURL, "management-url", "m", "", fmt.Sprintf("Management Service URL [http|https]://[host]:[port] (default \"%s\")", profilemanager.DefaultManagementURL)) - rootCmd.PersistentFlags().StringVar(&adminURL, "admin-url", "", fmt.Sprintf("Admin Panel URL [http|https]://[host]:[port] (default \"%s\")", profilemanager.DefaultAdminURL)) + rootCmd.PersistentFlags().StringVar(&adminURL, "admin-url", "", "(DEPRECATED) Admin Panel URL - This flag is no longer functional") + _ = rootCmd.PersistentFlags().MarkDeprecated("admin-url", "the admin-url flag is no longer functional and will be removed in a future version") rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "sets NetBird log level") rootCmd.PersistentFlags().StringSliceVar(&logFiles, "log-file", []string{defaultLogFile}, "sets NetBird log paths written to simultaneously. If `console` is specified the log will be output to stdout. If `syslog` is specified the log will be sent to syslog daemon. You can pass the flag multiple times or separate entries by `,` character") rootCmd.PersistentFlags().StringVarP(&setupKey, "setup-key", "k", "", "Setup key obtained from the Management Service Dashboard (used to register peer)") diff --git a/client/cmd/up.go b/client/cmd/up.go index e336ba257..1b5a4a6cd 100644 --- a/client/cmd/up.go +++ b/client/cmd/up.go @@ -493,7 +493,6 @@ func setupSetConfigReq(customDNSAddressConverted []byte, cmd *cobra.Command, pro req.Username = username req.ManagementUrl = managementURL - req.AdminURL = adminURL req.NatExternalIPs = natExternalIPs req.CustomDNSAddress = customDNSAddressConverted req.ExtraIFaceBlacklist = extraIFaceBlackList diff --git a/client/internal/debug/debug.go b/client/internal/debug/debug.go index 95419b0e9..5e8badfc5 100644 --- a/client/internal/debug/debug.go +++ b/client/internal/debug/debug.go @@ -174,7 +174,6 @@ The IP addresses in the interfaces file are anonymized using the same process as Configuration The config.txt file contains anonymized configuration information of the NetBird client. Sensitive information such as private keys and SSH keys are excluded. The following fields are anonymized: - ManagementURL -- AdminURL - NATExternalIPs - CustomDNSAddress @@ -602,9 +601,6 @@ func (g *BundleGenerator) addConfig() error { if g.internalConfig.ManagementURL != nil { configContent.WriteString(fmt.Sprintf("ManagementURL: %s\n", g.anonymizer.AnonymizeURI(g.internalConfig.ManagementURL.String()))) } - if g.internalConfig.AdminURL != nil { - configContent.WriteString(fmt.Sprintf("AdminURL: %s\n", g.anonymizer.AnonymizeURI(g.internalConfig.AdminURL.String()))) - } configContent.WriteString(fmt.Sprintf("NATExternalIPs: %v\n", anonymizeNATExternalIPs(g.internalConfig.NATExternalIPs, g.anonymizer))) if g.internalConfig.CustomDNSAddress != "" { configContent.WriteString(fmt.Sprintf("CustomDNSAddress: %s\n", g.anonymizer.AnonymizeString(g.internalConfig.CustomDNSAddress))) @@ -613,9 +609,6 @@ func (g *BundleGenerator) addConfig() error { if g.internalConfig.ManagementURL != nil { configContent.WriteString(fmt.Sprintf("ManagementURL: %s\n", g.internalConfig.ManagementURL.String())) } - if g.internalConfig.AdminURL != nil { - configContent.WriteString(fmt.Sprintf("AdminURL: %s\n", g.internalConfig.AdminURL.String())) - } configContent.WriteString(fmt.Sprintf("NATExternalIPs: %v\n", g.internalConfig.NATExternalIPs)) if g.internalConfig.CustomDNSAddress != "" { configContent.WriteString(fmt.Sprintf("CustomDNSAddress: %s\n", g.internalConfig.CustomDNSAddress)) diff --git a/client/internal/debug/debug_test.go b/client/internal/debug/debug_test.go index a9cda5a46..93886c5e7 100644 --- a/client/internal/debug/debug_test.go +++ b/client/internal/debug/debug_test.go @@ -856,14 +856,12 @@ func TestAddConfig_AllFieldsCovered(t *testing.T) { } mURL, _ := url.Parse("https://api.example.com:443") - aURL, _ := url.Parse("https://admin.example.com:443") bTrue := true iVal := 42 cfg := &profilemanager.Config{ PrivateKey: "priv", PreSharedKey: "psk", ManagementURL: mURL, - AdminURL: aURL, WgIface: "wt0", WgPort: 51820, NetworkMonitor: &bTrue, @@ -947,7 +945,7 @@ func TestAddConfig_AllFieldsCovered(t *testing.T) { } // renderAddConfigSpecific renders the fields handled by the anonymize/non-anonymize -// branches in addConfig (ManagementURL, AdminURL, NATExternalIPs, CustomDNSAddress). +// branches in addConfig (ManagementURL, NATExternalIPs, CustomDNSAddress). // addCommonConfigFields covers the rest. Keeping this in the test mirrors the // production shape without needing to write an actual zip. func renderAddConfigSpecific(g *BundleGenerator) string { @@ -956,9 +954,6 @@ func renderAddConfigSpecific(g *BundleGenerator) string { if g.internalConfig.ManagementURL != nil { sb.WriteString("ManagementURL: " + g.anonymizer.AnonymizeURI(g.internalConfig.ManagementURL.String()) + "\n") } - if g.internalConfig.AdminURL != nil { - sb.WriteString("AdminURL: " + g.anonymizer.AnonymizeURI(g.internalConfig.AdminURL.String()) + "\n") - } sb.WriteString("NATExternalIPs: x\n") if g.internalConfig.CustomDNSAddress != "" { sb.WriteString("CustomDNSAddress: " + g.anonymizer.AnonymizeString(g.internalConfig.CustomDNSAddress) + "\n") @@ -967,9 +962,6 @@ func renderAddConfigSpecific(g *BundleGenerator) string { if g.internalConfig.ManagementURL != nil { sb.WriteString("ManagementURL: " + g.internalConfig.ManagementURL.String() + "\n") } - if g.internalConfig.AdminURL != nil { - sb.WriteString("AdminURL: " + g.internalConfig.AdminURL.String() + "\n") - } sb.WriteString("NATExternalIPs: x\n") if g.internalConfig.CustomDNSAddress != "" { sb.WriteString("CustomDNSAddress: " + g.internalConfig.CustomDNSAddress + "\n") diff --git a/client/internal/profilemanager/config.go b/client/internal/profilemanager/config.go index 3d378a9e6..6c797a184 100644 --- a/client/internal/profilemanager/config.go +++ b/client/internal/profilemanager/config.go @@ -36,7 +36,8 @@ const ( DefaultManagementURL = "https://api.netbird.io:443" // oldDefaultManagementURL points to the NetBird's old cloud management endpoint oldDefaultManagementURL = "https://api.wiretrustee.com:443" - // DefaultAdminURL points to NetBird's cloud management console + // DefaultAdminURL points to NetBird's cloud management console. It is only + // reported by the deprecated mobile admin URL getters. DefaultAdminURL = "https://app.netbird.io:443" ) @@ -60,7 +61,6 @@ var DefaultInterfaceBlacklist = []string{ // ConfigInput carries configuration changes to the client type ConfigInput struct { ManagementURL string - AdminURL string ConfigPath string StateFilePath string PreSharedKey *string @@ -114,7 +114,6 @@ type Config struct { PrivateKey string PreSharedKey string ManagementURL *url.URL - AdminURL *url.URL WgIface string WgPort int NetworkMonitor *bool @@ -508,29 +507,6 @@ func (config *Config) apply(input ConfigInput) (updated bool, err error) { } } - if config.AdminURL == nil { - log.Infof("using default Admin URL %s", DefaultAdminURL) - config.AdminURL, err = parseURL("Admin URL", DefaultAdminURL) - if err != nil { - return false, err - } - } - // The admin panel is opened, not dialed, so unlike the Management URL its - // path is part of what identifies it: a panel served under /netbird is not - // the one served at the root. - if input.AdminURL != "" { - newURL, err := parseURL("Admin Panel URL", input.AdminURL) - if err != nil { - return updated, err - } - if !SameServiceURLIncludingPath(newURL, config.AdminURL) { - log.Infof("new Admin Panel URL provided, updated to %#v (old value %#v)", - newURL.String(), config.AdminURL.String()) - config.AdminURL = newURL - updated = true - } - } - if input.WireguardPort != nil && *input.WireguardPort != config.WgPort { log.Infof("updating Wireguard port %d (old value %d)", *input.WireguardPort, config.WgPort) @@ -1027,8 +1003,7 @@ func ParseServiceURL(serviceName, serviceURL string) (*url.URL, error) { // matches only another nil one. // // The path plays no part: a management URL is dialed, and only its host and -// port are. util.SameServiceURL is this comparison plus the path, which is -// what SameServiceURLIncludingPath needs and delegates to. +// port are. util.SameServiceURL is this comparison plus the path. func SameServiceURL(a, b *url.URL) bool { if a == nil || b == nil { return a == b @@ -1039,25 +1014,6 @@ func SameServiceURL(a, b *url.URL) bool { util.ServiceURLPort(a) == util.ServiceURLPort(b) } -// SameServiceURLIncludingPath is SameServiceURL plus everything a URL carries -// past its endpoint: path, query, fragment and userinfo. -// -// Use it for a URL that gets opened rather than dialed. The admin panel can -// live under a path, so two URLs with the same endpoint and different paths are -// two different panels — where for a URL the client dials over gRPC only the -// endpoint is ever used. Equivalent spellings still compare equal: a missing -// path and "/" are the same root, and so is a trailing slash on any path. -func SameServiceURLIncludingPath(a, b *url.URL) bool { - if a == nil || b == nil { - return a == b - } - - return util.SameServiceURL(a, b) && - a.RawQuery == b.RawQuery && - a.Fragment == b.Fragment && - a.User.String() == b.User.String() -} - func parseURL(serviceName, serviceURL string) (*url.URL, error) { parsedMgmtURL, err := url.ParseRequestURI(serviceURL) if err != nil { diff --git a/client/internal/profilemanager/config_test.go b/client/internal/profilemanager/config_test.go index a461aa71f..192fc8ec8 100644 --- a/client/internal/profilemanager/config_test.go +++ b/client/internal/profilemanager/config_test.go @@ -36,17 +36,14 @@ func TestGetConfig(t *testing.T) { } assert.Equal(t, config.ManagementURL.String(), DefaultManagementURL) - assert.Equal(t, config.AdminURL.String(), DefaultAdminURL) managementURL := "https://test.management.url:33071" - adminURL := "https://app.admin.url:443" path := filepath.Join(t.TempDir(), "config.json") preSharedKey := "preSharedKey" // case 2: new config has to be generated config, err = UpdateOrCreateConfig(ConfigInput{ ManagementURL: managementURL, - AdminURL: adminURL, ConfigPath: path, PreSharedKey: &preSharedKey, }) @@ -64,7 +61,6 @@ func TestGetConfig(t *testing.T) { // case 3: existing config -> fetch it config, err = UpdateOrCreateConfig(ConfigInput{ ManagementURL: managementURL, - AdminURL: adminURL, ConfigPath: path, PreSharedKey: &preSharedKey, }) @@ -79,7 +75,6 @@ func TestGetConfig(t *testing.T) { newManagementURL := "https://test.newManagement.url:33071" config, err = UpdateOrCreateConfig(ConfigInput{ ManagementURL: newManagementURL, - AdminURL: adminURL, ConfigPath: path, PreSharedKey: &preSharedKey, }) @@ -164,7 +159,6 @@ func TestNewProfileDefaults(t *testing.T) { require.NoError(t, err, "should create new config") assert.Equal(t, DefaultManagementURL, config.ManagementURL.String(), "ManagementURL should have default") - assert.Equal(t, DefaultAdminURL, config.AdminURL.String(), "AdminURL should have default") assert.NotEmpty(t, config.PrivateKey, "PrivateKey should be generated") assert.NotEmpty(t, config.SSHKey, "SSHKey should be generated") assert.Equal(t, iface.WgInterfaceDefault, config.WgIface, "WgIface should have default") diff --git a/client/internal/profilemanager/config_would_change_test.go b/client/internal/profilemanager/config_would_change_test.go index 6b140030f..3efa2fb05 100644 --- a/client/internal/profilemanager/config_would_change_test.go +++ b/client/internal/profilemanager/config_would_change_test.go @@ -334,40 +334,34 @@ func TestCreateInMemoryConfigCarriesAnIdentity(t *testing.T) { require.NotEmpty(t, cfg.SSHKey) } -// The admin panel is opened, not dialed, so its path identifies it. Comparing -// it as a bare endpoint left a custom panel URL unable to change. -func TestAdminURLPathIsPartOfTheIdentity(t *testing.T) { - path := filepath.Join(t.TempDir(), "panel.json") - _, err := UpdateOrCreateConfig(ConfigInput{ - ConfigPath: path, - AdminURL: "https://app.example.com/netbird", - }) +// Profiles written before the admin URL was dropped still carry an AdminURL key. +// It must not break loading, and the next write must drop it. +func TestLegacyAdminURLIsIgnored(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy.json") + _, err := UpdateOrCreateConfig(ConfigInput{ConfigPath: path}) require.NoError(t, err) - cfg, err := GetExistingConfig(path) + raw, err := os.ReadFile(path) require.NoError(t, err) - require.Equal(t, "https://app.example.com:443/netbird", cfg.AdminURL.String()) - - // Equivalent spellings of the same panel are still not a change. - for _, same := range []string{ - "https://app.example.com/netbird", - "https://app.example.com:443/netbird", - "https://app.example.com/netbird/", - "https://APP.example.com/netbird", - } { - changed, err := cfg.WouldChange(ConfigInput{AdminURL: same}) - require.NoError(t, err) - require.False(t, changed, "%q is the stored panel written differently", same) - } - - // A different path is a different panel, and it must be persisted. - changed, err := cfg.WouldChange(ConfigInput{AdminURL: "https://app.example.com/other"}) + var stored map[string]json.RawMessage + require.NoError(t, json.Unmarshal(raw, &stored)) + stored["AdminURL"] = json.RawMessage(`{"Scheme":"https","Host":"panel.example.com:443","Path":"/netbird"}`) + rewritten, err := json.Marshal(stored) require.NoError(t, err) - require.True(t, changed, "a different panel path is a change") + require.NoError(t, os.WriteFile(path, rewritten, 0600)) - updated, err := UpdateConfig(ConfigInput{ConfigPath: path, AdminURL: "https://app.example.com/other"}) + _, err = GetExistingConfig(path) + require.NoError(t, err, "a legacy AdminURL key must not prevent loading the profile") + + port := 51999 + _, err = UpdateConfig(ConfigInput{ConfigPath: path, WireguardPort: &port}) require.NoError(t, err) - require.Equal(t, "https://app.example.com:443/other", updated.AdminURL.String(), "the new panel path was not persisted") + + raw, err = os.ReadFile(path) + require.NoError(t, err) + stored = nil + require.NoError(t, json.Unmarshal(raw, &stored)) + require.NotContains(t, stored, "AdminURL", "the legacy AdminURL key should be dropped on write") } // unsetOnDisk rewrites the stored config so the named fields carry a JSON null, diff --git a/client/ios/NetBirdSDK/preferences.go b/client/ios/NetBirdSDK/preferences.go index 642f9e160..4209a5654 100644 --- a/client/ios/NetBirdSDK/preferences.go +++ b/client/ios/NetBirdSDK/preferences.go @@ -61,23 +61,17 @@ func (p *Preferences) SetManagementURL(url string) { p.configInput.ManagementURL = url } -// GetAdminURL read url from config file +// GetAdminURL returns the default admin panel URL. +// +// Deprecated: the admin URL is no longer stored or used by the client. func (p *Preferences) GetAdminURL() (string, error) { - if p.configInput.AdminURL != "" { - return p.configInput.AdminURL, nil - } - - cfg, err := profilemanager.ReadConfigOrDefault(p.configInput.ConfigPath) - if err != nil { - return "", err - } - return cfg.AdminURL.String(), err + return profilemanager.DefaultAdminURL, nil } -// SetAdminURL store the given url and wait for commit -func (p *Preferences) SetAdminURL(url string) { - p.configInput.AdminURL = url -} +// SetAdminURL is a no-op kept for API compatibility. +// +// Deprecated: the admin URL is no longer stored or used by the client. +func (p *Preferences) SetAdminURL(_ string) {} // HasPreSharedKey reports whether a pre-shared key is staged, persisted, or // enforced by MDM; the key itself is never handed to the native layer. diff --git a/client/ios/NetBirdSDK/preferences_test.go b/client/ios/NetBirdSDK/preferences_test.go index 2382e123c..2deb996b2 100644 --- a/client/ios/NetBirdSDK/preferences_test.go +++ b/client/ios/NetBirdSDK/preferences_test.go @@ -47,13 +47,14 @@ func TestPreferences_ReadUncommitedValues(t *testing.T) { stateFile := filepath.Join(t.TempDir(), "state.json") p := NewPreferences(cfgFile, stateFile) + // The admin URL is deprecated: setting it is a no-op. p.SetAdminURL(exampleString) resp, err := p.GetAdminURL() if err != nil { t.Fatalf("failed to read admin url: %s", err) } - if resp != exampleString { + if resp != profilemanager.DefaultAdminURL { t.Errorf("unexpected admin url: %s", resp) } @@ -100,7 +101,7 @@ func TestPreferences_Commit(t *testing.T) { t.Fatalf("failed to read admin url: %s", err) } - if resp != exampleURL { + if resp != profilemanager.DefaultAdminURL { t.Errorf("unexpected admin url: %s", resp) } diff --git a/client/server/server.go b/client/server/server.go index 4ce2a5c82..94469c683 100644 --- a/client/server/server.go +++ b/client/server/server.go @@ -593,9 +593,6 @@ func (s *Server) setConfigInputFromRequest(msg *proto.SetConfigRequest) (profile if msg.ManagementUrl != "" { config.ManagementURL = msg.ManagementUrl } - if msg.AdminURL != "" { - config.AdminURL = msg.AdminURL - } if msg.InterfaceName != nil { config.InterfaceName = msg.InterfaceName } @@ -2409,7 +2406,6 @@ func (s *Server) GetConfig(ctx context.Context, req *proto.GetConfigRequest) (*p // overlay (Loader lives outside profilemanager). cfg.ApplyMDMPolicy(s.mdmLoader.Load()) managementURL := cfg.ManagementURL - adminURL := cfg.AdminURL var preSharedKey = cfg.PreSharedKey if preSharedKey != "" { @@ -2465,7 +2461,6 @@ func (s *Server) GetConfig(ctx context.Context, req *proto.GetConfigRequest) (*p return &proto.GetConfigResponse{ ManagementUrl: managementURL.String(), PreSharedKey: preSharedKey, - AdminURL: adminURL.String(), InterfaceName: cfg.WgIface, WireguardPort: int64(cfg.WgPort), Mtu: int64(cfg.MTU), diff --git a/client/server/setconfig_test.go b/client/server/setconfig_test.go index d7f7b2bd5..454bfe423 100644 --- a/client/server/setconfig_test.go +++ b/client/server/setconfig_test.go @@ -1,6 +1,7 @@ package server import ( + "os" "os/user" "path/filepath" "reflect" @@ -129,7 +130,10 @@ func TestSetConfig_AllFieldsSaved(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://new-api.netbird.io:443", cfg.ManagementURL.String()) - require.Equal(t, "https://new-admin.netbird.io:443", cfg.AdminURL.String()) + // Older clients still send the deprecated admin URL; it must be ignored. + raw, err := os.ReadFile(cfgPath) + require.NoError(t, err) + require.NotContains(t, string(raw), "new-admin.netbird.io", "deprecated AdminURL must not be persisted") require.Equal(t, rosenpassEnabled, cfg.RosenpassEnabled) require.Equal(t, rosenpassPermissive, cfg.RosenpassPermissive) require.NotNil(t, cfg.ServerSSHAllowed) @@ -182,11 +186,11 @@ func verifyAllFieldsCovered(t *testing.T, req *proto.SetConfigRequest) { "CleanNATExternalIPs": true, // control flag for clearing "CleanDNSLabels": true, // control flag for clearing "LazyConnectionEnabled": true, // deprecated: proto field retained for compat, no longer applied + "AdminURL": true, // deprecated: proto field retained for compat, no longer applied } expectedFields := map[string]bool{ "ManagementUrl": true, - "AdminURL": true, "RosenpassEnabled": true, "RosenpassPermissive": true, "ServerSSHAllowed": true, @@ -249,7 +253,6 @@ func TestCLIFlags_MappedToSetConfig(t *testing.T) { // This map must be updated when adding new config-related CLI flags. flagToField := map[string]string{ "management-url": "ManagementUrl", - "admin-url": "AdminURL", "enable-rosenpass": "RosenpassEnabled", "rosenpass-permissive": "RosenpassPermissive", "allow-server-ssh": "ServerSSHAllowed", @@ -286,6 +289,7 @@ func TestCLIFlags_MappedToSetConfig(t *testing.T) { fieldsWithoutCLIFlags := map[string]bool{ "DisableNotifications": true, // Only settable via UI "LazyConnectionEnabled": true, // deprecated: no longer settable (managed by server + NB_LAZY_CONN) + "AdminURL": true, // deprecated: the admin-url flag is no longer functional } // Get all SetConfigRequest fields to verify our map is complete. diff --git a/client/ui/frontend/WAILS-API.md b/client/ui/frontend/WAILS-API.md index 6cc1dd79c..ad0866b65 100644 --- a/client/ui/frontend/WAILS-API.md +++ b/client/ui/frontend/WAILS-API.md @@ -110,7 +110,7 @@ Settings.SetConfig(p: SetConfigParams): Promise // partial update Settings.GetFeatures(): Promise // operator-disabled UI sections ``` -`SetConfig` is a partial update: only fields you set are pushed to the daemon. `profileName` + `username` are always required; the typed fields in `SetConfigParams` are optional (`field?: T | null`). `managementUrl` and `adminUrl` are always-string for historical reasons. +`SetConfig` is a partial update: only fields you set are pushed to the daemon. `profileName` + `username` are always required; the typed fields in `SetConfigParams` are optional (`field?: T | null`). `managementUrl` is always-string for historical reasons. **PSK mask quirk:** `GetConfig` returns existing pre-shared keys as `"**********"`. If you send the mask back, `wgtypes.ParseKey` fails on the next connect. `SettingsContext.save` drops the field when it equals `"**********"`. See `modules/settings/SettingsContext.tsx`. @@ -242,7 +242,7 @@ The tray also reads a tray-only synthetic `"Error"` for icon purposes; the front `Config` (read-only mirror, all required): ```ts -{ managementUrl, adminUrl, configFile, logFile, preSharedKey, interfaceName: string; +{ managementUrl, configFile, logFile, preSharedKey, interfaceName: string; wireguardPort, mtu, sshJwtCacheTtl: number; disableAutoConnect, serverSshAllowed, rosenpassEnabled, rosenpassPermissive, @@ -254,7 +254,7 @@ The tray also reads a tray-only synthetic `"Error"` for icon purposes; the front disableSshAuth: boolean; } ``` -`SetConfigParams` has all `Config` fields as `field?: T | null` (partial update), plus the write-only `disableFirewall?: boolean | null`, plus `profileName` / `username` / `managementUrl` / `adminUrl` as required strings. +`SetConfigParams` has all `Config` fields as `field?: T | null` (partial update), plus the write-only `disableFirewall?: boolean | null`, plus `profileName` / `username` / `managementUrl` as required strings. `Features`: `{ disableProfiles, disableUpdateSettings, disableNetworks: boolean }`. diff --git a/client/ui/services/settings.go b/client/ui/services/settings.go index 7c20184bd..c3628fbdf 100644 --- a/client/ui/services/settings.go +++ b/client/ui/services/settings.go @@ -51,7 +51,6 @@ type ConfigParams struct { type Config struct { ManagementURL string `json:"managementUrl"` - AdminURL string `json:"adminUrl"` ConfigFile string `json:"configFile"` LogFile string `json:"logFile"` PreSharedKeySet bool `json:"preSharedKeySet"` @@ -84,7 +83,6 @@ type SetConfigParams struct { ProfileName string `json:"profileName"` Username string `json:"username"` ManagementURL string `json:"managementUrl"` - AdminURL string `json:"adminUrl"` InterfaceName *string `json:"interfaceName,omitempty"` WireguardPort *int64 `json:"wireguardPort,omitempty"` MTU *int64 `json:"mtu,omitempty"` @@ -144,7 +142,6 @@ func (s *Settings) GetConfig(ctx context.Context, p ConfigParams) (Config, error } return Config{ ManagementURL: resp.GetManagementUrl(), - AdminURL: resp.GetAdminURL(), ConfigFile: resp.GetConfigFile(), LogFile: resp.GetLogFile(), PreSharedKeySet: resp.GetPreSharedKey() != "", @@ -181,7 +178,6 @@ func (s *Settings) SetConfig(ctx context.Context, p SetConfigParams) (SaveOutcom ProfileName: p.ProfileName, Username: p.Username, ManagementUrl: p.ManagementURL, - AdminURL: p.AdminURL, InterfaceName: p.InterfaceName, WireguardPort: p.WireguardPort, Mtu: p.MTU, From 569b9aa169c01ddb89885f188811da2f21f085d0 Mon Sep 17 00:00:00 2001 From: Maycon Santos Date: Tue, 20 Oct 2026 14:21:05 +0200 Subject: [PATCH 14/15] [misc] Let suites outside the module reach the e2e harness network (#8260) The harness hands peers the management address netbird.local:8080, which only resolves on the deployment's own Docker network, and keeps that network, the client image and the client container private. A suite that runs agents somewhere else, such as the Kubernetes operator's Kind cluster, has no way to attach to the deployment, run the same client build, or check routed access from a harness peer. Expose the network name, resolve the client image on its own, and let a caller exec into a client container. --- e2e/harness/client.go | 34 +++++++++++++++++++++++++++++----- e2e/harness/combined.go | 8 ++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/e2e/harness/client.go b/e2e/harness/client.go index 9843c25b2..da27d3bc5 100644 --- a/e2e/harness/client.go +++ b/e2e/harness/client.go @@ -65,11 +65,7 @@ func StartClient(ctx context.Context, c *Combined, setupKey string, opts ...Clie opt(&o) } - root, err := repoRoot(ctx) - if err != nil { - return nil, err - } - clientImage, err := resolveImage(ctx, root, "NB_E2E_CLIENT_IMAGE", defaultClientImage, clientDockerfile) + clientImage, err := ClientImage(ctx) if err != nil { return nil, err } @@ -105,6 +101,34 @@ func StartClient(ctx context.Context, c *Combined, setupKey string, opts ...Clie return &Client{container: ctr, name: o.name}, nil } +// ClientImage returns the client image StartClient runs, building it from this +// module's source unless NB_E2E_CLIENT_IMAGE names a published one. A suite that +// runs the agent outside a harness container, such as in a Kubernetes cluster, +// uses it to get the same build. +func ClientImage(ctx context.Context) (string, error) { + root, err := repoRoot(ctx) + if err != nil { + return "", err + } + return resolveImage(ctx, root, "NB_E2E_CLIENT_IMAGE", defaultClientImage, clientDockerfile) +} + +// Exec runs a command inside the client container and returns its exit code and +// combined output. It reaches whatever the agent routes, so a suite can check +// access the request helpers here do not model, such as plain HTTP to a routed +// address. +func (cl *Client) Exec(ctx context.Context, cmd ...string) (int, string, error) { + code, reader, err := cl.container.Exec(ctx, cmd, tcexec.Multiplexed()) + if err != nil { + return 0, "", fmt.Errorf("exec %v: %w", cmd, err) + } + out, err := io.ReadAll(reader) + if err != nil { + return code, string(out), fmt.Errorf("read output of %v: %w", cmd, err) + } + return code, string(out), nil +} + // Hostname returns the container hostname the agent reports to management — // the name the registered peer appears under in the peers API. func (cl *Client) Hostname() string { diff --git a/e2e/harness/combined.go b/e2e/harness/combined.go index ea451e3ad..d08db8bf9 100644 --- a/e2e/harness/combined.go +++ b/e2e/harness/combined.go @@ -332,6 +332,14 @@ func (c *Combined) Restart(ctx context.Context) error { return nil } +// NetworkName returns the Docker network the deployment runs on. Peers reach +// management, signal and relay at the combined server's alias on this network +// only, so a suite running agents outside the harness, such as in a Kind +// cluster, attaches them here. +func (c *Combined) NetworkName() string { + return c.network.Name +} + // Logs returns the combined server container logs, for diagnostics. func (c *Combined) Logs(ctx context.Context) string { return containerLogs(ctx, c.container) From aa0f569677a687dac0c9fe7e329ac4229579a699 Mon Sep 17 00:00:00 2001 From: Bethuel Mmbaga Date: Tue, 20 Oct 2026 18:50:32 +0300 Subject: [PATCH 15/15] [management] Remove the MySQL store engine (#7914) --- .../workflows/check-license-dependencies.yml | 4 +- .github/workflows/golang-test-linux.yml | 8 +- .github/workflows/golang-test-windows.yml | 2 +- .../workflows/test-infrastructure-files.yml | 32 +- .goreleaser.yaml | 26 - combined/cmd/admin_config_test.go | 4 - combined/cmd/config.go | 2 +- combined/cmd/root.go | 9 +- combined/config.yaml.example | 4 +- .../modules/20-management-store.md | 8 +- go.mod | 2 - go.sum | 6 - infrastructure_files/configure.sh | 12 - infrastructure_files/docker-compose.yml.tmpl | 1 - .../docker-compose.yml.tmpl.traefik | 1 - infrastructure_files/migrate-to-enterprise.sh | 2 +- infrastructure_files/migrate.sh | 12 - .../agent_config_realstore_test.go | 2 +- .../internals/modules/agentnetwork/manager.go | 1 - .../agentnetwork/provider_redaction_test.go | 5 +- .../modules/agentnetwork/types/settings.go | 3 +- .../agentnetwork/types/usageoverview.go | 2 +- management/internals/shared/db/engine.go | 1 - management/internals/shared/db/open.go | 25 - management/internals/shared/db/open_test.go | 12 - management/internals/shared/db/transaction.go | 30 +- management/server/account.go | 1 - management/server/account_test.go | 2 +- management/server/management_proto_test.go | 4 - management/server/migration/migration.go | 54 +- .../migration/migration_agentnetwork.go | 20 +- management/server/migration/migration_test.go | 54 +- management/server/peer_test.go | 7 +- management/server/store/sql_store.go | 36 - management/server/store/sql_store_account.go | 6 +- .../server/store/sql_store_group_test.go | 5 - .../server/store/sql_store_idp_migration.go | 1 - management/server/store/sql_store_peer.go | 10 +- .../server/store/sql_store_pgx_parity_test.go | 2 +- management/server/store/sql_store_proxy.go | 6 +- .../server/store/sql_store_setup_key.go | 6 +- management/server/store/sql_store_test.go | 48 -- management/server/store/store.go | 307 +------- management/server/testutil/store.go | 64 +- management/server/testutil/store_ios.go | 6 - management/server/types/store.go | 2 +- .../management/client/rest/accounts_test.go | 2 +- tools/mysql-migrate/LICENSE | 661 ------------------ tools/mysql-migrate/copy.go | 357 ---------- tools/mysql-migrate/main.go | 242 ------- tools/mysql-migrate/main_test.go | 225 ------ 51 files changed, 103 insertions(+), 2241 deletions(-) delete mode 100644 management/internals/shared/db/open_test.go delete mode 100644 tools/mysql-migrate/LICENSE delete mode 100644 tools/mysql-migrate/copy.go delete mode 100644 tools/mysql-migrate/main.go delete mode 100644 tools/mysql-migrate/main_test.go diff --git a/.github/workflows/check-license-dependencies.yml b/.github/workflows/check-license-dependencies.yml index 27c59f8d6..81d293e4f 100644 --- a/.github/workflows/check-license-dependencies.yml +++ b/.github/workflows/check-license-dependencies.yml @@ -34,7 +34,7 @@ jobs: while IFS= read -r dir; do echo "=== Checking $dir ===" # Search for problematic imports, excluding test files - RESULTS=$(grep -r "github.com/netbirdio/netbird/\(management\|signal\|relay\|proxy\)" "$dir" --include="*.go" 2>/dev/null | grep -v "_test.go" | grep -v "test_" | grep -v "/test/" | grep -v "tools/idp-migrate/" | grep -v "tools/mysql-migrate/" || true) + RESULTS=$(grep -r "github.com/netbirdio/netbird/\(management\|signal\|relay\|proxy\)" "$dir" --include="*.go" 2>/dev/null | grep -v "_test.go" | grep -v "test_" | grep -v "/test/" | grep -v "tools/idp-migrate/" || true) if [ -n "$RESULTS" ]; then echo "❌ Found problematic dependencies:" echo "$RESULTS" @@ -93,7 +93,7 @@ jobs: IMPORTERS=$(go list -json -deps ./... 2>/dev/null | jq -r "select(.Imports[]? == \"$package\") | .ImportPath") # Check if any importer is NOT in management/signal/relay - BSD_IMPORTER=$(echo "$IMPORTERS" | grep -v "github.com/netbirdio/netbird/\(management\|signal\|relay\|proxy\|combined\|tools/idp-migrate\|tools/mysql-migrate\)" | head -1) + BSD_IMPORTER=$(echo "$IMPORTERS" | grep -v "github.com/netbirdio/netbird/\(management\|signal\|relay\|proxy\|combined\|tools/idp-migrate\)" | head -1) if [ -n "$BSD_IMPORTER" ]; then echo "❌ $package ($license) is imported by BSD-licensed code: $BSD_IMPORTER" diff --git a/.github/workflows/golang-test-linux.yml b/.github/workflows/golang-test-linux.yml index 880370ede..b3e4dd4f7 100644 --- a/.github/workflows/golang-test-linux.yml +++ b/.github/workflows/golang-test-linux.yml @@ -307,7 +307,7 @@ jobs: sh -c ' \ apk update; apk add --no-cache \ ca-certificates iptables ip6tables dbus dbus-dev libpcap-dev build-base; \ - go test -buildvcs=false -tags "devcert privileged" -v -timeout 10m -p 1 $(go list -e -buildvcs=false ./... | grep -v -e /management -e /signal -e /relay -e /proxy -e /combined -e /client/ui -e /upload-server -e /client/testutil/privileged -e tools/mysql-migrate) + go test -buildvcs=false -tags "devcert privileged" -v -timeout 10m -p 1 $(go list -e -buildvcs=false ./... | grep -v -e /management -e /signal -e /relay -e /proxy -e /combined -e /client/ui -e /upload-server -e /client/testutil/privileged) ' test_relay: @@ -498,7 +498,7 @@ jobs: fail-fast: false matrix: arch: ["amd64"] - store: ["sqlite", "postgres", "mysql"] + store: ["sqlite", "postgres"] runs-on: ubuntu-22.04 steps: - name: Checkout code @@ -547,10 +547,6 @@ jobs: DOCKER_TOKEN: ${{ secrets.DOCKER_TOKEN }} run: echo "$DOCKER_TOKEN" | sudo docker login --username "$DOCKER_USER" --password-stdin - - name: download mysql image - if: matrix.store == 'mysql' - run: docker pull mlsmaycon/warmed-mysql:8 - # The -json stream goes through tools/gotestsummary so the log shows one # line per test, the output of failed tests, the head of a timeout panic # with the still-running tests, and the slowest tests per package. diff --git a/.github/workflows/golang-test-windows.yml b/.github/workflows/golang-test-windows.yml index 49be3af58..ca300f7df 100644 --- a/.github/workflows/golang-test-windows.yml +++ b/.github/workflows/golang-test-windows.yml @@ -76,7 +76,7 @@ jobs: # resolve; the Where-Object pipeline then drops the broken package by # path. Without -e, go list aborts with empty stdout. run: | - $packages = go list -e ./... | Where-Object { $_ -notmatch '/management' } | Where-Object { $_ -notmatch '/relay' } | Where-Object { $_ -notmatch '/signal' } | Where-Object { $_ -notmatch '/proxy' } | Where-Object { $_ -notmatch '/combined' } | Where-Object { $_ -notmatch '/client/ui$' } | Where-Object { $_ -notmatch '/tools/mysql-migrate' } + $packages = go list -e ./... | Where-Object { $_ -notmatch '/management' } | Where-Object { $_ -notmatch '/relay' } | Where-Object { $_ -notmatch '/signal' } | Where-Object { $_ -notmatch '/proxy' } | Where-Object { $_ -notmatch '/combined' } | Where-Object { $_ -notmatch '/client/ui$' } $goExe = "C:\hostedtoolcache\windows\go\${{ steps.go.outputs.go-version }}\x64\bin\go.exe" $cmd = "$goExe test -tags `"devcert privileged`" -timeout 10m -p 1 $($packages -join ' ') > test-out.txt 2>&1" Set-Content -Path "${{ github.workspace }}\run-tests.cmd" -Value $cmd diff --git a/.github/workflows/test-infrastructure-files.yml b/.github/workflows/test-infrastructure-files.yml index 4875adc31..68cf1b639 100644 --- a/.github/workflows/test-infrastructure-files.yml +++ b/.github/workflows/test-infrastructure-files.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - store: ["sqlite", "postgres", "mysql"] + store: ["sqlite", "postgres"] services: postgres: image: ${{ (matrix.store == 'postgres') && 'postgres' || '' }} @@ -35,19 +35,6 @@ jobs: --health-timeout 5s ports: - 5432:5432 - mysql: - image: ${{ (matrix.store == 'mysql') && 'mysql' || '' }} - env: - MYSQL_USER: netbird - MYSQL_PASSWORD: mysql - MYSQL_ROOT_PASSWORD: mysqlroot - MYSQL_DATABASE: netbird - options: >- - --health-cmd "mysqladmin ping --silent" - --health-interval 10s - --health-timeout 5s - ports: - - 3306:3306 steps: - name: Set Database Connection String run: | @@ -56,11 +43,6 @@ jobs: else echo "NETBIRD_STORE_ENGINE_POSTGRES_DSN==" >> $GITHUB_ENV fi - if [ "${{ matrix.store }}" == "mysql" ]; then - echo "NETBIRD_STORE_ENGINE_MYSQL_DSN=netbird:mysql@tcp($(hostname -I | awk '{print $1}'):3306)/netbird" >> $GITHUB_ENV - else - echo "NETBIRD_STORE_ENGINE_MYSQL_DSN==" >> $GITHUB_ENV - fi - name: Install jq run: sudo apt-get install -y jq @@ -86,15 +68,6 @@ jobs: restore-keys: | ${{ runner.os }}-go- - - name: Setup MySQL privileges - if: matrix.store == 'mysql' - run: | - sleep 10 - mysql -h 127.0.0.1 -u root -pmysqlroot -e " - GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO 'netbird'@'%'; - FLUSH PRIVILEGES; - " - - name: cp setup.env run: cp infrastructure_files/tests/setup.env infrastructure_files/ @@ -114,7 +87,6 @@ jobs: CI_NETBIRD_AUTH_SUPPORTED_SCOPES: "openid profile email offline_access api email_verified" CI_NETBIRD_STORE_CONFIG_ENGINE: ${{ matrix.store }} NETBIRD_STORE_ENGINE_POSTGRES_DSN: ${{ env.NETBIRD_STORE_ENGINE_POSTGRES_DSN }} - NETBIRD_STORE_ENGINE_MYSQL_DSN: ${{ env.NETBIRD_STORE_ENGINE_MYSQL_DSN }} CI_NETBIRD_MGMT_IDP_SIGNKEY_REFRESH: false - name: check values @@ -143,7 +115,6 @@ jobs: CI_NETBIRD_SIGNAL_PORT: 12345 CI_NETBIRD_STORE_CONFIG_ENGINE: ${{ matrix.store }} NETBIRD_STORE_ENGINE_POSTGRES_DSN: "${{ env.NETBIRD_STORE_ENGINE_POSTGRES_DSN }}$" - NETBIRD_STORE_ENGINE_MYSQL_DSN: "${{ env.NETBIRD_STORE_ENGINE_MYSQL_DSN }}$" CI_NETBIRD_MGMT_IDP_SIGNKEY_REFRESH: false CI_NETBIRD_TURN_EXTERNAL_IP: "1.2.3.4" CI_NETBIRD_MGMT_DISABLE_DEFAULT_POLICY: false @@ -182,7 +153,6 @@ jobs: grep -A 10 PKCEAuthorizationFlow management.json | grep -A 10 ProviderConfig | grep Scope | grep "$CI_NETBIRD_AUTH_SUPPORTED_SCOPES" grep -A 10 PKCEAuthorizationFlow management.json | grep -A 10 ProviderConfig | grep -A 3 RedirectURLs | grep "http://localhost:53000" grep "external-ip" turnserver.conf | grep $CI_NETBIRD_TURN_EXTERNAL_IP - grep "NETBIRD_STORE_ENGINE_MYSQL_DSN=$NETBIRD_STORE_ENGINE_MYSQL_DSN" docker-compose.yml grep NETBIRD_STORE_ENGINE_POSTGRES_DSN docker-compose.yml | egrep "$NETBIRD_STORE_ENGINE_POSTGRES_DSN" # check relay values grep "NB_EXPOSED_ADDRESS=rels://$CI_NETBIRD_DOMAIN:33445" docker-compose.yml diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 41c330a64..62b64717e 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -280,28 +280,6 @@ builds: - -s -w -X github.com/netbirdio/netbird/version.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.CommitDate}} -X main.builtBy=goreleaser mod_timestamp: "{{ .CommitTimestamp }}" - - id: netbird-mysql-migrate - dir: tools/mysql-migrate - env: - - CGO_ENABLED=1 - - >- - {{- if eq .Runtime.Goos "linux" }} - {{- if eq .Arch "arm64"}}CC=aarch64-linux-gnu-gcc{{- end }} - {{- if eq .Arch "arm"}}CC=arm-linux-gnueabihf-gcc{{- end }} - {{- end }} - binary: netbird-mysql-migrate - goos: - - linux - goarch: - - amd64 - - arm64 - - arm - goarm: - - 7 - ldflags: - - -s -w -X github.com/netbirdio/netbird/version.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.CommitDate}} -X main.builtBy=goreleaser - mod_timestamp: "{{ .CommitTimestamp }}" - universal_binaries: - id: netbird @@ -318,10 +296,6 @@ archives: builds: - netbird-idp-migrate name_template: "netbird-idp-migrate_{{ .Version }}_{{ .Os }}_{{ .Arch }}" - - id: netbird-mysql-migrate - builds: - - netbird-mysql-migrate - name_template: "netbird-mysql-migrate_{{ .Version }}_{{ .Os }}_{{ .Arch }}" - id: nblink builds: - nblink diff --git a/combined/cmd/admin_config_test.go b/combined/cmd/admin_config_test.go index ff7045d38..5cec26552 100644 --- a/combined/cmd/admin_config_test.go +++ b/combined/cmd/admin_config_test.go @@ -35,13 +35,9 @@ func TestOpenAdminEventStoreMissingEncryptionKeyReturnsNilInterface(t *testing.T func TestApplyServerStoreEnv(t *testing.T) { t.Setenv("NB_STORE_ENGINE_POSTGRES_DSN", "") - t.Setenv("NB_STORE_ENGINE_MYSQL_DSN", "") t.Setenv("NB_STORE_ENGINE_SQLITE_FILE", "") applyServerStoreEnv(StoreConfig{Engine: "postgres", DSN: "postgres-dsn", File: "store.db"}) require.Equal(t, "postgres-dsn", os.Getenv("NB_STORE_ENGINE_POSTGRES_DSN")) require.Equal(t, "store.db", os.Getenv("NB_STORE_ENGINE_SQLITE_FILE")) - - applyServerStoreEnv(StoreConfig{Engine: "mysql", DSN: "mysql-dsn"}) - require.Equal(t, "mysql-dsn", os.Getenv("NB_STORE_ENGINE_MYSQL_DSN")) } diff --git a/combined/cmd/config.go b/combined/cmd/config.go index 890c86876..ca3b25617 100644 --- a/combined/cmd/config.go +++ b/combined/cmd/config.go @@ -188,7 +188,7 @@ type RelaysConfig struct { type StoreConfig struct { Engine string `yaml:"engine"` EncryptionKey string `yaml:"encryptionKey"` - DSN string `yaml:"dsn"` // Connection string for postgres or mysql engines + DSN string `yaml:"dsn"` // Connection string for the postgres engine File string `yaml:"file"` // SQLite database file path (optional, defaults to dataDir) } diff --git a/combined/cmd/root.go b/combined/cmd/root.go index fa65f7b6d..fedb0e1cc 100644 --- a/combined/cmd/root.go +++ b/combined/cmd/root.go @@ -127,13 +127,8 @@ func execute(cmd *cobra.Command, _ []string) error { // initializeConfig loads and validates the configuration, then initializes logging. func applyServerStoreEnv(storeConfig StoreConfig) { - if dsn := storeConfig.DSN; dsn != "" { - switch strings.ToLower(storeConfig.Engine) { - case "postgres": - os.Setenv("NB_STORE_ENGINE_POSTGRES_DSN", dsn) - case "mysql": - os.Setenv("NB_STORE_ENGINE_MYSQL_DSN", dsn) - } + if dsn := storeConfig.DSN; dsn != "" && strings.EqualFold(storeConfig.Engine, "postgres") { + os.Setenv("NB_STORE_ENGINE_POSTGRES_DSN", dsn) } if file := storeConfig.File; file != "" { os.Setenv("NB_STORE_ENGINE_SQLITE_FILE", file) diff --git a/combined/config.yaml.example b/combined/config.yaml.example index 085e4344f..68dbf701e 100644 --- a/combined/config.yaml.example +++ b/combined/config.yaml.example @@ -110,8 +110,8 @@ server: # Store configuration store: - engine: "sqlite" # sqlite, postgres, or mysql - dsn: "" # Connection string for postgres or mysql + engine: "sqlite" # sqlite or postgres + dsn: "" # Connection string for postgres encryptionKey: "" # file: "" # Custom SQLite file path (optional, defaults to {dataDir}/store.db) diff --git a/docs/agent-networks/modules/20-management-store.md b/docs/agent-networks/modules/20-management-store.md index 1acc12611..658b1fb4f 100644 --- a/docs/agent-networks/modules/20-management-store.md +++ b/docs/agent-networks/modules/20-management-store.md @@ -64,17 +64,17 @@ Reads decrypt provider secrets in-place; writes do `provider.Copy().EncryptSensi ### Correctness - `SaveAgentNetworkProvider` saves the copy (sql_store_agentnetwork.go:95). The caller's in-memory pointer therefore keeps plaintext `api_key` and any `CreatedAt`/`UpdatedAt` gorm autofills land on the copy, not the original. Callers that need synced timestamps must re-fetch. -- `IncrementAgentNetworkConsumption`'s `Create` provides initial counter values (`TokensInput: tokensIn`, etc.) in the row, and on conflict the assignments add the same deltas to the existing values. The insert-vs-update arithmetic is consistent. Cross-check that no engine in use (sqlite, postgres, mysql) silently rejects the `OnConflict` clause — GORM emits engine-specific SQL but `ON DUPLICATE KEY UPDATE` (mysql) vs `ON CONFLICT (...)` (sqlite/postgres) need their unique constraint to match the composite PK on `agent_network_consumption`; it does, by construction. +- `IncrementAgentNetworkConsumption`'s `Create` provides initial counter values (`TokensInput: tokensIn`, etc.) in the row, and on conflict the assignments add the same deltas to the existing values. The insert-vs-update arithmetic is consistent. Cross-check that no engine in use (sqlite, postgres) silently rejects the `OnConflict` clause — GORM emits `ON CONFLICT (...)`, which needs its unique constraint to match the composite PK on `agent_network_consumption`; it does, by construction. - `IncrementAgentNetworkConsumption` writes `updated_at: time.Now().UTC()` literally inside the assignments map (sql_store_agentnetwork.go:333) — fine, but it's a Go-side timestamp captured at call time, not a DB-side `now()`. Acceptable for an audit field. - `GetAgentNetworkConsumption` returns a zero-valued non-nil row on `ErrRecordNotFound` (sql_store_agentnetwork.go:364-371). Document or rename — a typed sentinel error would be more orthodox; callers must know not to error-check. ### Concurrency / transactions -- Hot-path `IncrementAgentNetworkConsumption` runs outside any explicit transaction; concurrency safety relies entirely on the DB serialising the `ON CONFLICT` upsert against the composite PK. This is correct for postgres and mysql; for sqlite it serialises behind the single writer. +- Hot-path `IncrementAgentNetworkConsumption` runs outside any explicit transaction; concurrency safety relies entirely on the DB serialising the `ON CONFLICT` upsert against the composite PK. This is correct for postgres; for sqlite it serialises behind the single writer. - `SaveAgentNetworkSettings` is a blind upsert with no version/etag — concurrent writes from two operators last-write-wins on the collection-toggle flags (settings.go:23-25). Acceptable for admin-curated state but worth flagging. - `Save*Provider` uses `db.Save` on a struct with a PK already set — GORM emits UPDATE or INSERT based on row existence. No upsert clause is attached, so a race between two creates with the same generated `xid` (vanishingly unlikely) would surface as a PK violation. ### Migration safety -- All six tables ride `AutoMigrate` (sql_store.go:141-142). AutoMigrate is additive: new columns get added, but it never drops columns nor narrows types. Three `bool` columns on `agent_network_settings` (`EnableLogCollection`, `EnablePromptCollection`, `RedactPii`) default to false at the GORM/DDL layer for existing rows; the test at sql_store_agentnetwork_budgetrule_test.go:83-112 locks that down on a fresh sqlite. Verify postgres/mysql produce the same default. +- All six tables ride `AutoMigrate` (sql_store.go:141-142). AutoMigrate is additive: new columns get added, but it never drops columns nor narrows types. Three `bool` columns on `agent_network_settings` (`EnableLogCollection`, `EnablePromptCollection`, `RedactPii`) default to false at the GORM/DDL layer for existing rows; the test at sql_store_agentnetwork_budgetrule_test.go:83-112 locks that down on a fresh sqlite. Verify postgres produces the same default. - The named index `idx_agent_network_settings_cluster_subdomain` on settings.go:15 is declared on only `subdomain`. Either the cluster column also needs `gorm:"index:idx_agent_network_settings_cluster_subdomain"` to make it composite, or the name is misleading. - The named index `idx_agent_network_provider` on `Provider.ProviderID` (provider.go:30) is *not* unique and not scoped to account — two providers in the same account with the same `provider_id` are permitted at the DB layer; uniqueness, if any, must live above the store. @@ -101,7 +101,7 @@ Gap: there is no store-level test for providers (encryption round-trip), policie - No retention / GC for `agent_network_consumption`. - No `Delete` for `Settings` (one row per account, cleared with the account). -- No DB-engine-specific tuning — the same struct tags drive sqlite, mysql, postgres. +- No DB-engine-specific tuning — the same struct tags drive sqlite and postgres. - Provider `extra_values` and `models` are JSON blobs; querying inside them is not supported by design. - `GetAgentNetworkConsumption` "not-found = zero row" contract is convenient but unconventional. diff --git a/go.mod b/go.mod index bc8e5e287..beb612a72 100644 --- a/go.mod +++ b/go.mod @@ -113,7 +113,6 @@ require ( github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8 github.com/stretchr/testify v1.12.1 github.com/testcontainers/testcontainers-go v0.37.0 - github.com/testcontainers/testcontainers-go/modules/mysql v0.37.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.37.0 github.com/testcontainers/testcontainers-go/modules/redis v0.37.0 github.com/things-go/go-socks5 v0.0.4 @@ -142,7 +141,6 @@ require ( google.golang.org/api v0.276.0 google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 gopkg.in/yaml.v3 v3.0.1 - gorm.io/driver/mysql v1.5.7 gorm.io/driver/postgres v1.5.7 gorm.io/driver/sqlite v1.5.7 gorm.io/gorm v1.25.12 diff --git a/go.sum b/go.sum index 9af59daf5..82e2daf78 100644 --- a/go.sum +++ b/go.sum @@ -252,7 +252,6 @@ github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3yg github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6 h1:teYtXy9B7y5lHTp8V9KPxpYRAVA7dozigQcMiBust1s= github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= -github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= @@ -721,8 +720,6 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8 github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/testcontainers/testcontainers-go v0.37.0 h1:L2Qc0vkTw2EHWQ08djon0D2uw7Z/PtHS/QzZZ5Ra/hg= github.com/testcontainers/testcontainers-go v0.37.0/go.mod h1:QPzbxZhQ6Bclip9igjLFj6z0hs01bU8lrl2dHQmgFGM= -github.com/testcontainers/testcontainers-go/modules/mysql v0.37.0 h1:LqUos1oR5iuuzorFnSvxsHNdYdCHB/DfI82CuT58wbI= -github.com/testcontainers/testcontainers-go/modules/mysql v0.37.0/go.mod h1:vHEEHx5Kf+uq5hveaVAMrTzPY8eeRZcKcl23MRw5Tkc= github.com/testcontainers/testcontainers-go/modules/postgres v0.37.0 h1:hsVwFkS6s+79MbKEO+W7A1wNIw1fmkMtF4fg83m6kbc= github.com/testcontainers/testcontainers-go/modules/postgres v0.37.0/go.mod h1:Qj/eGbRbO/rEYdcRLmN+bEojzatP/+NS1y8ojl2PQsc= github.com/testcontainers/testcontainers-go/modules/redis v0.37.0 h1:9HIY28I9ME/Zmb+zey1p/I1mto5+5ch0wLX+nJdOsQ4= @@ -1025,13 +1022,10 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo= -gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM= gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM= gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA= gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I= gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4= -gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8= gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= diff --git a/infrastructure_files/configure.sh b/infrastructure_files/configure.sh index ce1a041e6..2d9fe5ee8 100755 --- a/infrastructure_files/configure.sh +++ b/infrastructure_files/configure.sh @@ -53,18 +53,6 @@ if [[ "$NETBIRD_STORE_CONFIG_ENGINE" == "postgres" ]]; then export NETBIRD_STORE_ENGINE_POSTGRES_DSN fi -# Check if MySQL is set as the store engine -if [[ "$NETBIRD_STORE_CONFIG_ENGINE" == "mysql" ]]; then - # Exit if 'NETBIRD_STORE_ENGINE_MYSQL_DSN' is not set - if [[ -z "$NETBIRD_STORE_ENGINE_MYSQL_DSN" ]]; then - echo "Warning: NETBIRD_STORE_CONFIG_ENGINE=mysql but NETBIRD_STORE_ENGINE_MYSQL_DSN is not set." - echo "Please add the following line to your setup.env file:" - echo 'NETBIRD_STORE_ENGINE_MYSQL_DSN=":@tcp(127.0.0.1:3306)/"' - exit 1 - fi - export NETBIRD_STORE_ENGINE_MYSQL_DSN -fi - # local development or tests if [[ $NETBIRD_DOMAIN == "localhost" || $NETBIRD_DOMAIN == "127.0.0.1" ]]; then export NETBIRD_MGMT_SINGLE_ACCOUNT_MODE_DOMAIN="netbird.selfhosted" diff --git a/infrastructure_files/docker-compose.yml.tmpl b/infrastructure_files/docker-compose.yml.tmpl index 1c9c63f78..0ffb20a72 100644 --- a/infrastructure_files/docker-compose.yml.tmpl +++ b/infrastructure_files/docker-compose.yml.tmpl @@ -94,7 +94,6 @@ services: ] environment: - NETBIRD_STORE_ENGINE_POSTGRES_DSN=$NETBIRD_STORE_ENGINE_POSTGRES_DSN - - NETBIRD_STORE_ENGINE_MYSQL_DSN=$NETBIRD_STORE_ENGINE_MYSQL_DSN # Coturn coturn: diff --git a/infrastructure_files/docker-compose.yml.tmpl.traefik b/infrastructure_files/docker-compose.yml.tmpl.traefik index 0010974c5..7fcf1cdde 100644 --- a/infrastructure_files/docker-compose.yml.tmpl.traefik +++ b/infrastructure_files/docker-compose.yml.tmpl.traefik @@ -100,7 +100,6 @@ services: - traefik.http.services.netbird-management.loadbalancer.server.scheme=h2c environment: - NETBIRD_STORE_ENGINE_POSTGRES_DSN=$NETBIRD_STORE_ENGINE_POSTGRES_DSN - - NETBIRD_STORE_ENGINE_MYSQL_DSN=$NETBIRD_STORE_ENGINE_MYSQL_DSN # Coturn coturn: diff --git a/infrastructure_files/migrate-to-enterprise.sh b/infrastructure_files/migrate-to-enterprise.sh index 8abde2f68..5b2cc2f79 100755 --- a/infrastructure_files/migrate-to-enterprise.sh +++ b/infrastructure_files/migrate-to-enterprise.sh @@ -855,7 +855,7 @@ configure_sqlite_store() { POSTGRES_DSN="host=postgres user=netbird password=${POSTGRES_PASSWORD} dbname=netbird port=5432 sslmode=disable" } -# mysql, or something this script has never seen. Swapping the images is still +# An engine this script has never seen. Swapping the images is still # valid; touching the store is not. configure_unsupported_store() { MIGRATE_POSTGRES="no" diff --git a/infrastructure_files/migrate.sh b/infrastructure_files/migrate.sh index 46971a57a..2b018ab54 100755 --- a/infrastructure_files/migrate.sh +++ b/infrastructure_files/migrate.sh @@ -472,12 +472,6 @@ detect_store_config() { if [[ -n "$pg_dsn" ]]; then STORE_DSN="$pg_dsn" fi - - local mysql_dsn - mysql_dsn=$(grep '^NETBIRD_STORE_ENGINE_MYSQL_DSN=' "$INSTALL_DIR/setup.env" 2>/dev/null | sed 's/^NETBIRD_STORE_ENGINE_MYSQL_DSN=//' | tr -d '"' || echo "") - if [[ -n "$mysql_dsn" ]]; then - STORE_DSN="$mysql_dsn" - fi fi # Also check base.setup.env @@ -487,12 +481,6 @@ detect_store_config() { if [[ -n "$pg_dsn" ]]; then STORE_DSN="$pg_dsn" fi - - local mysql_dsn - mysql_dsn=$(grep '^NETBIRD_STORE_ENGINE_MYSQL_DSN=' "$INSTALL_DIR/base.setup.env" 2>/dev/null | sed 's/^NETBIRD_STORE_ENGINE_MYSQL_DSN=//' | tr -d '"' || echo "") - if [[ -n "$mysql_dsn" ]]; then - STORE_DSN="$mysql_dsn" - fi fi log_success "Store engine: $STORE_ENGINE" diff --git a/management/internals/modules/agentnetwork/agent_config_realstore_test.go b/management/internals/modules/agentnetwork/agent_config_realstore_test.go index 2fd541fad..e69cec59a 100644 --- a/management/internals/modules/agentnetwork/agent_config_realstore_test.go +++ b/management/internals/modules/agentnetwork/agent_config_realstore_test.go @@ -341,7 +341,7 @@ func TestGetAgentConfigForUser_RealStore(t *testing.T) { require.NoError(t, s.SaveAgentNetworkPolicy(ctx, newSynthTestPolicy(provider.ID, "grp-eng", ""))) // users.account_id is a foreign key into accounts, enforced on - // MySQL/Postgres, so the account row must exist before its users. + // Postgres, so the account row must exist before its users. require.NoError(t, s.SaveAccount(ctx, &nbtypes.Account{Id: testAccountID})) require.NoError(t, s.SaveUser(ctx, &nbtypes.User{ Id: "user-in", AccountID: testAccountID, Role: nbtypes.UserRoleUser, AutoGroups: []string{"grp-eng"}, diff --git a/management/internals/modules/agentnetwork/manager.go b/management/internals/modules/agentnetwork/manager.go index 71ff53214..69ae4b432 100644 --- a/management/internals/modules/agentnetwork/manager.go +++ b/management/internals/modules/agentnetwork/manager.go @@ -1277,7 +1277,6 @@ func isUniqueConstraintError(err error) bool { } msg := err.Error() return strings.Contains(msg, "(SQLSTATE 23505)") || // postgres - strings.Contains(msg, "Error 1062 (23000)") || // mysql strings.Contains(msg, "UNIQUE constraint failed") // sqlite } diff --git a/management/internals/modules/agentnetwork/provider_redaction_test.go b/management/internals/modules/agentnetwork/provider_redaction_test.go index d6a749fb9..1503f4121 100644 --- a/management/internals/modules/agentnetwork/provider_redaction_test.go +++ b/management/internals/modules/agentnetwork/provider_redaction_test.go @@ -98,9 +98,8 @@ func TestGetProvider_RedactsForReadOnlyViewer(t *testing.T) { // keeps the account-wide view with full config. // newSelfScopeStore seeds the account and its users only, so each test -// declares exactly the providers and policies it asserts on — the store -// rejects re-saving a policy id on MySQL, so tests never overwrite each -// other's rows. +// declares exactly the providers and policies it asserts on, so tests never +// overwrite each other's rows. func newSelfScopeStore(t *testing.T) (*managerImpl, store.Store) { t.Helper() mgr, s := newAgentConfigTestMgr(t) diff --git a/management/internals/modules/agentnetwork/types/settings.go b/management/internals/modules/agentnetwork/types/settings.go index 70ecc5f70..6a28e6a5c 100644 --- a/management/internals/modules/agentnetwork/types/settings.go +++ b/management/internals/modules/agentnetwork/types/settings.go @@ -21,8 +21,7 @@ type Settings struct { AccountID string `gorm:"primaryKey"` // Domain is the gateway endpoint hostname agents call. Globally unique - // across accounts. Sized explicitly because MySQL cannot index an - // unbounded TEXT column; 255 covers the RFC 1035 253-octet bound. + // across accounts. 255 covers the RFC 1035 253-octet bound. Domain string `gorm:"type:varchar(255);uniqueIndex:idx_agent_network_settings_domain"` // ProxyAddress is the declared cluster address of the proxy serving this diff --git a/management/internals/modules/agentnetwork/types/usageoverview.go b/management/internals/modules/agentnetwork/types/usageoverview.go index 81e02c6b8..d46aec9c5 100644 --- a/management/internals/modules/agentnetwork/types/usageoverview.go +++ b/management/internals/modules/agentnetwork/types/usageoverview.go @@ -95,7 +95,7 @@ func bucketStart(t time.Time, g UsageGranularity) time.Time { // AggregateUsageByGranularity buckets the usage rows by the requested // granularity and returns the buckets ordered oldest-first. Aggregation is done // in Go (rather than per-engine SQL date_trunc) so granularities stay portable -// across SQLite/Postgres/MySQL and easy to extend. +// across SQLite and Postgres and easy to extend. func AggregateUsageByGranularity(rows []*AgentNetworkUsage, g UsageGranularity) []*AgentNetworkUsageBucket { byPeriod := make(map[string]*AgentNetworkUsageBucket) for _, r := range rows { diff --git a/management/internals/shared/db/engine.go b/management/internals/shared/db/engine.go index 02a3f5570..6cf03e239 100644 --- a/management/internals/shared/db/engine.go +++ b/management/internals/shared/db/engine.go @@ -6,5 +6,4 @@ type Engine string const ( SqliteStoreEngine Engine = "sqlite" PostgresStoreEngine Engine = "postgres" - MysqlStoreEngine Engine = "mysql" ) diff --git a/management/internals/shared/db/open.go b/management/internals/shared/db/open.go index 48a7bf330..c573e8c08 100644 --- a/management/internals/shared/db/open.go +++ b/management/internals/shared/db/open.go @@ -11,7 +11,6 @@ import ( "time" "github.com/jackc/pgx/v5/pgxpool" - "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" @@ -121,30 +120,6 @@ func OpenPostgres(ctx context.Context, dsn string, pool PoolConfig) (*Conn, erro return conn, nil } -// MysqlDSN adds the connection parameters every MySQL handle needs, keeping -// the options already present in dsn. -func MysqlDSN(dsn string) string { - separator := "?" - if strings.Contains(dsn, "?") { - separator = "&" - } - return dsn + separator + "charset=utf8&parseTime=True&loc=Local" -} - -// OpenMysql opens a MySQL database through gorm. -func OpenMysql(ctx context.Context, dsn string) (*Conn, error) { - gormDB, err := gorm.Open(mysql.Open(MysqlDSN(dsn)), GormConfig()) - if err != nil { - return nil, err - } - conn, err := NewConn(ctx, gormDB, MysqlStoreEngine, nil) - if err != nil { - closeGorm(gormDB) - return nil, err - } - return conn, nil -} - func newPgxPool(ctx context.Context, dsn string, cfg PoolConfig) (*pgxpool.Pool, error) { config, err := pgxpool.ParseConfig(dsn) if err != nil { diff --git a/management/internals/shared/db/open_test.go b/management/internals/shared/db/open_test.go deleted file mode 100644 index e6b506b78..000000000 --- a/management/internals/shared/db/open_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package db - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestMysqlDSN(t *testing.T) { - assert.Equal(t, "user:pw@tcp(host:3306)/db?charset=utf8&parseTime=True&loc=Local", MysqlDSN("user:pw@tcp(host:3306)/db")) - assert.Equal(t, "user:pw@tcp(host:3306)/db?tls=true&charset=utf8&parseTime=True&loc=Local", MysqlDSN("user:pw@tcp(host:3306)/db?tls=true")) -} diff --git a/management/internals/shared/db/transaction.go b/management/internals/shared/db/transaction.go index 9699aaee6..3930033d5 100644 --- a/management/internals/shared/db/transaction.go +++ b/management/internals/shared/db/transaction.go @@ -39,10 +39,7 @@ func (c *Conn) RunInTx(ctx context.Context, fn func(tx *Tx) error) error { return err } - err := c.withForeignKeyChecksDisabled(tx, func() error { - return fn(&Tx{db: tx}) - }) - if err != nil { + if err := fn(&Tx{db: tx}); err != nil { tx.Rollback() c.logIfTimedOut(ctx, timeoutCtx, err, "transaction", startTime) return err @@ -73,31 +70,6 @@ func (c *Conn) applyStatementTimeouts(tx *gorm.DB) error { return nil } -// withForeignKeyChecksDisabled runs fn with MySQL's FK checks off, which avoids -// deadlocks on MySQL and Aurora without needing SUPER privilege. The setting is -// session-scoped and survives a rollback, so it is turned back on whenever fn -// returns or panics; otherwise the pooled connection would keep it disabled. -func (c *Conn) withForeignKeyChecksDisabled(tx *gorm.DB, fn func() error) (err error) { - if c.engine != MysqlStoreEngine { - return fn() - } - if err := tx.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil { - return fmt.Errorf("failed to disable FK checks: %w", err) - } - defer func() { - restoreErr := tx.Exec("SET FOREIGN_KEY_CHECKS = 1").Error - if restoreErr == nil { - return - } - if err == nil { - err = fmt.Errorf("failed to re-enable FK checks: %w", restoreErr) - return - } - log.WithContext(tx.Statement.Context).Warnf("failed to re-enable FK checks after failed transaction: %v", restoreErr) - }() - return fn() -} - func (c *Conn) logIfTimedOut(ctx, timeoutCtx context.Context, err error, phase string, startTime time.Time) { if errors.Is(err, context.DeadlineExceeded) || errors.Is(timeoutCtx.Err(), context.DeadlineExceeded) { log.WithContext(ctx).Warnf("%s exceeded %s timeout after %v, stack: %s", phase, c.txTimeout, time.Since(startTime), debug.Stack()) diff --git a/management/server/account.go b/management/server/account.go index 59991a4e4..68150a947 100644 --- a/management/server/account.go +++ b/management/server/account.go @@ -152,7 +152,6 @@ func (am *DefaultAccountManager) runAccountDeletionHooks(ctx context.Context, ac func isUniqueConstraintError(err error) bool { switch { case strings.Contains(err.Error(), "(SQLSTATE 23505)"), - strings.Contains(err.Error(), "Error 1062 (23000)"), strings.Contains(err.Error(), "UNIQUE constraint failed"): return true diff --git a/management/server/account_test.go b/management/server/account_test.go index ef7525961..8f7b1f18b 100644 --- a/management/server/account_test.go +++ b/management/server/account_test.go @@ -3759,7 +3759,7 @@ func setupNetworkMapTest(t *testing.T) (*DefaultAccountManager, *update_channel. // peerUpdateTimeout bounds how long peerShouldReceiveUpdate and its outer // wrappers wait for an expected update message. Sized for slow CI runners -// (MySQL, FreeBSD, loaded sqlite) where the channel publish can take +// (FreeBSD, loaded sqlite) where the channel publish can take // seconds. Only runs down on failure; passing tests return immediately // when the channel delivers. const peerUpdateTimeout = 5 * time.Second diff --git a/management/server/management_proto_test.go b/management/server/management_proto_test.go index 4e21ea7a3..9ca94d2e6 100644 --- a/management/server/management_proto_test.go +++ b/management/server/management_proto_test.go @@ -429,10 +429,6 @@ func Test_SyncStatusRace(t *testing.T) { if os.Getenv("NETBIRD_STORE_ENGINE") == "postgres" { t.Skip("Skipping on CI and Postgres store") } - - if os.Getenv("NETBIRD_STORE_ENGINE") == "mysql" { - t.Skip("Skipping on CI and MySQL store") - } } for i := 0; i < 500; i++ { t.Run(fmt.Sprintf("TestRun-%d", i), func(t *testing.T) { diff --git a/management/server/migration/migration.go b/management/server/migration/migration.go index 6d8ed90cc..239166c99 100644 --- a/management/server/migration/migration.go +++ b/management/server/migration/migration.go @@ -19,19 +19,11 @@ import ( "gorm.io/gorm/clause" ) -func GetColumnName(db *gorm.DB, column string) string { - if db.Name() == "mysql" { - return fmt.Sprintf("`%s`", column) - } - return column -} - // MigrateFieldFromGobToJSON migrates a column from Gob encoding to JSON encoding. // T is the type of the model that contains the field to be migrated. // S is the type of the field to be migrated. func MigrateFieldFromGobToJSON[T any, S any](ctx context.Context, db *gorm.DB, fieldName string) error { - orgColumnName := fieldName - oldColumnName := GetColumnName(db, orgColumnName) + oldColumnName := fieldName newColumnName := fieldName + "_tmp" var model T @@ -86,7 +78,7 @@ func MigrateFieldFromGobToJSON[T any, S any](ctx context.Context, db *gorm.DB, f for _, row := range rows { var field S - str, ok := row[orgColumnName].(string) + str, ok := row[oldColumnName].(string) if !ok { return fmt.Errorf("type assertion failed") } @@ -125,8 +117,7 @@ func MigrateFieldFromGobToJSON[T any, S any](ctx context.Context, db *gorm.DB, f // MigrateNetIPFieldFromBlobToJSON migrates a Net IP column from Blob encoding to JSON encoding. // T is the type of the model that contains the field to be migrated. func MigrateNetIPFieldFromBlobToJSON[T any](ctx context.Context, db *gorm.DB, fieldName string, indexName string) error { - orgColumnName := fieldName - oldColumnName := GetColumnName(db, orgColumnName) + oldColumnName := fieldName newColumnName := fieldName + "_tmp" var model T @@ -178,7 +169,7 @@ func MigrateNetIPFieldFromBlobToJSON[T any](ctx context.Context, db *gorm.DB, fi for _, row := range rows { var blobValue string - if columnValue := row[orgColumnName]; columnValue != nil { + if columnValue := row[oldColumnName]; columnValue != nil { value, ok := columnValue.(string) if !ok { return fmt.Errorf("type assertion failed") @@ -225,8 +216,7 @@ func MigrateNetIPFieldFromBlobToJSON[T any](ctx context.Context, db *gorm.DB, fi } func MigrateSetupKeyToHashedSetupKey[T any](ctx context.Context, db *gorm.DB) error { - orgColumnName := "key" - oldColumnName := GetColumnName(db, orgColumnName) + oldColumnName := "key" newColumnName := "key_secret" var model T @@ -268,7 +258,7 @@ func MigrateSetupKeyToHashedSetupKey[T any](ctx context.Context, db *gorm.DB) er for _, row := range rows { var plainKey string - if columnValue := row[orgColumnName]; columnValue != nil { + if columnValue := row[oldColumnName]; columnValue != nil { value, ok := columnValue.(string) if !ok { return fmt.Errorf("type assertion failed") @@ -394,33 +384,13 @@ func CreateIndexIfNotExists[T any](ctx context.Context, db *gorm.DB, indexName s return fmt.Errorf("failed to parse model schema: %w", err) } tableName := stmt.Schema.Table - dialect := db.Name() if db.Migrator().HasIndex(&model, indexName) { log.WithContext(ctx).Infof("index %s already exists on table %s", indexName, tableName) return nil } - var columnClause string - if dialect == "mysql" { - var withLength []string - for _, col := range columns { - quotedCol := fmt.Sprintf("`%s`", col) - if col == "ip" || col == "dns_label" || col == "key" { - withLength = append(withLength, fmt.Sprintf("%s(64)", quotedCol)) - } else { - withLength = append(withLength, quotedCol) - } - } - columnClause = strings.Join(withLength, ", ") - } else { - columnClause = strings.Join(columns, ", ") - } - - createStmt := fmt.Sprintf("CREATE UNIQUE INDEX %s ON %s (%s)", indexName, tableName, columnClause) - if dialect == "postgres" || dialect == "sqlite" { - createStmt = strings.Replace(createStmt, "CREATE UNIQUE INDEX", "CREATE UNIQUE INDEX IF NOT EXISTS", 1) - } + createStmt := fmt.Sprintf("CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s (%s)", indexName, tableName, strings.Join(columns, ", ")) log.WithContext(ctx).Infof("executing index creation: %s", createStmt) if err := db.Exec(createStmt).Error; err != nil { @@ -505,14 +475,6 @@ func hasForeignKey(db *gorm.DB, table, column string) bool { AND kcu.table_name = ? AND kcu.column_name = ? `, table, column).Scan(&count) - case "mysql": - db.Raw(` - SELECT COUNT(*) FROM information_schema.key_column_usage - WHERE table_schema = DATABASE() - AND table_name = ? - AND column_name = ? - AND referenced_table_name IS NOT NULL - `, table, column).Scan(&count) default: // sqlite type fkInfo struct { From string @@ -592,7 +554,7 @@ func RemoveDuplicatePeerKeys(ctx context.Context, db *gorm.DB) error { return nil } - keyColumn := GetColumnName(db, "key") + keyColumn := "key" var duplicates []struct { Key string diff --git a/management/server/migration/migration_agentnetwork.go b/management/server/migration/migration_agentnetwork.go index c6cda56c2..7e19c0298 100644 --- a/management/server/migration/migration_agentnetwork.go +++ b/management/server/migration/migration_agentnetwork.go @@ -33,15 +33,6 @@ func (agentNetworkSettingsMigration) TableName() string { return "agent_network_ // bootstrap always wrote both, so such a row indicates corruption and the // migration fails loudly rather than leaving an empty domain to collide with // the unique index confusingly. -// -// The transaction is real only on sqlite and postgres, where DDL is -// transactional. MySQL implicitly commits around every ALTER TABLE, so there -// each step stands alone; what makes an interrupted run resumable on MySQL is -// that every step is guarded by the schema state it changes — the entry check -// fires while either legacy column remains, the adds skip existing columns, -// the backfill and its loud-failure check run only while the legacy cluster -// column exists (they provably completed before any drop), and each drop -// skips what is already gone. func MigrateAgentNetworkSettingsToDomain(ctx context.Context, db *gorm.DB) error { model := &agentNetworkSettingsMigration{} migrator := db.Migrator() @@ -66,14 +57,9 @@ func MigrateAgentNetworkSettingsToDomain(ctx context.Context, db *gorm.DB) error } if hasCluster { - concat := "subdomain || '.' || cluster" - if tx.Name() == "mysql" { - concat = "CONCAT(subdomain, '.', cluster)" - } - res := tx.Exec(fmt.Sprintf( - "UPDATE agent_network_settings SET domain = %s, proxy_address = cluster WHERE (domain IS NULL OR domain = '') AND cluster <> '' AND subdomain <> ''", - concat, - )) + res := tx.Exec( + "UPDATE agent_network_settings SET domain = subdomain || '.' || cluster, proxy_address = cluster WHERE (domain IS NULL OR domain = '') AND cluster <> '' AND subdomain <> ''", + ) if res.Error != nil { return fmt.Errorf("backfill agent_network_settings domain: %w", res.Error) } diff --git a/management/server/migration/migration_test.go b/management/server/migration/migration_test.go index 868332fdf..54c587a8a 100644 --- a/management/server/migration/migration_test.go +++ b/management/server/migration/migration_test.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" @@ -32,17 +31,6 @@ func setupDatabase(t *testing.T) *gorm.DB { var dsn string var cleanup func() switch os.Getenv("NETBIRD_STORE_ENGINE") { - case "mysql": - cleanup, dsn, err = testutil.CreateMysqlTestContainer() - if err != nil { - t.Fatalf("Failed to create MySQL test container: %v", err) - } - - if dsn == "" { - t.Fatal("MySQL connection string is empty, ensure the test container is running") - } - - db, err = gorm.Open(mysql.Open(dsn+"?charset=utf8&parseTime=True&loc=Local"), &gorm.Config{}) case "postgres": cleanup, dsn, err = testutil.CreatePostgresTestContainer() if err != nil { @@ -597,9 +585,8 @@ func TestCleanupOrphanedResources_Idempotent(t *testing.T) { } func TestCleanupOrphanedResources_SkipsWhenForeignKeyExists(t *testing.T) { - engine := os.Getenv("NETBIRD_STORE_ENGINE") - if engine != "postgres" && engine != "mysql" { - t.Skip("FK constraint early-exit test requires postgres or mysql") + if os.Getenv("NETBIRD_STORE_ENGINE") != "postgres" { + t.Skip("FK constraint early-exit test requires postgres") } db := setupDatabase(t) @@ -614,24 +601,12 @@ func TestCleanupOrphanedResources_SkipsWhenForeignKeyExists(t *testing.T) { require.NoError(t, db.Create(&testChildWithFK{ID: "c1", ParentID: "p1"}).Error) require.NoError(t, db.Create(&testChildWithFK{ID: "c2", ParentID: "p2"}).Error) - switch engine { - case "postgres": - require.NoError(t, db.Exec("ALTER TABLE test_children DROP CONSTRAINT fk_test_children_parent").Error) - require.NoError(t, db.Exec("DELETE FROM test_parents WHERE id = ?", "p2").Error) - require.NoError(t, db.Exec( - "ALTER TABLE test_children ADD CONSTRAINT fk_test_children_parent "+ - "FOREIGN KEY (parent_id) REFERENCES test_parents(id) NOT VALID", - ).Error) - case "mysql": - require.NoError(t, db.Exec("SET FOREIGN_KEY_CHECKS = 0").Error) - require.NoError(t, db.Exec("ALTER TABLE test_children DROP FOREIGN KEY fk_test_children_parent").Error) - require.NoError(t, db.Exec("DELETE FROM test_parents WHERE id = ?", "p2").Error) - require.NoError(t, db.Exec( - "ALTER TABLE test_children ADD CONSTRAINT fk_test_children_parent "+ - "FOREIGN KEY (parent_id) REFERENCES test_parents(id)", - ).Error) - require.NoError(t, db.Exec("SET FOREIGN_KEY_CHECKS = 1").Error) - } + require.NoError(t, db.Exec("ALTER TABLE test_children DROP CONSTRAINT fk_test_children_parent").Error) + require.NoError(t, db.Exec("DELETE FROM test_parents WHERE id = ?", "p2").Error) + require.NoError(t, db.Exec( + "ALTER TABLE test_children ADD CONSTRAINT fk_test_children_parent "+ + "FOREIGN KEY (parent_id) REFERENCES test_parents(id) NOT VALID", + ).Error) err = migration.CleanupOrphanedResources[testChildWithFK, testParent](context.Background(), db, "parent_id") require.NoError(t, err) @@ -717,8 +692,6 @@ func TestFoldCostAggregatesIntoBuckets_SkipsAlreadyMigrated(t *testing.T) { require.NoError(t, db.Migrator().DropTable(&agentNetworkTypes.AgentNetworkUsage{})) require.NoError(t, db.AutoMigrate(&agentNetworkTypes.AgentNetworkUsage{})) - // Timestamp must be set explicitly: a zero time.Time serialises as - // '0000-00-00 00:00:00', which MySQL rejects under strict mode. require.NoError(t, db.Create(&agentNetworkTypes.AgentNetworkUsage{ ID: "u1", AccountID: "acct-1", Model: "claude-sonnet-4-6", Timestamp: time.Date(2026, 5, 5, 9, 0, 0, 0, time.UTC), @@ -819,10 +792,9 @@ func TestMigrateAgentNetworkSettingsToDomain_FailsOnUnmigratableRow(t *testing.T assert.Contains(t, err.Error(), "resolve them manually", "the error must tell the operator what to do") } -// partialAgentNetworkSettings models the one non-atomic state a MySQL run can -// be interrupted in: DDL auto-commits there, so a crash between the two legacy -// column drops leaves subdomain behind while cluster (and the completed -// backfill) are already committed. +// partialAgentNetworkSettings models a schema left between the two legacy +// column drops: subdomain is still present while cluster is gone and the +// backfill has already completed. type partialAgentNetworkSettings struct { AccountID string `gorm:"primaryKey"` Subdomain string @@ -832,8 +804,8 @@ type partialAgentNetworkSettings struct { func (partialAgentNetworkSettings) TableName() string { return "agent_network_settings" } -// TestMigrateAgentNetworkSettingsToDomain_ResumesAfterPartialDrop pins MySQL -// resumability: a rerun over the interrupted state must remove the leftover +// TestMigrateAgentNetworkSettingsToDomain_ResumesAfterPartialDrop pins +// resumability: a rerun over the partial state must remove the leftover // subdomain column without re-running the backfill (the cluster column that // feeds it is gone) and without touching the migrated values. func TestMigrateAgentNetworkSettingsToDomain_ResumesAfterPartialDrop(t *testing.T) { diff --git a/management/server/peer_test.go b/management/server/peer_test.go index 691630a3b..b75dd1b72 100644 --- a/management/server/peer_test.go +++ b/management/server/peer_test.go @@ -1566,8 +1566,7 @@ func Test_RegisterPeerBySetupKey(t *testing.T) { func Test_RegisterPeerRollbackOnFailure(t *testing.T) { engine := os.Getenv("NETBIRD_STORE_ENGINE") - if engine == "sqlite" || engine == "mysql" || engine == "" { - // we intentionally disabled foreign keys in mysql + if engine == "sqlite" || engine == "" { t.Skip("Skipping test because store is not respecting foreign keys") } if runtime.GOOS == "windows" { @@ -2219,10 +2218,6 @@ func Test_IsUniqueConstraintError(t *testing.T) { name: "PostgreSQL uniqueness error", engine: types.PostgresStoreEngine, }, - { - name: "MySQL uniqueness error", - engine: types.MysqlStoreEngine, - }, { name: "SQLite uniqueness error", engine: types.SqliteStoreEngine, diff --git a/management/server/store/sql_store.go b/management/server/store/sql_store.go index b705ba0a2..1734129c3 100644 --- a/management/server/store/sql_store.go +++ b/management/server/store/sql_store.go @@ -33,7 +33,6 @@ import ( const ( idQueryCondition = "id = ?" keyQueryCondition = "key = ?" - mysqlKeyQueryCondition = "`key` = ?" accountAndIDQueryCondition = "account_id = ? and id = ?" accountAndAnyIDQueryCondition = "account_id = ? and (id = ? or public_id = ?)" accountAndPeerIDQueryCondition = "account_id = ? and peer_id = ?" @@ -119,13 +118,6 @@ func (s *SqlStore) pgxPool() *pgxpool.Pool { return s.conn.Pool(s.tx) } -func GetKeyQueryCondition(s *SqlStore) string { - if s.conn.Engine() == db.MysqlStoreEngine { - return mysqlKeyQueryCondition - } - return keyQueryCondition -} - // AcquireGlobalLock acquires global lock across all the accounts and returns a function that releases the lock func (s *SqlStore) AcquireGlobalLock(ctx context.Context) (unlock func()) { log.WithContext(ctx).Tracef("acquiring global lock") @@ -174,15 +166,6 @@ func NewPostgresqlStore(ctx context.Context, dsn string, metrics telemetry.AppMe return newStore(ctx, conn, metrics, skipMigration) } -// NewMysqlStore creates a new MySQL store. -func NewMysqlStore(ctx context.Context, dsn string, metrics telemetry.AppMetrics, skipMigration bool) (*SqlStore, error) { - conn, err := db.OpenMysql(ctx, dsn) - if err != nil { - return nil, err - } - return newStore(ctx, conn, metrics, skipMigration) -} - // NewSqliteStoreFromFileStore restores a store from FileStore and stores SQLite DB in the file located in datadir. func NewSqliteStoreFromFileStore(ctx context.Context, fileStore *FileStore, dataDir string, metrics telemetry.AppMetrics, skipMigration bool) (*SqlStore, error) { store, err := NewSqliteStore(ctx, dataDir, metrics, skipMigration) @@ -240,11 +223,6 @@ func NewPostgresqlStoreForTests(ctx context.Context, dsn string, metrics telemet return newStore(ctx, conn, metrics, skipMigration) } -// NewMysqlStoreFromSqlStore restores a store from SqlStore and stores MySQL DB. -func NewMysqlStoreFromSqlStore(ctx context.Context, sqliteStore *SqlStore, dsn string, metrics telemetry.AppMetrics) (*SqlStore, error) { - return newMysqlStoreFromSqlStore(ctx, sqliteStore, dsn, metrics, false) -} - // seedFromSqliteStore copies the installation ID and the accounts of the // sqlite seed store into a freshly created engine store. func seedFromSqliteStore(ctx context.Context, store, sqliteStore *SqlStore) error { @@ -259,20 +237,6 @@ func seedFromSqliteStore(ctx context.Context, store, sqliteStore *SqlStore) erro return nil } -func newMysqlStoreFromSqlStore(ctx context.Context, sqliteStore *SqlStore, dsn string, metrics telemetry.AppMetrics, skipMigration bool) (*SqlStore, error) { - store, err := NewMysqlStore(ctx, dsn, metrics, skipMigration) - if err != nil { - return nil, err - } - - if err := seedFromSqliteStore(ctx, store, sqliteStore); err != nil { - _ = store.Close(ctx) - return nil, err - } - - return store, nil -} - // ExecuteInTransaction runs operation in a transaction. A store that is already // bound to one joins it instead of opening a second, independent transaction. func (s *SqlStore) ExecuteInTransaction(ctx context.Context, operation func(store Store) error) error { diff --git a/management/server/store/sql_store_account.go b/management/server/store/sql_store_account.go index 3780de77d..5c488ece8 100644 --- a/management/server/store/sql_store_account.go +++ b/management/server/store/sql_store_account.go @@ -1084,10 +1084,8 @@ func (s *SqlStore) SaveAccountSettings(ctx context.Context, accountID string, se return status.Errorf(status.Internal, "failed to save account settings to store") } - // MySQL reports RowsAffected=0 for no-op updates where values don't change, - // unlike SQLite/Postgres which report matched rows. Skip the check since the - // caller (UpdateAccountSettings) already verified the account exists via - // GetAccountSettings with LockingStrengthUpdate. + // No RowsAffected check: the caller (UpdateAccountSettings) already verified + // the account exists via GetAccountSettings with LockingStrengthUpdate. return nil } diff --git a/management/server/store/sql_store_group_test.go b/management/server/store/sql_store_group_test.go index 58291ab44..abb7fa8de 100644 --- a/management/server/store/sql_store_group_test.go +++ b/management/server/store/sql_store_group_test.go @@ -3,7 +3,6 @@ package store import ( "context" "fmt" - "os" "testing" "github.com/stretchr/testify/require" @@ -69,10 +68,6 @@ func TestSqlStore_GetGroupsByIDs(t *testing.T) { } func TestSqlStore_CreateGroup(t *testing.T) { - if os.Getenv("CI") == "true" { - t.Log("Skipping MySQL test on CI") - } - t.Setenv("NETBIRD_STORE_ENGINE", string(types.MysqlStoreEngine)) store, cleanup, err := NewTestStoreFromSQL(context.Background(), "../testdata/extended-store.sql", t.TempDir()) t.Cleanup(cleanup) require.NoError(t, err) diff --git a/management/server/store/sql_store_idp_migration.go b/management/server/store/sql_store_idp_migration.go index 760d2967c..46ccd7603 100644 --- a/management/server/store/sql_store_idp_migration.go +++ b/management/server/store/sql_store_idp_migration.go @@ -55,7 +55,6 @@ func (s *SqlStore) ListUsers(ctx context.Context) ([]*types.User, error) { } // txDeferFKConstraints defers foreign key constraint checks for the duration of the transaction. -// MySQL is already handled by s.transaction (SET FOREIGN_KEY_CHECKS = 0). func (s *SqlStore) txDeferFKConstraints(tx *gorm.DB) error { if s.conn.Engine() == types.SqliteStoreEngine { return tx.Exec("PRAGMA defer_foreign_keys = ON").Error diff --git a/management/server/store/sql_store_peer.go b/management/server/store/sql_store_peer.go index 657d2a6e0..77642eea7 100644 --- a/management/server/store/sql_store_peer.go +++ b/management/server/store/sql_store_peer.go @@ -375,7 +375,7 @@ func (s *SqlStore) GetAccountByPeerID(ctx context.Context, peerID string) (*type func (s *SqlStore) GetAccountByPeerPubKey(ctx context.Context, peerKey string) (*types.Account, error) { var peer nbpeer.Peer - result := s.db.Select("account_id").Take(&peer, GetKeyQueryCondition(s), peerKey) + result := s.db.Select("account_id").Take(&peer, keyQueryCondition, peerKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -394,7 +394,7 @@ func (s *SqlStore) GetAccountByPeerPubKey(ctx context.Context, peerKey string) ( func (s *SqlStore) GetAccountIDByPeerPubKey(ctx context.Context, peerKey string) (string, error) { var peer nbpeer.Peer var accountID string - result := s.db.Model(&peer).Select("account_id").Where(GetKeyQueryCondition(s), peerKey).Take(&accountID) + result := s.db.Model(&peer).Select("account_id").Where(keyQueryCondition, peerKey).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.Errorf(status.NotFound, "account not found: index lookup failed") @@ -483,7 +483,7 @@ func (s *SqlStore) GetPeerByPeerPubKey(ctx context.Context, lockStrength Locking } var peer nbpeer.Peer - result := tx.Take(&peer, GetKeyQueryCondition(s), peerKey) + result := tx.Take(&peer, keyQueryCondition, peerKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -914,7 +914,7 @@ func (s *SqlStore) GetUserIDByPeerKey(ctx context.Context, lockStrength LockingS var userID string result := tx.Model(&nbpeer.Peer{}). Select("user_id"). - Take(&userID, GetKeyQueryCondition(s), peerKey) + Take(&userID, keyQueryCondition, peerKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { @@ -935,7 +935,7 @@ func (s *SqlStore) GetPeerIDByKey(ctx context.Context, lockStrength LockingStren var peerID string result := tx.Model(&nbpeer.Peer{}). Select("id"). - Where(GetKeyQueryCondition(s), key). + Where(keyQueryCondition, key). Limit(1). Scan(&peerID) if result.Error != nil { diff --git a/management/server/store/sql_store_pgx_parity_test.go b/management/server/store/sql_store_pgx_parity_test.go index 1f17817d0..4af0b5540 100644 --- a/management/server/store/sql_store_pgx_parity_test.go +++ b/management/server/store/sql_store_pgx_parity_test.go @@ -13,7 +13,7 @@ import ( ) // TestPgxServiceColumnsMatchGorm guards the Postgres pgx read path against -// drifting from the gorm model. The SQLite/MySQL gorm path loads rows by struct, +// drifting from the gorm model. The SQLite gorm path loads rows by struct, // so a new column on a model is picked up automatically, but the hand-written // pgx SELECT in sql_store.go must be updated by hand. This test fails when a // gorm column is missing from the pgx column list, which otherwise silently diff --git a/management/server/store/sql_store_proxy.go b/management/server/store/sql_store_proxy.go index bdccd282c..c6a08b508 100644 --- a/management/server/store/sql_store_proxy.go +++ b/management/server/store/sql_store_proxy.go @@ -21,8 +21,8 @@ func (s *SqlStore) GetProxyMetrics(ctx context.Context) (ProxyMetrics, error) { var m ProxyMetrics activeCutoff := time.Now().Add(-proxyActiveThreshold) - // COUNT(DISTINCT ... CASE WHEN ...) is portable across sqlite/postgres - // (MySQL too) and keeps the round-trip to one. proxy.StatusConnected + // COUNT(DISTINCT ... CASE WHEN ...) is portable across sqlite and postgres + // and keeps the round-trip to one. proxy.StatusConnected // is the same string the cluster-capability queries use; the active // window matches the cluster-capability semantics (only proxies // heartbeating within ~2 * heartbeat interval count as connected). @@ -292,7 +292,7 @@ func (s *SqlStore) GetProxyClusters(ctx context.Context, accountID string) ([]pr "cluster_address AS address, "+ // COUNT(CASE WHEN ... THEN 1 END) counts only non-NULL — i.e. only // rows that satisfy the predicate — so it works portably across - // sqlite/postgres/mysql without dialect-specific FILTER syntax. + // sqlite and postgres without dialect-specific FILTER syntax. "COUNT(CASE WHEN status = ? AND last_seen > ? THEN 1 END) AS connected_proxies, "+ // MAX(CASE …) > 0 expresses BOOL_OR in a way Postgres tolerates // (Postgres can't MAX a boolean column). diff --git a/management/server/store/sql_store_setup_key.go b/management/server/store/sql_store_setup_key.go index ac42ef725..ef63b2fca 100644 --- a/management/server/store/sql_store_setup_key.go +++ b/management/server/store/sql_store_setup_key.go @@ -18,7 +18,7 @@ import ( func (s *SqlStore) GetAccountBySetupKey(ctx context.Context, setupKey string) (*types.Account, error) { var key types.SetupKey - result := s.db.Select("account_id").Take(&key, GetKeyQueryCondition(s), setupKey) + result := s.db.Select("account_id").Take(&key, keyQueryCondition, setupKey) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, status.NewSetupKeyNotFoundError(setupKey) @@ -99,7 +99,7 @@ func (s *SqlStore) getSetupKeys(ctx context.Context, accountID string) ([]types. func (s *SqlStore) GetAccountIDBySetupKey(ctx context.Context, setupKey string) (string, error) { var accountID string - result := s.db.Model(&types.SetupKey{}).Select("account_id").Where(GetKeyQueryCondition(s), setupKey).Take(&accountID) + result := s.db.Model(&types.SetupKey{}).Select("account_id").Where(keyQueryCondition, setupKey).Take(&accountID) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { return "", status.NewSetupKeyNotFoundError(setupKey) @@ -123,7 +123,7 @@ func (s *SqlStore) GetSetupKeyBySecret(ctx context.Context, lockStrength Locking var setupKey types.SetupKey result := tx. - Take(&setupKey, GetKeyQueryCondition(s), key) + Take(&setupKey, keyQueryCondition, key) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { diff --git a/management/server/store/sql_store_test.go b/management/server/store/sql_store_test.go index 24f9a410d..867657d8b 100644 --- a/management/server/store/sql_store_test.go +++ b/management/server/store/sql_store_test.go @@ -164,7 +164,6 @@ func TestMigrate(t *testing.T) { err = migratePreAuto(context.Background(), store.(*SqlStore).db) require.NoError(t, err, "Migration should not fail on migrated db") - } func newAccount(store Store, id int) error { @@ -352,10 +351,6 @@ func TestSqlStore_DatabaseBlocking(t *testing.T) { } func TestSqlStore_ExecuteInTransaction_Timeout(t *testing.T) { - if os.Getenv("NETBIRD_STORE_ENGINE") == "mysql" { - t.Skip("Skipping timeout test for MySQL") - } - t.Setenv("NB_STORE_TRANSACTION_TIMEOUT", "1s") store, cleanup, err := NewTestStoreFromSQL(context.Background(), "", t.TempDir()) @@ -429,49 +424,6 @@ func TestNewSqliteStore_BusyTimeoutRespectsUserOverride(t *testing.T) { } } -func TestSqlStore_ExecuteInTransaction_RestoresForeignKeyChecksOnMysql(t *testing.T) { - runTestForAllEngines(t, "", func(t *testing.T, store Store) { - sqlStore := store.(*SqlStore) - if sqlStore.conn.Engine() != types.MysqlStoreEngine { - t.Skip("FOREIGN_KEY_CHECKS is MySQL specific") - } - sqlDB, err := sqlStore.GetDB().DB() - require.NoError(t, err) - sqlDB.SetMaxOpenConns(1) - ctx := context.Background() - - foreignKeyChecks := func() int { - var enabled int - require.NoError(t, sqlStore.GetDB().Raw("SELECT @@SESSION.foreign_key_checks").Scan(&enabled).Error) - return enabled - } - - err = store.ExecuteInTransaction(ctx, func(Store) error { return assert.AnError }) - require.ErrorIs(t, err, assert.AnError) - assert.Equal(t, 1, foreignKeyChecks()) - - require.Panics(t, func() { - _ = store.ExecuteInTransaction(ctx, func(Store) error { panic("boom") }) - }) - assert.Equal(t, 1, foreignKeyChecks()) - - err = sqlStore.transaction(ctx, func(*gorm.DB) error { return assert.AnError }) - require.ErrorIs(t, err, assert.AnError) - assert.Equal(t, 1, foreignKeyChecks()) - - err = store.ExecuteInTransaction(ctx, func(transaction Store) error { - bound := transaction.(*SqlStore) - require.NoError(t, bound.transaction(ctx, func(*gorm.DB) error { return nil })) - var enabled int - require.NoError(t, bound.GetDB().Raw("SELECT @@SESSION.foreign_key_checks").Scan(&enabled).Error) - assert.Equal(t, 0, enabled, "a savepoint must not re-enable FK checks for the rest of the transaction") - return nil - }) - require.NoError(t, err) - assert.Equal(t, 1, foreignKeyChecks()) - }) -} - func TestSqlStore_Transaction_RollsBackOnError(t *testing.T) { runTestForAllEngines(t, "../testdata/extended-store.sql", func(t *testing.T, store Store) { ctx := context.Background() diff --git a/management/server/store/store.go b/management/server/store/store.go index 174e97b48..6d20c1e2b 100644 --- a/management/server/store/store.go +++ b/management/server/store/store.go @@ -4,7 +4,6 @@ package store import ( "context" - "database/sql" "errors" "fmt" "net" @@ -20,7 +19,6 @@ import ( "github.com/google/uuid" log "github.com/sirupsen/logrus" - "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" @@ -452,8 +450,6 @@ type AgentNetworkMetrics struct { const ( PostgresDsnEnv = "NB_STORE_ENGINE_POSTGRES_DSN" PostgresDsnEnvLegacy = "NETBIRD_STORE_ENGINE_POSTGRES_DSN" - mysqlDsnEnv = "NB_STORE_ENGINE_MYSQL_DSN" - mysqlDsnEnvLegacy = "NETBIRD_STORE_ENGINE_MYSQL_DSN" ) // lookupDSNEnv checks the NB_ env var first, then falls back to the legacy NETBIRD_ env var. @@ -464,7 +460,7 @@ func lookupDSNEnv(nbKey, legacyKey string) (string, bool) { return os.LookupEnv(legacyKey) } -var supportedEngines = []types.Engine{types.SqliteStoreEngine, types.PostgresStoreEngine, types.MysqlStoreEngine} +var supportedEngines = []types.Engine{types.SqliteStoreEngine, types.PostgresStoreEngine} func getStoreEngineFromEnv() types.Engine { // NETBIRD_STORE_ENGINE supposed to be used in tests. Otherwise, rely on the config file. @@ -474,7 +470,7 @@ func getStoreEngineFromEnv() types.Engine { } value := types.Engine(strings.ToLower(kind)) - if slices.Contains(supportedEngines, value) { + if slices.Contains(supportedEngines, value) || value == types.MysqlStoreEngine { return value } @@ -540,12 +536,8 @@ func OpenConn(ctx context.Context, kind types.Engine, dataDir string) (*db.Conn, } return db.OpenPostgres(ctx, dsn, db.DefaultPoolConfig) case types.MysqlStoreEngine: - log.WithContext(ctx).Info("using MySQL store engine") - dsn, ok := lookupDSNEnv(mysqlDsnEnv, mysqlDsnEnvLegacy) - if !ok { - return nil, fmt.Errorf("%s is not set", mysqlDsnEnv) - } - return db.OpenMysql(ctx, dsn) + return nil, fmt.Errorf("the MySQL store engine is no longer supported. Please refer to the documentation for " + + "migrating to PostgreSQL: https://docs.netbird.io/selfhosted/migration/mysql-to-postgresql") default: return nil, fmt.Errorf("unsupported kind of store: %s", kind) } @@ -725,7 +717,7 @@ func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) ( } if filename != "" { - err = LoadSQL(conn.DB(nil), filename, translaterForSql(kind)) + err = LoadSQL(conn.DB(nil), filename) if err != nil { _ = conn.Close() return nil, nil, fmt.Errorf("failed to load SQL file: %v", err) @@ -761,6 +753,7 @@ func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) ( return nil, nil, fmt.Errorf("failed to create test store after %d attempts: %v", maxRetries, err) } +// NewTestStore creates a test store and optionally loads SQL after migrating its schema. func NewTestStore(ctx context.Context, filename string, dataDir string) (Store, func(), error) { kind := getStoreEngineFromEnv() if kind == "" { @@ -786,7 +779,7 @@ func NewTestStore(ctx context.Context, filename string, dataDir string) (Store, } if filename != "" { - err = LoadSQL(sqlStore.db, filename, translaterForSql(kind)) + err = LoadSQL(sqlStore.db, filename) if err != nil { _ = sqlStore.Close(ctx) return nil, nil, fmt.Errorf("failed to load SQL file: %v", err) @@ -802,18 +795,6 @@ func NewTestStore(ctx context.Context, filename string, dataDir string) (Store, return sqlStore, cleanup, nil } -// use to translate double-quote escaped reserved names (ansi) -// to mysql tick-escaped ones -func translaterForSql(kind types.Engine) *strings.Replacer { - if kind != types.MysqlStoreEngine { - return strings.NewReplacer() - } - return strings.NewReplacer( - "\"key\"", "`key`", - "\"groups\"", "`groups`", - ) -} - func addAllGroupToAccount(ctx context.Context, store Store) error { allAccounts := store.GetAllAccounts(ctx) for _, account := range allAccounts { @@ -843,9 +824,7 @@ func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.En var err error switch kind { case types.PostgresStoreEngine: - store, cleanup, err = newReusedPostgresStore(ctx, sqliteStore, kind) - case types.MysqlStoreEngine: - store, cleanup, err = newReusedMysqlStore(ctx, sqliteStore, kind) + store, cleanup, err = newReusedPostgresStore(ctx, sqliteStore) default: cleanup = func() { // sqlite doesn't need to be cleaned up @@ -877,7 +856,7 @@ func getSqlStoreEngine(ctx context.Context, sqliteStore *SqlStore, kind types.En return store, closeConnection, nil } -func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore, kind types.Engine) (*SqlStore, func(), error) { +func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore) (*SqlStore, func(), error) { dsn, ok := lookupDSNEnv(PostgresDsnEnv, PostgresDsnEnvLegacy) if !ok || dsn == "" { var err error @@ -891,7 +870,7 @@ func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore, kind typ return nil, nil, fmt.Errorf("%s is not set", PostgresDsnEnv) } - db, err := openDBWithRetry(dsn, kind, 5) + db, err := openDBWithRetry(dsn, 5) if err != nil { return nil, nil, fmt.Errorf("failed to open postgres connection: %v", err) } @@ -902,7 +881,7 @@ func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore, kind typ return nil, nil, err } - dsn, cleanup, err := createRandomDB(dsn, db, kind, template) + dsn, cleanup, err := createRandomDB(dsn, db, template) closeGormDB(db) @@ -928,74 +907,10 @@ func newReusedPostgresStore(ctx context.Context, sqliteStore *SqlStore, kind typ return store, cleanup, nil } -func newReusedMysqlStore(ctx context.Context, sqliteStore *SqlStore, kind types.Engine) (*SqlStore, func(), error) { - dsn, ok := lookupDSNEnv(mysqlDsnEnv, mysqlDsnEnvLegacy) - if !ok || dsn == "" { - var err error - _, dsn, err = testutil.CreateMysqlTestContainer() - if err != nil { - return nil, nil, err - } - } - - if dsn == "" { - return nil, nil, fmt.Errorf("%s is not set", mysqlDsnEnv) - } - - db, err := openDBWithRetry(dsn, kind, 5) - if err != nil { - return nil, nil, fmt.Errorf("failed to open mysql connection: %v", err) - } - - sqlDB, err := db.DB() - if err != nil { - return nil, nil, fmt.Errorf("failed to get underlying sql.DB: %v", err) - } - sqlDB.SetMaxOpenConns(1) - sqlDB.SetMaxIdleConns(1) - - tableDDL, err := mysqlSchemaTemplate(ctx, dsn, db) - if err != nil { - sqlDB.Close() - return nil, nil, err - } - - dsn, cleanup, err := createRandomDB(dsn, db, kind, "") - - sqlDB.Close() - - if err != nil { - return nil, nil, err - } - - if err := cloneMysqlSchema(ctx, dsn, tableDDL); err != nil { - cleanup() - return nil, nil, err - } - - var store *SqlStore - if sqliteStore != nil { - store, err = newMysqlStoreFromSqlStore(ctx, sqliteStore, dsn, nil, true) - if err != nil { - cleanup() - return nil, nil, err - } - } else { - store, err = NewMysqlStore(ctx, dsn, nil, false) - if err != nil { - cleanup() - return nil, nil, err - } - } - - return store, cleanup, nil -} - // schemaTemplates remembers, per engine and server, a database that went // through the full migration once in this process. Every later test database // is cloned from it, so a test pays for CREATE DATABASE and a schema copy -// instead of the 40-table AutoMigrate plus every pre and post migration, which -// is what made each MySQL test store cost well over a second in CI. +// instead of the 40-table AutoMigrate plus every pre and post migration. var ( schemaTemplatesMu sync.Mutex schemaTemplates = map[string]*schemaTemplate{} @@ -1003,10 +918,6 @@ var ( type schemaTemplate struct { dbName string - // tableDDL holds the CREATE TABLE statements of the template. MySQL has no - // server-side database template, so the schema is replayed statement by - // statement into each test database. - tableDDL []string } func schemaTemplateKey(engine types.Engine, dsn string) string { @@ -1046,112 +957,6 @@ func postgresSchemaTemplate(ctx context.Context, baseDSN string, admin *gorm.DB) return name, nil } -// mysqlSchemaTemplate returns the CREATE TABLE statements of a fully migrated -// database, migrating one on first use. -func mysqlSchemaTemplate(ctx context.Context, baseDSN string, admin *gorm.DB) ([]string, error) { - schemaTemplatesMu.Lock() - defer schemaTemplatesMu.Unlock() - - key := schemaTemplateKey(types.MysqlStoreEngine, baseDSN) - if tpl, ok := schemaTemplates[key]; ok { - return tpl.tableDDL, nil - } - - name := newTestDBName("test_template") - if err := admin.Exec(fmt.Sprintf("CREATE DATABASE %s", name)).Error; err != nil { - return nil, fmt.Errorf("create mysql template database: %w", err) - } - - tplStore, err := NewMysqlStore(ctx, replaceDBName(baseDSN, name), nil, false) - if err != nil { - dropDatabase(admin, name) - return nil, fmt.Errorf("migrate mysql template database: %w", err) - } - tableDDL, err := mysqlTableDDL(ctx, tplStore.db, name) - tplStore.Close(ctx) - if err != nil { - dropDatabase(admin, name) - return nil, err - } - - schemaTemplates[key] = &schemaTemplate{dbName: name, tableDDL: tableDDL} - return tableDDL, nil -} - -func mysqlTableDDL(ctx context.Context, db *gorm.DB, dbName string) ([]string, error) { - sqlDB, err := db.DB() - if err != nil { - return nil, err - } - - tables, err := mysqlTableNames(ctx, sqlDB, dbName) - if err != nil { - return nil, err - } - - tableDDL := make([]string, 0, len(tables)) - for _, table := range tables { - var name, createStmt string - row := sqlDB.QueryRowContext(ctx, fmt.Sprintf("SHOW CREATE TABLE %s.%s", dbName, table)) - if err := row.Scan(&name, &createStmt); err != nil { - return nil, fmt.Errorf("read create statement of %s: %w", table, err) - } - tableDDL = append(tableDDL, createStmt) - } - return tableDDL, nil -} - -func mysqlTableNames(ctx context.Context, sqlDB *sql.DB, dbName string) ([]string, error) { - rows, err := sqlDB.QueryContext(ctx, fmt.Sprintf("SHOW TABLES FROM %s", dbName)) - if err != nil { - return nil, fmt.Errorf("list template tables: %w", err) - } - defer rows.Close() - - var tables []string - for rows.Next() { - var table string - if err := rows.Scan(&table); err != nil { - return nil, fmt.Errorf("scan template table name: %w", err) - } - tables = append(tables, table) - } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("list template tables: %w", err) - } - return tables, nil -} - -// cloneMysqlSchema replays the template's CREATE TABLE statements into the -// database the DSN points at. -func cloneMysqlSchema(ctx context.Context, dsn string, tableDDL []string) error { - gormDB, err := gorm.Open(mysql.Open(db.MysqlDSN(dsn)), db.GormConfig()) - if err != nil { - return fmt.Errorf("connect to test database: %w", err) - } - sqlDB, err := gormDB.DB() - if err != nil { - return err - } - defer sqlDB.Close() - - // The statements come out of SHOW TABLES in name order, not dependency - // order, and their foreign keys reference tables of the session's default - // database. Pin a single connection so the session setting below covers - // every statement, and connect straight to the new database so unqualified - // references land there. - sqlDB.SetMaxOpenConns(1) - if _, err := sqlDB.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 0"); err != nil { - return fmt.Errorf("disable foreign key checks: %w", err) - } - for _, stmt := range tableDDL { - if _, err := sqlDB.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("replay table definition: %w", err) - } - } - return nil -} - // dropDatabase removes a template that never became usable, so a failed setup // does not leave it behind on a shared server. The server may still be tearing // down the sessions the failed migration held, so the drop retries while @@ -1168,18 +973,12 @@ func closeGormDB(db *gorm.DB) { } } -func openDBWithRetry(dsn string, engine types.Engine, maxRetries int) (*gorm.DB, error) { +func openDBWithRetry(dsn string, maxRetries int) (*gorm.DB, error) { var gormDB *gorm.DB var err error for i := range maxRetries { - switch engine { - case types.PostgresStoreEngine: - gormDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) - case types.MysqlStoreEngine: - gormDB, err = gorm.Open(mysql.Open(db.MysqlDSN(dsn)), &gorm.Config{}) - } - + gormDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err == nil { return gormDB, nil } @@ -1193,13 +992,13 @@ func openDBWithRetry(dsn string, engine types.Engine, maxRetries int) (*gorm.DB, return nil, err } -// createRandomDB creates a uniquely named database for one test. On postgres a -// non-empty template is copied server-side with CREATE DATABASE ... TEMPLATE. -func createRandomDB(dsn string, admin *gorm.DB, engine types.Engine, template string) (string, func(), error) { +// createRandomDB creates a uniquely named database for one test. A non-empty +// template is copied server-side with CREATE DATABASE ... TEMPLATE. +func createRandomDB(dsn string, admin *gorm.DB, template string) (string, func(), error) { dbName := newTestDBName("test_db") createStmt := fmt.Sprintf("CREATE DATABASE %s", dbName) - if template != "" && engine == types.PostgresStoreEngine { + if template != "" { createStmt = fmt.Sprintf("CREATE DATABASE %s TEMPLATE %s", dbName, template) } if err := execWithTemplateRetry(admin, createStmt); err != nil { @@ -1209,59 +1008,28 @@ func createRandomDB(dsn string, admin *gorm.DB, engine types.Engine, template st originalDSN := dsn cleanup := func() { - var dropDB *gorm.DB - var err error - - switch engine { - case types.PostgresStoreEngine: - dropDB, err = gorm.Open(postgres.Open(originalDSN), &gorm.Config{ - SkipDefaultTransaction: true, - PrepareStmt: false, - Logger: logger.Default.LogMode(logger.Info), - }) - if err != nil { - log.Errorf("failed to connect for dropping database %s: %v", dbName, err) - return - } - defer func() { - if sqlDB, _ := dropDB.DB(); sqlDB != nil { - sqlDB.Close() - } - }() - + dropDB, err := gorm.Open(postgres.Open(originalDSN), &gorm.Config{ + SkipDefaultTransaction: true, + PrepareStmt: false, + Logger: logger.Default.LogMode(logger.Info), + }) + if err != nil { + log.Errorf("failed to connect for dropping database %s: %v", dbName, err) + return + } + defer func() { if sqlDB, _ := dropDB.DB(); sqlDB != nil { - sqlDB.SetMaxOpenConns(1) - sqlDB.SetMaxIdleConns(0) - sqlDB.SetConnMaxLifetime(time.Second) + sqlDB.Close() } + }() - err = dropDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", dbName)).Error - - case types.MysqlStoreEngine: - dropDB, err = gorm.Open(mysql.Open(db.MysqlDSN(originalDSN)), &gorm.Config{ - SkipDefaultTransaction: true, - PrepareStmt: false, - }) - if err != nil { - log.Errorf("failed to connect for dropping database %s: %v", dbName, err) - return - } - defer func() { - if sqlDB, _ := dropDB.DB(); sqlDB != nil { - sqlDB.Close() - } - }() - - if sqlDB, _ := dropDB.DB(); sqlDB != nil { - sqlDB.SetMaxOpenConns(1) - sqlDB.SetMaxIdleConns(0) - sqlDB.SetConnMaxLifetime(time.Second) - } - - err = dropDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbName)).Error + if sqlDB, _ := dropDB.DB(); sqlDB != nil { + sqlDB.SetMaxOpenConns(1) + sqlDB.SetMaxIdleConns(0) + sqlDB.SetConnMaxLifetime(time.Second) } - if err != nil { + if err := dropDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s WITH (FORCE)", dbName)).Error; err != nil { log.Errorf("failed to drop database %s: %v", dbName, err) } } @@ -1288,7 +1056,8 @@ func replaceDBName(dsn, newDBName string) string { return re.ReplaceAllString(dsn, `${pre}`+newDBName+`${post}`) } -func LoadSQL(db *gorm.DB, filepath string, translator *strings.Replacer) error { +// LoadSQL executes the SQL statements from the given file. +func LoadSQL(db *gorm.DB, filepath string) error { sqlContent, err := os.ReadFile(filepath) if err != nil { return err @@ -1297,7 +1066,7 @@ func LoadSQL(db *gorm.DB, filepath string, translator *strings.Replacer) error { queries := strings.Split(string(sqlContent), ";") for _, query := range queries { - query = translator.Replace(strings.TrimSpace(query)) + query = strings.TrimSpace(query) if query != "" { err := db.Exec(query).Error if err != nil { diff --git a/management/server/testutil/store.go b/management/server/testutil/store.go index 3854c1173..ddb905d3e 100644 --- a/management/server/testutil/store.go +++ b/management/server/testutil/store.go @@ -8,74 +8,12 @@ import ( log "github.com/sirupsen/logrus" "github.com/testcontainers/testcontainers-go" - "github.com/testcontainers/testcontainers-go/modules/mysql" "github.com/testcontainers/testcontainers-go/modules/postgres" testcontainersredis "github.com/testcontainers/testcontainers-go/modules/redis" "github.com/testcontainers/testcontainers-go/wait" ) -var ( - pgContainer *postgres.PostgresContainer - mysqlContainer *mysql.MySQLContainer -) - -// CreateMysqlTestContainer creates a new MySQL container for testing. -func CreateMysqlTestContainer() (func(), string, error) { - ctx := context.Background() - - if mysqlContainer != nil { - connStr, err := mysqlContainer.ConnectionString(ctx) - if err != nil { - return nil, "", err - } - return noOpCleanup, connStr, nil - } - - var err error - mysqlContainer, err = mysql.Run(ctx, - "mlsmaycon/warmed-mysql:8", - mysql.WithDatabase("testing"), - mysql.WithUsername("root"), - mysql.WithPassword("testing"), - // Every test creates and drops a database with about 40 tables, so with - // the server defaults the run is dominated by durability work: each - // CREATE TABLE fsyncs the redo log, the binary log and the doublewrite - // buffer. None of it protects anything in a container that is discarded - // after the run. Tables stay in per-table files on purpose: in the shared - // system tablespace the cost of every CREATE and DROP grew with the number - // of databases the run had already created. - testcontainers.WithCmd("mysqld", - "--innodb-flush-log-at-trx-commit=0", - "--innodb-doublewrite=OFF", - "--skip-log-bin", - ), - testcontainers.WithWaitStrategy( - wait.ForLog("/usr/sbin/mysqld: ready for connections"). - WithOccurrence(1).WithStartupTimeout(15*time.Second).WithPollInterval(100*time.Millisecond), - ), - ) - if err != nil { - return nil, "", err - } - - cleanup := func() { - if mysqlContainer != nil { - timeoutCtx, cancelFunc := context.WithTimeout(ctx, 1*time.Second) - defer cancelFunc() - if err = mysqlContainer.Terminate(timeoutCtx); err != nil { - log.WithContext(ctx).Warnf("failed to stop mysql container %s: %s", mysqlContainer.GetContainerID(), err) - } - mysqlContainer = nil // reset the container to allow recreation - } - } - - talksConn, err := mysqlContainer.ConnectionString(ctx) - if err != nil { - return nil, "", err - } - - return cleanup, talksConn, nil -} +var pgContainer *postgres.PostgresContainer // CreatePostgresTestContainer creates a new PostgreSQL container for testing. func CreatePostgresTestContainer() (func(), string, error) { diff --git a/management/server/testutil/store_ios.go b/management/server/testutil/store_ios.go index 9e3b5ce4a..2a484724b 100644 --- a/management/server/testutil/store_ios.go +++ b/management/server/testutil/store_ios.go @@ -8,12 +8,6 @@ func CreatePostgresTestContainer() (func(), string, error) { }, "", nil } -func CreateMysqlTestContainer() (func(), string, error) { - return func() { - // Empty function for MySQL - }, "", nil -} - func CreateRedisTestContainer() (func(), string, error) { return func() { // Empty function for Redis diff --git a/management/server/types/store.go b/management/server/types/store.go index a13d52f91..726ca4c89 100644 --- a/management/server/types/store.go +++ b/management/server/types/store.go @@ -8,5 +8,5 @@ const ( PostgresStoreEngine = db.PostgresStoreEngine FileStoreEngine Engine = "jsonfile" SqliteStoreEngine = db.SqliteStoreEngine - MysqlStoreEngine = db.MysqlStoreEngine + MysqlStoreEngine Engine = "mysql" ) diff --git a/shared/management/client/rest/accounts_test.go b/shared/management/client/rest/accounts_test.go index e44ada298..9de802000 100644 --- a/shared/management/client/rest/accounts_test.go +++ b/shared/management/client/rest/accounts_test.go @@ -168,7 +168,7 @@ func TestAccounts_Integration_Update(t *testing.T) { }) } -// Account deletion on MySQL and PostgreSQL databases causes unknown errors +// Account deletion on PostgreSQL databases causes unknown errors // func TestAccounts_Integration_Delete(t *testing.T) { // withBlackBoxServer(t, func(c *rest.Client) { // accounts, err := c.Accounts.List(context.Background()) diff --git a/tools/mysql-migrate/LICENSE b/tools/mysql-migrate/LICENSE deleted file mode 100644 index be3f7b28e..000000000 --- a/tools/mysql-migrate/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/tools/mysql-migrate/copy.go b/tools/mysql-migrate/copy.go deleted file mode 100644 index 85e0c5e91..000000000 --- a/tools/mysql-migrate/copy.go +++ /dev/null @@ -1,357 +0,0 @@ -package main - -import ( - "context" - "database/sql" - "fmt" - "math" - "slices" - "strconv" - "strings" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgtype" -) - -type dialect struct { - quote func(string) string - tablesQuery string - columnsQuery string -} - -var mysqlDialect = dialect{ - quote: func(name string) string { return "`" + name + "`" }, - tablesQuery: `SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'`, - columnsQuery: `SELECT column_name FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?`, -} - -var sqliteDialect = dialect{ - quote: func(name string) string { return `"` + name + `"` }, - tablesQuery: `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`, - columnsQuery: `SELECT name FROM pragma_table_info(?)`, -} - -type column struct { - name string - pgType string -} - -// copyStore copies the tables the source shares with the target schema; -// source-only tables are legacy and skipped. -func copyStore(ctx context.Context, src *sql.DB, d dialect, tx pgx.Tx, skip map[string]bool) (int, int64, error) { - srcTables, err := queryStrings(ctx, src, d.tablesQuery) - if err != nil { - return 0, 0, fmt.Errorf("list source tables: %w", err) - } - dstTables, err := pgStrings(ctx, tx, `SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE'`) - if err != nil { - return 0, 0, fmt.Errorf("list target tables: %w", err) - } - - var tables []string - for _, t := range srcTables { - if !skip[t] && slices.Contains(dstTables, t) { - tables = append(tables, t) - } - } - if len(tables) == 0 { - return 0, 0, fmt.Errorf("no NetBird tables found in the source") - } - - ordered, err := parentsFirst(ctx, tx, tables) - if err != nil { - return 0, 0, err - } - - var total int64 - for _, table := range ordered { - n, err := copyTable(ctx, src, d, tx, table) - if err != nil { - return 0, 0, fmt.Errorf("table %s: %w", table, err) - } - total += n - } - - if err := resetSequences(ctx, tx, tables); err != nil { - return 0, 0, err - } - return len(tables), total, nil -} - -func copyTable(ctx context.Context, src *sql.DB, d dialect, tx pgx.Tx, table string) (int64, error) { - cols, err := targetColumns(ctx, tx, table) - if err != nil { - return 0, err - } - srcCols, err := queryStrings(ctx, src, d.columnsQuery, table) - if err != nil { - return 0, fmt.Errorf("list source columns: %w", err) - } - - names := make([]string, len(cols)) - quoted := make([]string, len(cols)) - var missing []string - for i, c := range cols { - names[i] = c.name - quoted[i] = d.quote(c.name) - if !slices.Contains(srcCols, c.name) { - missing = append(missing, c.name) - } - } - if len(missing) > 0 { - return 0, fmt.Errorf("source lacks columns %v; start the management server once with this release before migrating", missing) - } - - var hasRows bool - if err := tx.QueryRow(ctx, fmt.Sprintf("SELECT EXISTS (SELECT 1 FROM %s)", pgx.Identifier{table}.Sanitize())).Scan(&hasRows); err != nil { - return 0, err - } - if hasRows { - return 0, fmt.Errorf("target already holds data") - } - - rows, err := src.QueryContext(ctx, fmt.Sprintf("SELECT %s FROM %s", strings.Join(quoted, ", "), d.quote(table))) - if err != nil { - return 0, fmt.Errorf("read source: %w", err) - } - defer rows.Close() - - return tx.CopyFrom(ctx, pgx.Identifier{table}, names, newRowSource(rows, cols)) -} - -func targetColumns(ctx context.Context, tx pgx.Tx, table string) ([]column, error) { - rows, err := tx.Query(ctx, `SELECT column_name, data_type FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = $1 ORDER BY ordinal_position`, table) - if err != nil { - return nil, err - } - return pgx.CollectRows(rows, func(row pgx.CollectableRow) (column, error) { - var c column - err := row.Scan(&c.name, &c.pgType) - return c, err - }) -} - -func parentsFirst(ctx context.Context, tx pgx.Tx, tables []string) ([]string, error) { - rows, err := tx.Query(ctx, `SELECT child.relname, parent.relname FROM pg_constraint c - JOIN pg_class child ON child.oid = c.conrelid - JOIN pg_class parent ON parent.oid = c.confrelid - JOIN pg_namespace n ON n.oid = child.relnamespace - WHERE c.contype = 'f' AND n.nspname = current_schema()`) - if err != nil { - return nil, fmt.Errorf("read foreign keys: %w", err) - } - parents := map[string][]string{} - var child, parent string - _, err = pgx.ForEachRow(rows, []any{&child, &parent}, func() error { - if child != parent { - parents[child] = append(parents[child], parent) - } - return nil - }) - if err != nil { - return nil, fmt.Errorf("read foreign keys: %w", err) - } - - pending := slices.Sorted(slices.Values(tables)) - done := make(map[string]bool, len(tables)) - ordered := make([]string, 0, len(tables)) - for len(pending) > 0 { - var next []string - for _, t := range pending { - if ready(parents[t], tables, done) { - ordered = append(ordered, t) - done[t] = true - } else { - next = append(next, t) - } - } - if len(next) == len(pending) { - return nil, fmt.Errorf("foreign keys form a cycle between %v", next) - } - pending = next - } - return ordered, nil -} - -func ready(parents, tables []string, done map[string]bool) bool { - for _, p := range parents { - if slices.Contains(tables, p) && !done[p] { - return false - } - } - return true -} - -// resetSequences moves serial sequences past the ids COPY inserted explicitly. -func resetSequences(ctx context.Context, tx pgx.Tx, tables []string) error { - rows, err := tx.Query(ctx, `SELECT table_name, column_name, pg_get_serial_sequence(quote_ident(table_name), column_name) - FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = ANY($1) - AND pg_get_serial_sequence(quote_ident(table_name), column_name) IS NOT NULL`, tables) - if err != nil { - return fmt.Errorf("list sequences: %w", err) - } - type sequence struct{ table, column, name string } - seqs, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (sequence, error) { - var s sequence - err := row.Scan(&s.table, &s.column, &s.name) - return s, err - }) - if err != nil { - return fmt.Errorf("list sequences: %w", err) - } - - for _, s := range seqs { - q := fmt.Sprintf("SELECT setval('%s', COALESCE(MAX(%s), 0) + 1, false) FROM %s", - strings.ReplaceAll(s.name, "'", "''"), pgx.Identifier{s.column}.Sanitize(), pgx.Identifier{s.table}.Sanitize()) - if _, err := tx.Exec(ctx, q); err != nil { - return fmt.Errorf("reset sequence %s: %w", s.name, err) - } - } - return nil -} - -type rowSource struct { - rows *sql.Rows - cols []column - vals []any - ptrs []any -} - -func newRowSource(rows *sql.Rows, cols []column) *rowSource { - r := &rowSource{rows: rows, cols: cols, vals: make([]any, len(cols)), ptrs: make([]any, len(cols))} - for i := range r.vals { - r.ptrs[i] = &r.vals[i] - } - return r -} - -func (r *rowSource) Next() bool { return r.rows.Next() } - -func (r *rowSource) Err() error { return r.rows.Err() } - -func (r *rowSource) Values() ([]any, error) { - if err := r.rows.Scan(r.ptrs...); err != nil { - return nil, err - } - out := make([]any, len(r.vals)) - for i, v := range r.vals { - if v == nil { - continue - } - converted, err := convert(v, r.cols[i].pgType) - if err != nil { - return nil, fmt.Errorf("column %s: %w", r.cols[i].name, err) - } - out[i] = converted - } - return out, nil -} - -// convert adapts a non-NULL value to the target column type: MySQL and SQLite -// return text and numbers as bytes and booleans as integers. -func convert(v any, pgType string) (any, error) { - switch pgType { - case "boolean": - return toBool(v) - case "bytea": - return toBytes(v), nil - case "smallint", "integer", "bigint": - return toInt64(v) - case "real", "double precision": - return toFloat64(v) - case "numeric": - return toNumeric(v) - default: - return toText(v), nil - } -} - -func toBool(v any) (any, error) { - switch b := v.(type) { - case int64: - return b != 0, nil - case []byte: - return strconv.ParseBool(string(b)) - case string: - return strconv.ParseBool(b) - } - return v, nil -} - -func toBytes(v any) any { - if s, ok := v.(string); ok { - return []byte(s) - } - return v -} - -func toInt64(v any) (any, error) { - switch n := v.(type) { - case uint64: - if n > math.MaxInt64 { - return nil, fmt.Errorf("value %d overflows bigint", n) - } - return int64(n), nil - case []byte: - return strconv.ParseInt(string(n), 10, 64) - } - return v, nil -} - -func toFloat64(v any) (any, error) { - if b, ok := v.([]byte); ok { - return strconv.ParseFloat(string(b), 64) - } - return v, nil -} - -func toNumeric(v any) (any, error) { - var s string - switch x := v.(type) { - case []byte: - s = string(x) - case string: - s = x - default: - return v, nil - } - var n pgtype.Numeric - if err := n.Scan(s); err != nil { - return nil, err - } - return n, nil -} - -func toText(v any) any { - if b, ok := v.([]byte); ok { - return string(b) - } - return v -} - -func queryStrings(ctx context.Context, db *sql.DB, query string, args ...any) ([]string, error) { - rows, err := db.QueryContext(ctx, query, args...) - if err != nil { - return nil, err - } - defer rows.Close() - var out []string - for rows.Next() { - var s string - if err := rows.Scan(&s); err != nil { - return nil, err - } - out = append(out, s) - } - return out, rows.Err() -} - -func pgStrings(ctx context.Context, tx pgx.Tx, query string) ([]string, error) { - rows, err := tx.Query(ctx, query) - if err != nil { - return nil, err - } - return pgx.CollectRows(rows, pgx.RowTo[string]) -} diff --git a/tools/mysql-migrate/main.go b/tools/mysql-migrate/main.go deleted file mode 100644 index f9531c66a..000000000 --- a/tools/mysql-migrate/main.go +++ /dev/null @@ -1,242 +0,0 @@ -package main - -import ( - "context" - "database/sql" - "errors" - "flag" - "fmt" - "log/slog" - "net/url" - "os" - "strings" - "time" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgxpool" - log "github.com/sirupsen/logrus" - "gorm.io/driver/mysql" - "gorm.io/driver/postgres" - "gorm.io/driver/sqlite" - "gorm.io/gorm" - "gorm.io/gorm/logger" - - "github.com/netbirdio/netbird/idp/dex" - "github.com/netbirdio/netbird/management/internals/shared/db" - "github.com/netbirdio/netbird/management/server/activity" - "github.com/netbirdio/netbird/management/server/store" -) - -type config struct { - mysqlDSN string - postgresDSN string - eventsPostgresDSN string - authPostgresDSN string - eventsDB string - authDB string - mysqlTimezone string -} - -type storeMigration struct { - name string - source *sql.DB - dialect dialect - targetDSN string - schema func(ctx context.Context, dsn string) error - skipTables map[string]bool -} - -func main() { - cfg, err := parseFlags(os.Args[1:]) - if errors.Is(err, flag.ErrHelp) { - return - } - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(2) - } - - // Silence the store constructors' migration logs. - log.SetLevel(log.WarnLevel) - - if err := run(context.Background(), cfg); err != nil { - fmt.Fprintf(os.Stderr, "migration failed: %v\n", err) - os.Exit(1) - } -} - -func parseFlags(args []string) (*config, error) { - cfg := &config{} - fs := flag.NewFlagSet("netbird-mysql-migrate", flag.ContinueOnError) - fs.StringVar(&cfg.mysqlDSN, "mysql-dsn", "", "MySQL DSN of the management store (required)") - fs.StringVar(&cfg.postgresDSN, "postgres-dsn", "", "Postgres DSN to migrate all stores to (required)") - fs.StringVar(&cfg.eventsPostgresDSN, "events-postgres-dsn", "", "Postgres DSN for activity events (default --postgres-dsn)") - fs.StringVar(&cfg.authPostgresDSN, "auth-postgres-dsn", "", "Postgres DSN for the embedded IdP (default --postgres-dsn)") - fs.StringVar(&cfg.eventsDB, "events-db", "/var/lib/netbird/events.db", "SQLite file of the activity events, skipped when missing") - fs.StringVar(&cfg.authDB, "auth-db", "/var/lib/netbird/idp.db", "SQLite file of the embedded IdP, skipped when missing") - fs.StringVar(&cfg.mysqlTimezone, "mysql-timezone", "UTC", "time zone the management server ran in, e.g. Europe/Berlin") - if err := fs.Parse(args); err != nil { - return nil, err - } - if _, err := time.LoadLocation(cfg.mysqlTimezone); err != nil { - return nil, fmt.Errorf("--mysql-timezone: %w", err) - } - - if cfg.mysqlDSN == "" || cfg.postgresDSN == "" { - return nil, errors.New("--mysql-dsn and --postgres-dsn are required") - } - if cfg.eventsPostgresDSN == "" { - cfg.eventsPostgresDSN = cfg.postgresDSN - } - if cfg.authPostgresDSN == "" { - cfg.authPostgresDSN = cfg.postgresDSN - } - return cfg, nil -} - -func run(ctx context.Context, cfg *config) error { - migrations, closeSources, err := openSources(cfg) - if err != nil { - return err - } - defer closeSources() - - for _, m := range migrations { - if err := m.schema(ctx, m.targetDSN); err != nil { - return fmt.Errorf("create %s schema: %w", m.name, err) - } - } - - var ( - pools []*pgxpool.Pool - txs []pgx.Tx - ) - // Roll back first: pool Close waits for the connections open transactions hold. - defer func() { - for _, tx := range txs { - _ = tx.Rollback(ctx) - } - for _, pool := range pools { - pool.Close() - } - }() - - results := make([]string, 0, len(migrations)) - for _, m := range migrations { - pool, err := pgxpool.New(ctx, m.targetDSN) - if err != nil { - return fmt.Errorf("connect %s target: %w", m.name, err) - } - pools = append(pools, pool) - - tx, err := pool.Begin(ctx) - if err != nil { - return fmt.Errorf("begin %s transaction: %w", m.name, err) - } - txs = append(txs, tx) - - tables, rows, err := copyStore(ctx, m.source, m.dialect, tx, m.skipTables) - if err != nil { - return fmt.Errorf("%s: %w", m.name, err) - } - results = append(results, fmt.Sprintf("%s: %d rows from %d tables", m.name, rows, tables)) - } - - // Commit last so a failure in any store leaves every target empty. - for i, tx := range txs { - if err := tx.Commit(ctx); err != nil { - return fmt.Errorf("commit %s: %w", migrations[i].name, err) - } - } - - for _, r := range results { - fmt.Fprintln(os.Stdout, r) - } - fmt.Fprintln(os.Stdout, "Done. Point the store, activity and auth store settings at Postgres before starting the server.") - return nil -} - -func openSources(cfg *config) ([]storeMigration, func(), error) { - var opened []*gorm.DB - closeAll := func() { - for _, g := range opened { - if sqlDB, err := g.DB(); err == nil { - _ = sqlDB.Close() - } - } - } - - open := func(dialector gorm.Dialector) (*sql.DB, error) { - g, err := gorm.Open(dialector, &gorm.Config{Logger: logger.Discard}) - if err != nil { - return nil, err - } - opened = append(opened, g) - return g.DB() - } - - mysqlDB, err := open(mysql.Open(mysqlDSN(cfg.mysqlDSN, cfg.mysqlTimezone))) - if err != nil { - closeAll() - return nil, nil, fmt.Errorf("open MySQL: %w", err) - } - migrations := []storeMigration{{ - name: "management", source: mysqlDB, dialect: mysqlDialect, - targetDSN: cfg.postgresDSN, schema: createManagementSchema, - }} - - sqliteStores := []storeMigration{ - {name: "activity", targetDSN: cfg.eventsPostgresDSN, schema: createActivitySchema}, - {name: "auth", targetDSN: cfg.authPostgresDSN, schema: createAuthSchema, skipTables: map[string]bool{"migrations": true}}, - } - for i, file := range []string{cfg.eventsDB, cfg.authDB} { - m := sqliteStores[i] - if _, err := os.Stat(file); errors.Is(err, os.ErrNotExist) { - fmt.Fprintf(os.Stdout, "%s: %s not found, skipping\n", m.name, file) - continue - } - m.source, err = open(sqlite.Open("file:" + file + "?mode=ro")) - if err != nil { - closeAll() - return nil, nil, fmt.Errorf("open %s: %w", file, err) - } - m.dialect = sqliteDialect - migrations = append(migrations, m) - } - - return migrations, closeAll, nil -} - -func mysqlDSN(dsn, timezone string) string { - return strings.TrimSuffix(db.MysqlDSN(dsn), "&loc=Local") + "&loc=" + url.QueryEscape(timezone) -} - -func createManagementSchema(ctx context.Context, dsn string) error { - s, err := store.NewPostgresqlStore(ctx, dsn, nil, false) - if err != nil { - return err - } - return s.Close(ctx) -} - -func createActivitySchema(_ context.Context, dsn string) error { - g, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Discard}) - if err != nil { - return err - } - defer func() { - if sqlDB, err := g.DB(); err == nil { - _ = sqlDB.Close() - } - }() - return g.AutoMigrate(&activity.Event{}, &activity.DeletedUser{}) -} - -func createAuthSchema(_ context.Context, dsn string) error { - cfg := dex.Storage{Type: "postgres", Config: map[string]any{"dsn": dsn}} - s, err := cfg.OpenStorage(slog.New(slog.DiscardHandler)) - if err != nil { - return err - } - return s.Close() -} diff --git a/tools/mysql-migrate/main_test.go b/tools/mysql-migrate/main_test.go deleted file mode 100644 index 59d444440..000000000 --- a/tools/mysql-migrate/main_test.go +++ /dev/null @@ -1,225 +0,0 @@ -package main - -import ( - "context" - "encoding/json" - "log/slog" - "os" - "path/filepath" - "runtime" - "strings" - "testing" - "time" - - dexstorage "github.com/dexidp/dex/storage" - "github.com/jackc/pgx/v5/pgxpool" - "github.com/rs/xid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "gorm.io/driver/mysql" - "gorm.io/gorm" - - "github.com/netbirdio/netbird/idp/dex" - "github.com/netbirdio/netbird/management/internals/shared/db" - "github.com/netbirdio/netbird/management/server/activity" - activitystore "github.com/netbirdio/netbird/management/server/activity/store" - "github.com/netbirdio/netbird/management/server/store" - "github.com/netbirdio/netbird/management/server/testutil" - "github.com/netbirdio/netbird/management/server/types" - "github.com/netbirdio/netbird/util/crypt" -) - -const testAccountID = "bf1c8084-ba50-4ce7-9439-34653001fc3b" - -func TestRun(t *testing.T) { - if runtime.GOOS == "windows" || (os.Getenv("CI") == "true" && runtime.GOOS != "linux") { - t.Skip("needs Docker with Linux containers for MySQL and Postgres") - } - // Seed in UTC to match the --mysql-timezone default. - time.Local = time.UTC - ctx := context.Background() - dir := t.TempDir() - key, err := crypt.GenerateKey() - require.NoError(t, err) - - mysqlDSN := newMySQLDatabase(t, "run_src") - pgDSN := newPostgresDatabase(t, ctx, "run_dst") - mysqlStore := seedMySQL(t, ctx, mysqlDSN) - eventID := seedEvents(t, ctx, dir, key) - seedIdP(t, ctx, filepath.Join(dir, "idp.db")) - - cfg, err := parseFlags([]string{ - "--mysql-dsn", mysqlDSN, - "--postgres-dsn", pgDSN, - "--events-db", filepath.Join(dir, "events.db"), - "--auth-db", filepath.Join(dir, "idp.db"), - }) - require.NoError(t, err) - require.NoError(t, run(ctx, cfg)) - - t.Run("management", func(t *testing.T) { - pgStore, err := store.NewPostgresqlStore(ctx, pgDSN, nil, true) - require.NoError(t, err) - t.Cleanup(func() { _ = pgStore.Close(ctx) }) - - assert.JSONEq(t, accountJSON(t, ctx, mysqlStore), accountJSON(t, ctx, pgStore), - "the account read from Postgres must match the one in MySQL") - }) - - t.Run("activity", func(t *testing.T) { - t.Setenv("NB_ACTIVITY_EVENT_STORE_ENGINE", "postgres") - t.Setenv("NB_ACTIVITY_EVENT_POSTGRES_DSN", pgDSN) - events, err := activitystore.NewSqlStore(ctx, dir, key) - require.NoError(t, err) - t.Cleanup(func() { _ = events.Close(ctx) }) - - got, err := events.Get(ctx, testAccountID, 0, 10, false) - require.NoError(t, err) - require.Len(t, got, 1, "the migrated event must be readable") - assert.Equal(t, eventID, got[0].ID, "the event must keep its id") - - next, err := events.Save(ctx, &activity.Event{Timestamp: time.Now(), AccountID: testAccountID, InitiatorID: "u", TargetID: "p"}) - require.NoError(t, err) - assert.Greater(t, next.ID, eventID, "new events must continue after the migrated ids") - }) - - t.Run("auth", func(t *testing.T) { - idp := dex.Storage{Type: "postgres", Config: map[string]any{"dsn": pgDSN}} - s, err := idp.OpenStorage(slog.New(slog.DiscardHandler)) - require.NoError(t, err) - t.Cleanup(func() { _ = s.Close() }) - - pw, err := s.GetPassword(ctx, "admin@example.com") - require.NoError(t, err) - assert.Equal(t, []byte("hash"), pw.Hash, "the IdP password must survive the migration") - }) - - t.Run("refuses a target that holds data", func(t *testing.T) { - assert.ErrorContains(t, run(ctx, cfg), "target already holds data") - }) -} - -func seedMySQL(t *testing.T, ctx context.Context, dsn string) *store.SqlStore { - t.Helper() - t.Setenv("NETBIRD_STORE_ENGINE", string(types.SqliteStoreEngine)) - seed, cleanup, err := store.NewTestStoreFromSQL(ctx, "../../management/server/testdata/extended-store.sql", t.TempDir()) - require.NoError(t, err) - t.Cleanup(cleanup) - - mysqlStore, err := store.NewMysqlStoreFromSqlStore(ctx, seed.(*store.SqlStore), dsn, nil) - require.NoError(t, err) - t.Cleanup(func() { _ = mysqlStore.Close(ctx) }) - return mysqlStore -} - -func seedEvents(t *testing.T, ctx context.Context, dir, key string) uint64 { - t.Helper() - events, err := activitystore.NewSqlStore(ctx, dir, key) - require.NoError(t, err) - defer events.Close(ctx) - - event, err := events.Save(ctx, &activity.Event{ - Timestamp: time.Now(), Activity: activity.PeerAddedByUser, - AccountID: testAccountID, InitiatorID: "user", TargetID: "peer", - Meta: map[string]any{"name": "peer"}, - }) - require.NoError(t, err) - return event.ID -} - -func seedIdP(t *testing.T, ctx context.Context, file string) { - t.Helper() - idp := dex.Storage{Type: "sqlite3", Config: map[string]any{"file": file}} - s, err := idp.OpenStorage(slog.New(slog.DiscardHandler)) - require.NoError(t, err) - defer s.Close() - - require.NoError(t, s.CreatePassword(ctx, dexstorage.Password{ - Email: "admin@example.com", Hash: []byte("hash"), Username: "admin", UserID: "admin-id", - })) -} - -func accountJSON(t *testing.T, ctx context.Context, s store.Store) string { - t.Helper() - var account *types.Account - require.NoError(t, s.ExecuteInTransaction(ctx, func(tx store.Store) error { - var err error - account, err = tx.GetAccount(ctx, testAccountID) - return err - })) - out, err := json.Marshal(account) - require.NoError(t, err) - return string(out) -} - -func TestMySQLTimezone(t *testing.T) { - if runtime.GOOS == "windows" || (os.Getenv("CI") == "true" && runtime.GOOS != "linux") { - t.Skip("needs Docker with Linux containers for MySQL and Postgres") - } - ctx := context.Background() - mysqlDSN := newMySQLDatabase(t, "tz_src") - pgDSN := newPostgresDatabase(t, ctx, "tz_dst") - ms := seedMySQL(t, ctx, mysqlDSN) - require.NoError(t, ms.GetDB().Exec("UPDATE accounts SET created_at = '2026-01-02 03:04:05' WHERE id = ?", testAccountID).Error) - - cfg, err := parseFlags([]string{ - "--mysql-dsn", mysqlDSN, - "--postgres-dsn", pgDSN, - "--mysql-timezone", "Asia/Tokyo", - "--events-db", filepath.Join(t.TempDir(), "none.db"), - "--auth-db", filepath.Join(t.TempDir(), "none.db"), - }) - require.NoError(t, err) - require.NoError(t, run(ctx, cfg)) - - pool, err := pgxpool.New(ctx, pgDSN) - require.NoError(t, err) - t.Cleanup(pool.Close) - var got time.Time - require.NoError(t, pool.QueryRow(ctx, "SELECT created_at FROM accounts WHERE id = $1", testAccountID).Scan(&got)) - want := time.Date(2026, 1, 1, 18, 4, 5, 0, time.UTC) - assert.True(t, want.Equal(got), "created_at must keep the instant the server wrote, got %s", got.UTC()) -} - -func TestParseFlagsRejectsUnknownTimezone(t *testing.T) { - _, err := parseFlags([]string{"--mysql-dsn", "m", "--postgres-dsn", "p", "--mysql-timezone", "Mars/Base"}) - assert.ErrorContains(t, err, "--mysql-timezone") -} - -// newMySQLDatabase creates a database unique to this run in the shared -// container, so repeated runs (-count) don't collide, and drops it afterwards. -func newMySQLDatabase(t *testing.T, prefix string) string { - t.Helper() - _, base, err := testutil.CreateMysqlTestContainer() - require.NoError(t, err) - admin, err := gorm.Open(mysql.Open(db.MysqlDSN(base)), &gorm.Config{}) - require.NoError(t, err) - name := prefix + "_" + xid.New().String() - require.NoError(t, admin.Exec("CREATE DATABASE "+name).Error) - t.Cleanup(func() { - _ = admin.Exec("DROP DATABASE IF EXISTS " + name).Error - if sqlDB, err := admin.DB(); err == nil { - _ = sqlDB.Close() - } - }) - return base[:strings.LastIndex(base, "/")] + "/" + name -} - -// newPostgresDatabase is the Postgres counterpart of newMySQLDatabase. -func newPostgresDatabase(t *testing.T, ctx context.Context, prefix string) string { - t.Helper() - _, base, err := testutil.CreatePostgresTestContainer() - require.NoError(t, err) - // Dex connects through lib/pq, which requires TLS unless told otherwise. - base = strings.TrimSuffix(base, "?") - admin, err := pgxpool.New(ctx, base+"?sslmode=disable") - require.NoError(t, err) - name := prefix + "_" + xid.New().String() - _, err = admin.Exec(ctx, "CREATE DATABASE "+name) - require.NoError(t, err) - t.Cleanup(func() { - _, _ = admin.Exec(context.Background(), "DROP DATABASE IF EXISTS "+name+" WITH (FORCE)") - admin.Close() - }) - return base[:strings.LastIndex(base, "/")] + "/" + name + "?sslmode=disable" -}