From cae2c7292ffc725bc0eea87755c1878c36540c16 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 15 Nov 2024 11:34:58 +0400 Subject: [PATCH 01/22] add uuid to network --- logic/networks.go | 34 +++++++++++++++++++++++++--------- migrate/migrate.go | 14 ++++++++++++++ models/network.go | 38 ++++++++++++++++++++++---------------- 3 files changed, 61 insertions(+), 25 deletions(-) diff --git a/logic/networks.go b/logic/networks.go index 1617889d5..6d9596a99 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -122,22 +122,22 @@ func getNetworksFromCache() (networks []models.Network) { return } -func deleteNetworkFromCache(key string) { +func deleteNetworkFromCache(key uuid.UUID) { networkCacheMutex.Lock() - delete(networkCacheMap, key) + delete(networkCacheMap, key.String()) networkCacheMutex.Unlock() } -func getNetworkFromCache(key string) (network models.Network, ok bool) { +func getNetworkFromCache(key uuid.UUID) (network models.Network, ok bool) { networkCacheMutex.RLock() - network, ok = networkCacheMap[key] + network, ok = networkCacheMap[key.String()] networkCacheMutex.RUnlock() return } -func storeNetworkInCache(key string, network models.Network) { +func storeNetworkInCache(key uuid.UUID, network models.Network) { networkCacheMutex.Lock() - networkCacheMap[key] = network + networkCacheMap[key.String()] = network networkCacheMutex.Unlock() } @@ -163,7 +163,7 @@ func GetNetworks() ([]models.Network, error) { // add network our array networks = append(networks, network) if servercfg.CacheEnabled() { - storeNetworkInCache(network.NetID, network) + storeNetworkInCache(network.ID, network) } } @@ -205,7 +205,7 @@ func DeleteNetwork(network string) error { // CreateNetwork - creates a network in database func CreateNetwork(network models.Network) (models.Network, error) { - + network.ID = uuid.New() if network.AddressRange != "" { normalizedRange, err := NormalizeCIDR(network.AddressRange) if err != nil { @@ -487,11 +487,12 @@ func UpdateNetwork(currentNetwork *models.Network, newNetwork *models.Network) ( hasrangeupdate4 := newNetwork.AddressRange != currentNetwork.AddressRange hasrangeupdate6 := newNetwork.AddressRange6 != currentNetwork.AddressRange6 hasholepunchupdate := newNetwork.DefaultUDPHolePunch != currentNetwork.DefaultUDPHolePunch + newNetwork.SetNetworkLastModified() data, err := json.Marshal(newNetwork) if err != nil { return false, false, false, err } - newNetwork.SetNetworkLastModified() + err = database.Insert(newNetwork.NetID, string(data), database.NETWORKS_TABLE_NAME) if err == nil { if servercfg.CacheEnabled() { @@ -504,6 +505,21 @@ func UpdateNetwork(currentNetwork *models.Network, newNetwork *models.Network) ( return false, false, false, errors.New("failed to update network " + newNetwork.NetID + ", cannot change netid.") } +func UpsertNetwork(net *models.Network) error { + net.SetNetworkLastModified() + data, err := json.Marshal(net) + if err != nil { + return err + } + + err = database.Insert(net.NetID, string(data), database.NETWORKS_TABLE_NAME) + if err == nil { + if servercfg.CacheEnabled() { + storeNetworkInCache(net.ID.String(), *net) + } + } +} + // GetNetwork - gets a network from database func GetNetwork(networkname string) (models.Network, error) { diff --git a/migrate/migrate.go b/migrate/migrate.go index 19e9232aa..8b80dd239 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -155,6 +155,20 @@ func updateEnrollmentKeys() { } } +func updateNetworks() { + nets, err := logic.GetNetworks() + if err != nil { + return + } + for _, netI := range nets { + netI := netI + if netI.ID == uuid.Nil { + netI.ID = uuid.New() + logic.UpsertNetwork(&netI) + } + } +} + func removeOldUserGrps() { rows, err := database.FetchRecords(database.USER_GROUPS_TABLE_NAME) if err != nil { diff --git a/models/network.go b/models/network.go index 32d95f865..c07162c16 100644 --- a/models/network.go +++ b/models/network.go @@ -3,27 +3,32 @@ package models import ( "net" "time" + + "github.com/google/uuid" ) // Network Struct - contains info for a given unique network // At some point, need to replace all instances of Name with something else like Identifier type Network struct { - AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` - AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` - NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=32,netid_valid"` - NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"` - NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"` - DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=35"` - DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"` - NodeLimit int32 `json:"nodelimit" bson:"nodelimit"` - DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"` - DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"` - AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"` - IsIPv4 string `json:"isipv4" bson:"isipv4" validate:"checkyesorno"` - IsIPv6 string `json:"isipv6" bson:"isipv6" validate:"checkyesorno"` - DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"` - DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"` - DefaultACL string `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"` + ID uuid.UUID `json:"id"` + AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` + AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` + NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=32,netid_valid"` + NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"` + NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"` + DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=35"` + DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"` + NodeLimit int32 `json:"nodelimit" bson:"nodelimit"` + DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"` + DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"` + AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"` + IsIPv4 string `json:"isipv4" bson:"isipv4" validate:"checkyesorno"` + IsIPv6 string `json:"isipv6" bson:"isipv6" validate:"checkyesorno"` + DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"` + DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"` + DefaultACL string `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"` + CreatedBy string `json:"created_by"` + CreatedAt string `json:"created_at"` } // SaveData - sensitive fields of a network that should be kept the same @@ -81,6 +86,7 @@ func (network *Network) SetDefaults() { if network.DefaultACL == "" { network.DefaultACL = "yes" } + network.CreatedAt = time.Now().UTC().String() } func (network *Network) GetNetworkNetworkCIDR4() *net.IPNet { From e9c13f7fc320f9eefa082182dba679d5d88793e5 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 15 Nov 2024 11:40:42 +0400 Subject: [PATCH 02/22] add name field to network model --- controllers/network.go | 2 +- logic/networks.go | 19 ++++++++++--------- migrate/migrate.go | 4 ++-- models/network.go | 40 +++++++++++++++++++--------------------- 4 files changed, 32 insertions(+), 33 deletions(-) diff --git a/controllers/network.go b/controllers/network.go index 86a6e3403..6ce96ad4f 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -488,7 +488,7 @@ func createNetwork(w http.ResponseWriter, r *http.Request) { return } - if len(network.NetID) > 32 { + if len(network.Name) > 32 { err := errors.New("network name shouldn't exceed 32 characters") logger.Log(0, r.Header.Get("user"), "failed to create network: ", err.Error()) diff --git a/logic/networks.go b/logic/networks.go index 6d9596a99..0fc7ecd45 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -122,22 +122,22 @@ func getNetworksFromCache() (networks []models.Network) { return } -func deleteNetworkFromCache(key uuid.UUID) { +func deleteNetworkFromCache(key string) { networkCacheMutex.Lock() - delete(networkCacheMap, key.String()) + delete(networkCacheMap, key) networkCacheMutex.Unlock() } -func getNetworkFromCache(key uuid.UUID) (network models.Network, ok bool) { +func getNetworkFromCache(key string) (network models.Network, ok bool) { networkCacheMutex.RLock() - network, ok = networkCacheMap[key.String()] + network, ok = networkCacheMap[key] networkCacheMutex.RUnlock() return } -func storeNetworkInCache(key uuid.UUID, network models.Network) { +func storeNetworkInCache(key string, network models.Network) { networkCacheMutex.Lock() - networkCacheMap[key.String()] = network + networkCacheMap[key] = network networkCacheMutex.Unlock() } @@ -163,7 +163,7 @@ func GetNetworks() ([]models.Network, error) { // add network our array networks = append(networks, network) if servercfg.CacheEnabled() { - storeNetworkInCache(network.ID, network) + storeNetworkInCache(network.NetID, network) } } @@ -205,7 +205,7 @@ func DeleteNetwork(network string) error { // CreateNetwork - creates a network in database func CreateNetwork(network models.Network) (models.Network, error) { - network.ID = uuid.New() + network.NetID = uuid.New().String() if network.AddressRange != "" { normalizedRange, err := NormalizeCIDR(network.AddressRange) if err != nil { @@ -515,9 +515,10 @@ func UpsertNetwork(net *models.Network) error { err = database.Insert(net.NetID, string(data), database.NETWORKS_TABLE_NAME) if err == nil { if servercfg.CacheEnabled() { - storeNetworkInCache(net.ID.String(), *net) + storeNetworkInCache(net.NetID, *net) } } + return nil } // GetNetwork - gets a network from database diff --git a/migrate/migrate.go b/migrate/migrate.go index 8b80dd239..976fc933a 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -162,8 +162,8 @@ func updateNetworks() { } for _, netI := range nets { netI := netI - if netI.ID == uuid.Nil { - netI.ID = uuid.New() + if netI.Name == "" { + netI.Name = netI.NetID logic.UpsertNetwork(&netI) } } diff --git a/models/network.go b/models/network.go index c07162c16..cb2be9682 100644 --- a/models/network.go +++ b/models/network.go @@ -3,32 +3,30 @@ package models import ( "net" "time" - - "github.com/google/uuid" ) // Network Struct - contains info for a given unique network // At some point, need to replace all instances of Name with something else like Identifier type Network struct { - ID uuid.UUID `json:"id"` - AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` - AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` - NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=32,netid_valid"` - NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"` - NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"` - DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=35"` - DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"` - NodeLimit int32 `json:"nodelimit" bson:"nodelimit"` - DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"` - DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"` - AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"` - IsIPv4 string `json:"isipv4" bson:"isipv4" validate:"checkyesorno"` - IsIPv6 string `json:"isipv6" bson:"isipv6" validate:"checkyesorno"` - DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"` - DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"` - DefaultACL string `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"` - CreatedBy string `json:"created_by"` - CreatedAt string `json:"created_at"` + Name string `json:"name"` + AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` + AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` + NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=32,netid_valid"` + NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"` + NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"` + DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=35"` + DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,min=1024,max=65535"` + NodeLimit int32 `json:"nodelimit" bson:"nodelimit"` + DefaultPostDown string `json:"defaultpostdown" bson:"defaultpostdown"` + DefaultKeepalive int32 `json:"defaultkeepalive" bson:"defaultkeepalive" validate:"omitempty,max=1000"` + AllowManualSignUp string `json:"allowmanualsignup" bson:"allowmanualsignup" validate:"checkyesorno"` + IsIPv4 string `json:"isipv4" bson:"isipv4" validate:"checkyesorno"` + IsIPv6 string `json:"isipv6" bson:"isipv6" validate:"checkyesorno"` + DefaultUDPHolePunch string `json:"defaultudpholepunch" bson:"defaultudpholepunch" validate:"checkyesorno"` + DefaultMTU int32 `json:"defaultmtu" bson:"defaultmtu"` + DefaultACL string `json:"defaultacl" bson:"defaultacl" yaml:"defaultacl" validate:"checkyesorno"` + CreatedBy string `json:"created_by"` + CreatedAt string `json:"created_at"` } // SaveData - sensitive fields of a network that should be kept the same From 76eef7e5b583edfb95e6fb65751feafe009e3e06 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 15 Nov 2024 11:44:56 +0400 Subject: [PATCH 03/22] add validation on name field --- models/network.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/models/network.go b/models/network.go index cb2be9682..2e122b7aa 100644 --- a/models/network.go +++ b/models/network.go @@ -8,10 +8,10 @@ import ( // Network Struct - contains info for a given unique network // At some point, need to replace all instances of Name with something else like Identifier type Network struct { - Name string `json:"name"` + Name string `json:"name" validate:"required,min=1,max=32,netid_valid"` AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` - NetID string `json:"netid" bson:"netid" validate:"required,min=1,max=32,netid_valid"` + NetID string `json:"netid"` NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"` NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"` DefaultInterface string `json:"defaultinterface" bson:"defaultinterface" validate:"min=1,max=35"` From 1e67a617a90949cbd6e67c4ec19394cc065e0df2 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Fri, 15 Nov 2024 13:37:33 +0400 Subject: [PATCH 04/22] fix network migration --- migrate/migrate.go | 1 + 1 file changed, 1 insertion(+) diff --git a/migrate/migrate.go b/migrate/migrate.go index 976fc933a..e1f6aaf24 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -20,6 +20,7 @@ import ( // Run - runs all migrations func Run() { + updateNetworks() updateEnrollmentKeys() assignSuperAdmin() createDefaultTagsAndPolicies() From d1c0691ae067a93f9dee82acc4879865e631b69b Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 5 Dec 2024 16:21:04 +0400 Subject: [PATCH 05/22] set epoch as network ID --- logic/networks.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/networks.go b/logic/networks.go index 0fc7ecd45..612ab9f3c 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -205,7 +205,7 @@ func DeleteNetwork(network string) error { // CreateNetwork - creates a network in database func CreateNetwork(network models.Network) (models.Network, error) { - network.NetID = uuid.New().String() + network.NetID = fmt.Sprintf("%d", time.Now().Unix()) if network.AddressRange != "" { normalizedRange, err := NormalizeCIDR(network.AddressRange) if err != nil { From 504935988d23dbfec06d16e9708579802098bb8d Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 5 Dec 2024 16:23:28 +0400 Subject: [PATCH 06/22] add network mutex --- logic/networks.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/logic/networks.go b/logic/networks.go index 612ab9f3c..63b057cc6 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -23,6 +23,7 @@ import ( ) var ( + networkMutex = &sync.RWMutex{} networkCacheMutex = &sync.RWMutex{} networkCacheMap = make(map[string]models.Network) allocatedIpMap = make(map[string]map[string]net.IP) @@ -205,6 +206,8 @@ func DeleteNetwork(network string) error { // CreateNetwork - creates a network in database func CreateNetwork(network models.Network) (models.Network, error) { + networkMutex.Lock() + defer networkMutex.Unlock() network.NetID = fmt.Sprintf("%d", time.Now().Unix()) if network.AddressRange != "" { normalizedRange, err := NormalizeCIDR(network.AddressRange) From 5509b960c7372761a7b34dbddc3a58576632377b Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 5 Dec 2024 16:39:59 +0400 Subject: [PATCH 07/22] remove name validation --- controllers/network.go | 8 -------- models/network.go | 2 +- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/controllers/network.go b/controllers/network.go index 6ce96ad4f..5d0625209 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -488,14 +488,6 @@ func createNetwork(w http.ResponseWriter, r *http.Request) { return } - if len(network.Name) > 32 { - err := errors.New("network name shouldn't exceed 32 characters") - logger.Log(0, r.Header.Get("user"), "failed to create network: ", - err.Error()) - logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) - return - } - if network.AddressRange == "" && network.AddressRange6 == "" { err := errors.New("IPv4 or IPv6 CIDR required") logger.Log(0, r.Header.Get("user"), "failed to create network: ", diff --git a/models/network.go b/models/network.go index 2e122b7aa..dfcba5185 100644 --- a/models/network.go +++ b/models/network.go @@ -8,7 +8,7 @@ import ( // Network Struct - contains info for a given unique network // At some point, need to replace all instances of Name with something else like Identifier type Network struct { - Name string `json:"name" validate:"required,min=1,max=32,netid_valid"` + Name string `json:"name"` AddressRange string `json:"addressrange" bson:"addressrange" validate:"omitempty,cidrv4"` AddressRange6 string `json:"addressrange6" bson:"addressrange6" validate:"omitempty,cidrv6"` NetID string `json:"netid"` From b6b31a3cdf99ed2e2cafde1ab925c00216dfd811 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 5 Dec 2024 20:12:14 +0400 Subject: [PATCH 08/22] remove update copy --- controllers/network.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/controllers/network.go b/controllers/network.go index 5d0625209..e10ec341a 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -606,9 +606,8 @@ func updateNetwork(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } - // partial update - netOld2 := netOld1 - _, _, _, err = logic.UpdateNetwork(&netOld1, &netOld2) + + _, _, _, err = logic.UpdateNetwork(&netOld1, &payload) if err != nil { slog.Info("failed to update network", "user", r.Header.Get("user"), "err", err) logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) From e2740324a72ce53e242918a35569db11aa6f491a Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sun, 8 Dec 2024 13:31:04 +0400 Subject: [PATCH 09/22] check for unique network names --- logic/networks.go | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/logic/networks.go b/logic/networks.go index 63b057cc6..6e80fecc3 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -473,7 +473,7 @@ func IsNetworkNameUnique(network *models.Network) (bool, error) { for i := 0; i < len(dbs); i++ { - if network.NetID == dbs[i].NetID { + if network.Name == dbs[i].Name { isunique = false } } @@ -545,7 +545,6 @@ func GetNetwork(networkname string) (models.Network, error) { // NetIDInNetworkCharSet - checks if a netid of a network uses valid characters func NetIDInNetworkCharSet(network *models.Network) bool { - charset := "abcdefghijklmnopqrstuvwxyz1234567890-_" for _, char := range network.NetID { @@ -559,15 +558,7 @@ func NetIDInNetworkCharSet(network *models.Network) bool { // Validate - validates fields of an network struct func ValidateNetwork(network *models.Network, isUpdate bool) error { v := validator.New() - _ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool { - inCharSet := NetIDInNetworkCharSet(network) - if isUpdate { - return inCharSet - } - isFieldUnique, _ := IsNetworkNameUnique(network) - return isFieldUnique && inCharSet - }) - // + _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool { return validation.CheckYesOrNo(fl) }) From fb97d0413b137a281807308c698de73b6745d98e Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 9 Dec 2024 08:08:06 +0400 Subject: [PATCH 10/22] enforce validation --- logic/networks.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/logic/networks.go b/logic/networks.go index 6e80fecc3..414de4f6b 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -558,7 +558,11 @@ func NetIDInNetworkCharSet(network *models.Network) bool { // Validate - validates fields of an network struct func ValidateNetwork(network *models.Network, isUpdate bool) error { v := validator.New() - + isFieldUnique, _ := IsNetworkNameUnique(network) + if !isFieldUnique { + return errors.New("duplicate network name") + } + // _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool { return validation.CheckYesOrNo(fl) }) From eb6964f71374dbb5572969f163ae2756106524ca Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 9 Dec 2024 20:48:34 +0400 Subject: [PATCH 11/22] set network name as tag --- logic/networks.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/networks.go b/logic/networks.go index 414de4f6b..53f80beb5 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -253,7 +253,7 @@ func CreateNetwork(network models.Network) (models.Network, error) { 0, time.Time{}, []string{network.NetID}, - []string{network.NetID}, + []string{network.Name}, []models.TagID{}, true, uuid.Nil, From de4ce434fe7143addec1256387607437c7db4bb8 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Mon, 9 Dec 2024 20:58:03 +0400 Subject: [PATCH 12/22] use network name as tag --- migrate/migrate.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/migrate/migrate.go b/migrate/migrate.go index e1f6aaf24..ed1865b61 100644 --- a/migrate/migrate.go +++ b/migrate/migrate.go @@ -139,14 +139,14 @@ func updateEnrollmentKeys() { } networks, _ := logic.GetNetworks() for _, network := range networks { - if _, ok := existingTags[network.NetID]; ok { + if _, ok := existingTags[network.Name]; ok { continue } _, _ = logic.CreateEnrollmentKey( 0, time.Time{}, []string{network.NetID}, - []string{network.NetID}, + []string{network.Name}, []models.TagID{}, true, uuid.Nil, From 33a6b85cd041f66b64dc2c12d2f86cd229ac205e Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Tue, 10 Dec 2024 10:12:47 +0400 Subject: [PATCH 13/22] use network name for user roles and groups --- controllers/dns_test.go | 2 ++ controllers/network_test.go | 32 ++++++++------------------------ logic/dns.go | 2 +- logic/networks.go | 24 +++++++++++++++++++++--- pro/logic/user_mgmt.go | 12 ++++++++---- 5 files changed, 40 insertions(+), 32 deletions(-) diff --git a/controllers/dns_test.go b/controllers/dns_test.go index 4682f5258..d6fc5cf1c 100644 --- a/controllers/dns_test.go +++ b/controllers/dns_test.go @@ -1,6 +1,7 @@ package controller import ( + "fmt" "net" "os" "testing" @@ -440,6 +441,7 @@ func createHost() { func deleteAllDNS(t *testing.T) { dns, err := logic.GetAllDNS() assert.Nil(t, err) + fmt.Println("=====> DNS RECORDS ", dns) for _, record := range dns { err := logic.DeleteDNS(record.Name, record.Network) assert.Nil(t, err) diff --git a/controllers/network_test.go b/controllers/network_test.go index 4320b6e39..6d1a11360 100644 --- a/controllers/network_test.go +++ b/controllers/network_test.go @@ -46,10 +46,8 @@ func TestCreateNetwork(t *testing.T) { deleteAllNetworks() var network models.Network - network.NetID = "skynet1" + network.Name = "skynet1" network.AddressRange = "10.10.0.1/24" - // if tests break - check here (removed displayname) - //network.DisplayName = "mynetwork" _, err := logic.CreateNetwork(network) assert.Nil(t, err) @@ -115,7 +113,7 @@ func TestValidateNetwork(t *testing.T) { { testname: "InvalidAddress", network: models.Network{ - NetID: "skynet", + Name: "skynet", AddressRange: "10.0.0.256", }, errMessage: "Field validation for 'AddressRange' failed on the 'cidrv4' tag", @@ -123,29 +121,15 @@ func TestValidateNetwork(t *testing.T) { { testname: "InvalidAddress6", network: models.Network{ - NetID: "skynet1", + Name: "skynet1", AddressRange6: "2607::ffff/130", }, errMessage: "Field validation for 'AddressRange6' failed on the 'cidrv6' tag", }, - { - testname: "InvalidNetID", - network: models.Network{ - NetID: "with spaces", - }, - errMessage: "Field validation for 'NetID' failed on the 'netid_valid' tag", - }, - { - testname: "NetIDTooLong", - network: models.Network{ - NetID: "LongNetIDNameForMaxCharactersTest", - }, - errMessage: "Field validation for 'NetID' failed on the 'max' tag", - }, { testname: "ListenPortTooLow", network: models.Network{ - NetID: "skynet", + Name: "skynet", DefaultListenPort: 1023, }, errMessage: "Field validation for 'DefaultListenPort' failed on the 'min' tag", @@ -153,7 +137,7 @@ func TestValidateNetwork(t *testing.T) { { testname: "ListenPortTooHigh", network: models.Network{ - NetID: "skynet", + Name: "skynet", DefaultListenPort: 65536, }, errMessage: "Field validation for 'DefaultListenPort' failed on the 'max' tag", @@ -161,7 +145,7 @@ func TestValidateNetwork(t *testing.T) { { testname: "KeepAliveTooBig", network: models.Network{ - NetID: "skynet", + Name: "skynet", DefaultKeepalive: 1010, }, errMessage: "Field validation for 'DefaultKeepalive' failed on the 'max' tag", @@ -207,9 +191,9 @@ func deleteAllNetworks() { func createNet() { var network models.Network - network.NetID = "skynet" + network.Name = "skynet" network.AddressRange = "10.0.0.1/24" - _, err := logic.GetNetwork("skynet") + _, err := logic.GetNetworkByName("skynet") if err != nil { logic.CreateNetwork(network) } diff --git a/logic/dns.go b/logic/dns.go index dd3450a21..7c60c68ee 100644 --- a/logic/dns.go +++ b/logic/dns.go @@ -188,7 +188,7 @@ func GetAllDNS() ([]models.DNSEntry, error) { return []models.DNSEntry{}, err } for _, net := range networks { - netdns, err := GetDNS(net.NetID) + netdns, err := GetDNS(net.Name) if err != nil { return []models.DNSEntry{}, nil } diff --git a/logic/networks.go b/logic/networks.go index 53f80beb5..b95f9c488 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -524,16 +524,34 @@ func UpsertNetwork(net *models.Network) error { return nil } +func GetNetworkByName(name string) (network models.Network, err error) { + networksData, err := database.FetchRecords(database.NETWORKS_TABLE_NAME) + if err != nil { + return network, err + } + for _, networkData := range networksData { + + if err = json.Unmarshal([]byte(networkData), &network); err != nil { + return models.Network{}, err + } + if network.Name == name { + return network, nil + } + + } + return network, errors.New("network not found") +} + // GetNetwork - gets a network from database -func GetNetwork(networkname string) (models.Network, error) { +func GetNetwork(networkID string) (models.Network, error) { var network models.Network if servercfg.CacheEnabled() { - if network, ok := getNetworkFromCache(networkname); ok { + if network, ok := getNetworkFromCache(networkID); ok { return network, nil } } - networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, networkname) + networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, networkID) if err != nil { return network, err } diff --git a/pro/logic/user_mgmt.go b/pro/logic/user_mgmt.go index 2a21a8bdb..c2fb7e7a0 100644 --- a/pro/logic/user_mgmt.go +++ b/pro/logic/user_mgmt.go @@ -143,9 +143,13 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { if netID.String() == "" { return } + network, err := logic.GetNetwork(netID.String()) + if err != nil { + return + } var NetworkAdminPermissionTemplate = models.UserRolePermissionTemplate{ ID: models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkAdmin)), - Name: fmt.Sprintf("%s Admin", netID), + Name: fmt.Sprintf("%s Admin", network.Name), MetaData: fmt.Sprintf("can manage your network `%s` configuration.", netID), Default: true, NetworkID: netID, @@ -155,7 +159,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { var NetworkUserPermissionTemplate = models.UserRolePermissionTemplate{ ID: models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkUser)), - Name: fmt.Sprintf("%s User", netID), + Name: fmt.Sprintf("%s User", network.Name), MetaData: fmt.Sprintf("cannot access the admin console, but can connect to nodes in your network `%s` via Remote Access Client.", netID), Default: true, FullAccess: false, @@ -217,7 +221,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { // create default network groups var NetworkAdminGroup = models.UserGroup{ ID: models.UserGroupID(fmt.Sprintf("%s-%s-grp", netID, models.NetworkAdmin)), - Name: fmt.Sprintf("%s Admin Group", netID), + Name: fmt.Sprintf("%s Admin Group", network.Name), NetworkRoles: map[models.NetworkID]map[models.UserRoleID]struct{}{ netID: { models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkAdmin)): {}, @@ -227,7 +231,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { } var NetworkUserGroup = models.UserGroup{ ID: models.UserGroupID(fmt.Sprintf("%s-%s-grp", netID, models.NetworkUser)), - Name: fmt.Sprintf("%s User Group", netID), + Name: fmt.Sprintf("%s User Group", network.Name), NetworkRoles: map[models.NetworkID]map[models.UserRoleID]struct{}{ netID: { models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkUser)): {}, From 268503373068908210a46dbfef734d6e11561b77 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Wed, 11 Dec 2024 09:55:28 +0400 Subject: [PATCH 14/22] add network name validation --- controllers/dns.go | 6 +++--- logic/dns.go | 27 +++++++++++++++------------ logic/networks.go | 29 ++++++++++------------------- logic/tags.go | 5 +++++ models/tags.go | 11 ++++++----- mq/publishers.go | 4 ++-- 6 files changed, 41 insertions(+), 41 deletions(-) diff --git a/controllers/dns.go b/controllers/dns.go index cc1d70abf..859d36e44 100644 --- a/controllers/dns.go +++ b/controllers/dns.go @@ -49,7 +49,7 @@ func getNodeDNS(w http.ResponseWriter, r *http.Request) { var dns []models.DNSEntry var params = mux.Vars(r) network := params["network"] - dns, err := logic.GetNodeDNS(network) + dns, err := logic.GetNodeDNS(models.NetworkID(network)) if err != nil { logger.Log(0, r.Header.Get("user"), fmt.Sprintf("failed to get node DNS entries for network [%s]: %v", network, err)) @@ -125,7 +125,7 @@ func getDNS(w http.ResponseWriter, r *http.Request) { var dns []models.DNSEntry var params = mux.Vars(r) network := params["network"] - dns, err := logic.GetDNS(network) + dns, err := logic.GetDNS(models.NetworkID(network)) if err != nil { logger.Log(0, r.Header.Get("user"), fmt.Sprintf("failed to get all DNS entries for network [%s]: %v", network, err.Error())) @@ -298,7 +298,7 @@ func syncDNS(w http.ResponseWriter, r *http.Request) { } var params = mux.Vars(r) netID := params["network"] - k, err := logic.GetDNS(netID) + k, err := logic.GetDNS(models.NetworkID(netID)) if err == nil && len(k) > 0 { err = mq.PushSyncDNS(k) } diff --git a/logic/dns.go b/logic/dns.go index 7c60c68ee..b61559364 100644 --- a/logic/dns.go +++ b/logic/dns.go @@ -28,7 +28,7 @@ func SetDNS() error { for _, net := range networks { corefilestring = corefilestring + net.NetID + " " - dns, err := GetDNS(net.NetID) + dns, err := GetDNS(models.NetworkID(net.NetID)) if err != nil && !database.IsEmptyRecord(err) { return err } @@ -58,13 +58,13 @@ func SetDNS() error { } // GetDNS - gets the DNS of a current network -func GetDNS(network string) ([]models.DNSEntry, error) { +func GetDNS(networkID models.NetworkID) ([]models.DNSEntry, error) { - dns, err := GetNodeDNS(network) + dns, err := GetNodeDNS(networkID) if err != nil && !database.IsEmptyRecord(err) { return dns, err } - customdns, err := GetCustomDNS(network) + customdns, err := GetCustomDNS(networkID.String()) if err != nil && !database.IsEmptyRecord(err) { return dns, err } @@ -96,17 +96,20 @@ func GetExtclientDNS() []models.DNSEntry { } // GetNodeDNS - gets the DNS of a network node -func GetNodeDNS(network string) ([]models.DNSEntry, error) { +func GetNodeDNS(networkID models.NetworkID) ([]models.DNSEntry, error) { var dns []models.DNSEntry - - nodes, err := GetNetworkNodes(network) + net, err := GetNetwork(networkID.String()) + if err != nil { + return []models.DNSEntry{}, err + } + nodes, err := GetNetworkNodes(networkID.String()) if err != nil { return dns, err } for _, node := range nodes { - if node.Network != network { + if node.Network != networkID.String() { continue } host, err := GetHost(node.HostID.String()) @@ -114,8 +117,8 @@ func GetNodeDNS(network string) ([]models.DNSEntry, error) { continue } var entry = models.DNSEntry{} - entry.Name = fmt.Sprintf("%s.%s", host.Name, network) - entry.Network = network + entry.Name = fmt.Sprintf("%s.%s", host.Name, net.Name) + entry.Network = net.NetID if node.Address.IP != nil { entry.Address = node.Address.IP.String() } @@ -188,7 +191,7 @@ func GetAllDNS() ([]models.DNSEntry, error) { return []models.DNSEntry{}, err } for _, net := range networks { - netdns, err := GetDNS(net.Name) + netdns, err := GetDNS(models.NetworkID(net.NetID)) if err != nil { return []models.DNSEntry{}, nil } @@ -202,7 +205,7 @@ func GetDNSEntryNum(domain string, network string) (int, error) { num := 0 - entries, err := GetDNS(network) + entries, err := GetDNS(models.NetworkID(network)) if err != nil { return 0, err } diff --git a/logic/networks.go b/logic/networks.go index b95f9c488..17c6cd355 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net" + "regexp" "sort" "strings" "sync" @@ -230,7 +231,7 @@ func CreateNetwork(network models.Network) (models.Network, error) { network.SetDefaults() network.SetNodesLastModified() network.SetNetworkLastModified() - + network.Name = strings.ReplaceAll(network.Name, " ", "-") err := ValidateNetwork(&network, false) if err != nil { //logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) @@ -483,6 +484,7 @@ func IsNetworkNameUnique(network *models.Network) (bool, error) { // UpdateNetwork - updates a network with another network's fields func UpdateNetwork(currentNetwork *models.Network, newNetwork *models.Network) (bool, bool, bool, error) { + newNetwork.Name = strings.ReplaceAll(newNetwork.Name, " ", "-") if err := ValidateNetwork(newNetwork, true); err != nil { return false, false, false, err } @@ -561,16 +563,10 @@ func GetNetwork(networkID string) (models.Network, error) { return network, nil } -// NetIDInNetworkCharSet - checks if a netid of a network uses valid characters -func NetIDInNetworkCharSet(network *models.Network) bool { - charset := "abcdefghijklmnopqrstuvwxyz1234567890-_" - - for _, char := range network.NetID { - if !strings.Contains(charset, string(char)) { - return false - } - } - return true +// IsNetworkNameValid - checks if a netid of a network uses valid characters +func IsNetworkNameValid(network *models.Network) bool { + re := regexp.MustCompile(`^[A-Za-z0-9-]+$`) + return re.MatchString(network.Name) } // Validate - validates fields of an network struct @@ -580,7 +576,9 @@ func ValidateNetwork(network *models.Network, isUpdate bool) error { if !isFieldUnique { return errors.New("duplicate network name") } - // + if !IsNetworkNameValid(network) { + return errors.New("invalid input. Only uppercase letters (A-Z), lowercase letters (a-z), numbers (0-9), and the minus sign (-) are allowed") + } _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool { return validation.CheckYesOrNo(fl) }) @@ -594,13 +592,6 @@ func ValidateNetwork(network *models.Network, isUpdate bool) error { return err } -// ParseNetwork - parses a network into a model -func ParseNetwork(value string) (models.Network, error) { - var network models.Network - err := json.Unmarshal([]byte(value), &network) - return network, err -} - // SaveNetwork - save network struct to database func SaveNetwork(network *models.Network) error { data, err := json.Marshal(network) diff --git a/logic/tags.go b/logic/tags.go index 7cdf0f324..1b2bdfcc0 100644 --- a/logic/tags.go +++ b/logic/tags.go @@ -85,9 +85,14 @@ func ListTagsWithNodes(netID models.NetworkID) ([]models.TagListResp, error) { if err != nil { return []models.TagListResp{}, err } + network, err := GetNetwork(netID.String()) + if err != nil { + return []models.TagListResp{}, err + } tagsNodeMap := GetTagMapWithNodesByNetwork(netID) resp := []models.TagListResp{} for _, tagI := range tags { + tagI.NetworkName = network.Name tagRespI := models.TagListResp{ Tag: tagI, UsedByCnt: len(tagsNodeMap[tagI.ID]), diff --git a/models/tags.go b/models/tags.go index 9fcb449da..9be767321 100644 --- a/models/tags.go +++ b/models/tags.go @@ -20,11 +20,12 @@ func (t Tag) GetIDFromName() string { } type Tag struct { - ID TagID `json:"id"` - TagName string `json:"tag_name"` - Network NetworkID `json:"network"` - CreatedBy string `json:"created_by"` - CreatedAt time.Time `json:"created_at"` + ID TagID `json:"id"` + TagName string `json:"tag_name"` + Network NetworkID `json:"network"` + NetworkName string `json:"network_name"` + CreatedBy string `json:"created_by"` + CreatedAt time.Time `json:"created_at"` } type CreateTagReq struct { diff --git a/mq/publishers.go b/mq/publishers.go index 3b47390a8..f58be1de2 100644 --- a/mq/publishers.go +++ b/mq/publishers.go @@ -256,7 +256,7 @@ func sendPeers() { func SendDNSSyncByNetwork(network string) error { - k, err := logic.GetDNS(network) + k, err := logic.GetDNS(models.NetworkID(network)) if err == nil && len(k) > 0 { err = PushSyncDNS(k) if err != nil { @@ -272,7 +272,7 @@ func sendDNSSync() error { networks, err := logic.GetNetworks() if err == nil && len(networks) > 0 { for _, v := range networks { - k, err := logic.GetDNS(v.NetID) + k, err := logic.GetDNS(models.NetworkID(v.NetID)) if err == nil && len(k) > 0 { err = PushSyncDNS(k) if err != nil { From e916d058203428eb976a94a9bca5041ff5d45019 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Wed, 11 Dec 2024 13:54:30 +0400 Subject: [PATCH 15/22] sync DNS entries on network name update --- controllers/network.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/controllers/network.go b/controllers/network.go index e10ec341a..7a4e91a01 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -613,7 +613,11 @@ func updateNetwork(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } - + if payload.Name != netOld1.Name { + if servercfg.GetManageDNS() { + mq.SendDNSSyncByNetwork(payload.NetID) + } + } slog.Info("updated network", "network", payload.NetID, "user", r.Header.Get("user")) w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(payload) From 0c4f7eb3448348016ca14b303abf86d343947f4f Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Wed, 11 Dec 2024 16:53:10 +0400 Subject: [PATCH 16/22] update default network roles and groups --- controllers/network.go | 1 + 1 file changed, 1 insertion(+) diff --git a/controllers/network.go b/controllers/network.go index 7a4e91a01..c65ea2648 100644 --- a/controllers/network.go +++ b/controllers/network.go @@ -617,6 +617,7 @@ func updateNetwork(w http.ResponseWriter, r *http.Request) { if servercfg.GetManageDNS() { mq.SendDNSSyncByNetwork(payload.NetID) } + logic.CreateDefaultNetworkRolesAndGroups(models.NetworkID(payload.NetID)) } slog.Info("updated network", "network", payload.NetID, "user", r.Header.Get("user")) w.WriteHeader(http.StatusOK) From e68454733a615f11c7ed0090748231efdfece5be Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 12 Dec 2024 10:48:59 +0400 Subject: [PATCH 17/22] add network name to common node --- models/node.go | 1 + 1 file changed, 1 insertion(+) diff --git a/models/node.go b/models/node.go index c9e55e5d5..af52c9c4f 100644 --- a/models/node.go +++ b/models/node.go @@ -68,6 +68,7 @@ type CommonNode struct { ID uuid.UUID `json:"id" yaml:"id"` HostID uuid.UUID `json:"hostid" yaml:"hostid"` Network string `json:"network" yaml:"network"` + NetworkName string `json:"network_name" yaml:"network_name"` NetworkRange net.IPNet `json:"networkrange" yaml:"networkrange" swaggertype:"primitive,integer"` NetworkRange6 net.IPNet `json:"networkrange6" yaml:"networkrange6" swaggertype:"primitive,number"` Server string `json:"server" yaml:"server"` From 28bd5b890b401f3d4c8cf642d21773f6449cf8d1 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 12 Dec 2024 10:57:06 +0400 Subject: [PATCH 18/22] add network name to common node --- controllers/node.go | 2 ++ models/node.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/controllers/node.go b/controllers/node.go index 904f6375b..11d439e28 100644 --- a/controllers/node.go +++ b/controllers/node.go @@ -430,6 +430,8 @@ func getNode(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal")) return } + net, _ := logic.GetNetwork(node.Network) + node.NetworkName = net.Name server := servercfg.GetServerInfo() response := models.NodeGet{ Node: node, diff --git a/models/node.go b/models/node.go index af52c9c4f..c48155964 100644 --- a/models/node.go +++ b/models/node.go @@ -68,7 +68,7 @@ type CommonNode struct { ID uuid.UUID `json:"id" yaml:"id"` HostID uuid.UUID `json:"hostid" yaml:"hostid"` Network string `json:"network" yaml:"network"` - NetworkName string `json:"network_name" yaml:"network_name"` + NetworkName string `json:"network_name" yaml:"network_name"` NetworkRange net.IPNet `json:"networkrange" yaml:"networkrange" swaggertype:"primitive,integer"` NetworkRange6 net.IPNet `json:"networkrange6" yaml:"networkrange6" swaggertype:"primitive,number"` Server string `json:"server" yaml:"server"` From c3f2c50e4a9cb932254e211a8f57ac31a835be27 Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 12 Dec 2024 15:48:16 +0400 Subject: [PATCH 19/22] add dns entry validation check --- logic/dns.go | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/logic/dns.go b/logic/dns.go index b61559364..05c33904e 100644 --- a/logic/dns.go +++ b/logic/dns.go @@ -2,6 +2,7 @@ package logic import ( "encoding/json" + "errors" "fmt" "os" "regexp" @@ -11,6 +12,7 @@ import ( "github.com/gravitl/netmaker/database" "github.com/gravitl/netmaker/logger" "github.com/gravitl/netmaker/models" + "github.com/gravitl/netmaker/servercfg" "github.com/txn2/txeh" ) @@ -107,7 +109,7 @@ func GetNodeDNS(networkID models.NetworkID) ([]models.DNSEntry, error) { if err != nil { return dns, err } - + defaultDomain := servercfg.GetDefaultDomain() for _, node := range nodes { if node.Network != networkID.String() { continue @@ -117,7 +119,7 @@ func GetNodeDNS(networkID models.NetworkID) ([]models.DNSEntry, error) { continue } var entry = models.DNSEntry{} - entry.Name = fmt.Sprintf("%s.%s", host.Name, net.Name) + entry.Name = fmt.Sprintf("%s.%s.%s", host.Name, net.Name, defaultDomain) entry.Network = net.NetID if node.Address.IP != nil { entry.Address = node.Address.IP.String() @@ -227,9 +229,17 @@ func SortDNSEntrys(unsortedDNSEntrys []models.DNSEntry) { }) } +// IsNetworkNameValid - checks if a netid of a network uses valid characters +func IsDNSEntryValid(d string) bool { + re := regexp.MustCompile(`^[A-Za-z0-9-.]+$`) + return re.MatchString(d) +} + // ValidateDNSCreate - checks if an entry is valid func ValidateDNSCreate(entry models.DNSEntry) error { - + if !IsDNSEntryValid(entry.Name) { + return errors.New("invalid input. Only uppercase letters (A-Z), lowercase letters (a-z), numbers (0-9), minus sign (-) and dots (.) are allowed") + } v := validator.New() _ = v.RegisterValidation("whitespace", func(f1 validator.FieldLevel) bool { From 104af4cc98aa23661244749ae67fdcbf603ce89d Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 12 Dec 2024 15:53:52 +0400 Subject: [PATCH 20/22] append default domain if not append --- controllers/dns.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/controllers/dns.go b/controllers/dns.go index 859d36e44..651f2e381 100644 --- a/controllers/dns.go +++ b/controllers/dns.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "strings" "github.com/gorilla/mux" "github.com/gravitl/netmaker/database" @@ -162,7 +163,10 @@ func createDNS(w http.ResponseWriter, r *http.Request) { logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest")) return } - + // check if default domain is appended if not append + if !strings.HasSuffix(entry.Name, servercfg.GetDefaultDomain()) { + entry.Name += servercfg.GetDefaultDomain() + } entry, err = logic.CreateDNS(entry) if err != nil { logger.Log(0, r.Header.Get("user"), From 725da06b18b26c7593189042d4688c032276a36b Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Thu, 12 Dec 2024 16:08:57 +0400 Subject: [PATCH 21/22] add dot for default domain --- controllers/dns.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controllers/dns.go b/controllers/dns.go index 651f2e381..524d2b4c6 100644 --- a/controllers/dns.go +++ b/controllers/dns.go @@ -165,7 +165,7 @@ func createDNS(w http.ResponseWriter, r *http.Request) { } // check if default domain is appended if not append if !strings.HasSuffix(entry.Name, servercfg.GetDefaultDomain()) { - entry.Name += servercfg.GetDefaultDomain() + entry.Name += "." + servercfg.GetDefaultDomain() } entry, err = logic.CreateDNS(entry) if err != nil { From 125f8a64266dc64f8c196af3a6bfba8f902e249f Mon Sep 17 00:00:00 2001 From: abhishek9686 Date: Sun, 15 Dec 2024 19:42:31 +0400 Subject: [PATCH 22/22] update user roles and group description with network names --- pro/logic/user_mgmt.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pro/logic/user_mgmt.go b/pro/logic/user_mgmt.go index c2fb7e7a0..e0df0296f 100644 --- a/pro/logic/user_mgmt.go +++ b/pro/logic/user_mgmt.go @@ -150,7 +150,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { var NetworkAdminPermissionTemplate = models.UserRolePermissionTemplate{ ID: models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkAdmin)), Name: fmt.Sprintf("%s Admin", network.Name), - MetaData: fmt.Sprintf("can manage your network `%s` configuration.", netID), + MetaData: fmt.Sprintf("can manage your network `%s` configuration.", network.Name), Default: true, NetworkID: netID, FullAccess: true, @@ -160,7 +160,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { var NetworkUserPermissionTemplate = models.UserRolePermissionTemplate{ ID: models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkUser)), Name: fmt.Sprintf("%s User", network.Name), - MetaData: fmt.Sprintf("cannot access the admin console, but can connect to nodes in your network `%s` via Remote Access Client.", netID), + MetaData: fmt.Sprintf("cannot access the admin console, but can connect to nodes in your network `%s` via Remote Access Client.", network.Name), Default: true, FullAccess: false, NetworkID: netID, @@ -227,7 +227,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkAdmin)): {}, }, }, - MetaData: fmt.Sprintf("can manage your network `%s` configuration including adding and removing devices.", netID), + MetaData: fmt.Sprintf("can manage your network `%s` configuration including adding and removing devices.", network.Name), } var NetworkUserGroup = models.UserGroup{ ID: models.UserGroupID(fmt.Sprintf("%s-%s-grp", netID, models.NetworkUser)), @@ -237,7 +237,7 @@ func CreateDefaultNetworkRolesAndGroups(netID models.NetworkID) { models.UserRoleID(fmt.Sprintf("%s-%s", netID, models.NetworkUser)): {}, }, }, - MetaData: fmt.Sprintf("cannot access the admin console, but can connect to nodes in your network `%s` via Remote Access Client.", netID), + MetaData: fmt.Sprintf("cannot access the admin console, but can connect to nodes in your network `%s` via Remote Access Client.", network.Name), } d, _ = json.Marshal(NetworkAdminGroup) database.Insert(NetworkAdminGroup.ID.String(), string(d), database.USER_GROUPS_TABLE_NAME)