mirror of
https://github.com/gravitl/netmaker.git
synced 2025-10-05 08:47:35 +08:00
massive number of changes to schema and error handling.
This commit is contained in:
@@ -72,27 +72,27 @@ func grpcAuthorize(ctx context.Context) error {
|
||||
|
||||
authToken := authHeader[0]
|
||||
|
||||
mac, group, err := functions.VerifyToken(authToken)
|
||||
mac, network, err := functions.VerifyToken(authToken)
|
||||
|
||||
if err != nil { return err }
|
||||
|
||||
groupexists, err := functions.GroupExists(group)
|
||||
networkexists, err := functions.NetworkExists(network)
|
||||
|
||||
if err != nil {
|
||||
return status.Errorf(codes.Unauthenticated, "Unauthorized. Group does not exist: " + group)
|
||||
return status.Errorf(codes.Unauthenticated, "Unauthorized. Network does not exist: " + network)
|
||||
|
||||
}
|
||||
emptynode := models.Node{}
|
||||
node, err := functions.GetNodeByMacAddress(group, mac)
|
||||
node, err := functions.GetNodeByMacAddress(network, mac)
|
||||
if err != nil || node == emptynode {
|
||||
return status.Errorf(codes.Unauthenticated, "Node does not exist.")
|
||||
}
|
||||
|
||||
//check that the request is for a valid group
|
||||
//if (groupCheck && !groupexists) || err != nil {
|
||||
if (!groupexists) {
|
||||
//check that the request is for a valid network
|
||||
//if (networkCheck && !networkexists) || err != nil {
|
||||
if (!networkexists) {
|
||||
|
||||
return status.Errorf(codes.Unauthenticated, "Group does not exist.")
|
||||
return status.Errorf(codes.Unauthenticated, "Network does not exist.")
|
||||
|
||||
} else {
|
||||
return nil
|
||||
@@ -124,7 +124,7 @@ func (s *NodeServiceServer) Login(ctx context.Context, req *nodepb.LoginRequest)
|
||||
//Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
var err = collection.FindOne(ctx, bson.M{ "macaddress": macaddress, "group": network}).Decode(&result)
|
||||
var err = collection.FindOne(ctx, bson.M{ "macaddress": macaddress, "network": network}).Decode(&result)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -140,7 +140,7 @@ func (s *NodeServiceServer) Login(ctx context.Context, req *nodepb.LoginRequest)
|
||||
return nil, err
|
||||
} else {
|
||||
//Create a new JWT for the node
|
||||
tokenString, err := functions.CreateJWT(macaddress, result.Group)
|
||||
tokenString, err := functions.CreateJWT(macaddress, result.Network)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
)
|
||||
|
||||
func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
||||
func GetPeersList(networkName string) ([]models.PeersResponse, error) {
|
||||
|
||||
var peers []models.PeersResponse
|
||||
|
||||
@@ -25,8 +25,8 @@ func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
//Get all nodes in the relevant group which are NOT in pending state
|
||||
filter := bson.M{"group": groupName, "ispending": false}
|
||||
//Get all nodes in the relevant network which are NOT in pending state
|
||||
filter := bson.M{"network": networkName, "ispending": false}
|
||||
cur, err := collection.Find(ctx, filter)
|
||||
|
||||
if err != nil {
|
||||
@@ -59,18 +59,18 @@ func GetPeersList(groupName string) ([]models.PeersResponse, error) {
|
||||
}
|
||||
|
||||
|
||||
func ValidateNode(operation string, groupName string, node models.Node) error {
|
||||
func ValidateNode(operation string, networkName string, node models.Node) error {
|
||||
|
||||
v := validator.New()
|
||||
|
||||
_ = v.RegisterValidation("endpoint_check", func(fl validator.FieldLevel) bool {
|
||||
//var isFieldUnique bool = functions.IsFieldUnique(groupName, "endpoint", node.Endpoint)
|
||||
//var isFieldUnique bool = functions.IsFieldUnique(networkName, "endpoint", node.Endpoint)
|
||||
isIpv4 := functions.IsIpv4Net(node.Endpoint)
|
||||
notEmptyCheck := node.Endpoint != ""
|
||||
return (notEmptyCheck && isIpv4) || operation == "update"
|
||||
})
|
||||
_ = v.RegisterValidation("localaddress_check", func(fl validator.FieldLevel) bool {
|
||||
//var isFieldUnique bool = functions.IsFieldUnique(groupName, "endpoint", node.Endpoint)
|
||||
//var isFieldUnique bool = functions.IsFieldUnique(networkName, "endpoint", node.Endpoint)
|
||||
isIpv4 := functions.IsIpv4Net(node.LocalAddress)
|
||||
notEmptyCheck := node.LocalAddress != ""
|
||||
return (notEmptyCheck && isIpv4) || operation == "update"
|
||||
@@ -78,7 +78,7 @@ func ValidateNode(operation string, groupName string, node models.Node) error {
|
||||
|
||||
|
||||
_ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
|
||||
var isFieldUnique bool = functions.IsFieldUnique(groupName, "macaddress", node.MacAddress)
|
||||
var isFieldUnique bool = functions.IsFieldUnique(networkName, "macaddress", node.MacAddress)
|
||||
return isFieldUnique || operation == "update"
|
||||
})
|
||||
|
||||
@@ -92,8 +92,8 @@ func ValidateNode(operation string, groupName string, node models.Node) error {
|
||||
return isvalid
|
||||
})
|
||||
|
||||
_ = v.RegisterValidation("group_exists", func(fl validator.FieldLevel) bool {
|
||||
_, err := node.GetGroup()
|
||||
_ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
|
||||
_, err := node.GetNetwork()
|
||||
return err == nil
|
||||
})
|
||||
_ = v.RegisterValidation("pubkey_check", func(fl validator.FieldLevel) bool {
|
||||
@@ -122,12 +122,12 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
||||
//Question: Is there a better way of doing this than a bunch of "if" statements? probably...
|
||||
//Eventually, lets have a better way to check if any of the fields are filled out...
|
||||
queryMac := node.MacAddress
|
||||
queryGroup := node.Group
|
||||
notifygroup := false
|
||||
queryNetwork := node.Network
|
||||
notifynetwork := false
|
||||
|
||||
if nodechange.Address != "" {
|
||||
node.Address = nodechange.Address
|
||||
notifygroup = true
|
||||
notifynetwork = true
|
||||
}
|
||||
if nodechange.Name != "" {
|
||||
node.Name = nodechange.Name
|
||||
@@ -155,7 +155,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
||||
}
|
||||
if nodechange.Endpoint != "" {
|
||||
node.Endpoint = nodechange.Endpoint
|
||||
notifygroup = true
|
||||
notifynetwork = true
|
||||
}
|
||||
if nodechange.SaveConfig != nil {
|
||||
node.SaveConfig = nodechange.SaveConfig
|
||||
@@ -180,7 +180,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
||||
if nodechange.PublicKey != "" {
|
||||
node.PublicKey = nodechange.PublicKey
|
||||
node.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
notifygroup = true
|
||||
notifynetwork = true
|
||||
}
|
||||
|
||||
//collection := mongoconn.ConnectDB()
|
||||
@@ -189,7 +189,7 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"macaddress": queryMac, "group": queryGroup}
|
||||
filter := bson.M{"macaddress": queryMac, "network": queryNetwork}
|
||||
|
||||
node.SetLastModified()
|
||||
|
||||
@@ -221,24 +221,24 @@ func UpdateNode(nodechange models.Node, node models.Node) (models.Node, error) {
|
||||
return nodeupdate, errN
|
||||
}
|
||||
|
||||
returnnode, errN := GetNode(node.MacAddress, node.Group)
|
||||
returnnode, errN := GetNode(node.MacAddress, node.Network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
if notifygroup {
|
||||
errN = SetGroupNodesLastModified(node.Group)
|
||||
if notifynetwork {
|
||||
errN = SetNetworkNodesLastModified(node.Network)
|
||||
}
|
||||
|
||||
return returnnode, errN
|
||||
}
|
||||
|
||||
func DeleteNode(macaddress string, group string) (bool, error) {
|
||||
func DeleteNode(macaddress string, network string) (bool, error) {
|
||||
|
||||
deleted := false
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
|
||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
||||
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -252,13 +252,13 @@ func DeleteNode(macaddress string, group string) (bool, error) {
|
||||
|
||||
defer cancel()
|
||||
|
||||
err = SetGroupNodesLastModified(group)
|
||||
fmt.Println("Deleted node " + macaddress + " from group " + group)
|
||||
err = SetNetworkNodesLastModified(network)
|
||||
fmt.Println("Deleted node " + macaddress + " from network " + network)
|
||||
|
||||
return deleted, err
|
||||
}
|
||||
|
||||
func GetNode(macaddress string, group string) (models.Node, error) {
|
||||
func GetNode(macaddress string, network string) (models.Node, error) {
|
||||
|
||||
var node models.Node
|
||||
|
||||
@@ -266,7 +266,7 @@ func GetNode(macaddress string, group string) (models.Node, error) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
||||
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&node)
|
||||
|
||||
defer cancel()
|
||||
@@ -274,7 +274,7 @@ func GetNode(macaddress string, group string) (models.Node, error) {
|
||||
return node, err
|
||||
}
|
||||
|
||||
func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
||||
func CreateNode(node models.Node, networkName string) (models.Node, error) {
|
||||
|
||||
//encrypt that password so we never see it again
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(node.Password), 5)
|
||||
@@ -286,7 +286,7 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
||||
node.Password = string(hash)
|
||||
|
||||
|
||||
node.Group = groupName
|
||||
node.Network = networkName
|
||||
|
||||
//node.SetDefaults()
|
||||
//Umm, why am I doing this again?
|
||||
@@ -296,9 +296,9 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
||||
node.SetDefaults()
|
||||
|
||||
//Another DB call here...Inefficient
|
||||
//Anyways, this scrolls through all the IP Addresses in the group range and checks against nodes
|
||||
//Anyways, this scrolls through all the IP Addresses in the network range and checks against nodes
|
||||
//until one is open and then returns it
|
||||
node.Address, err = functions.UniqueAddress(groupName)
|
||||
node.Address, err = functions.UniqueAddress(networkName)
|
||||
|
||||
if err != nil {/*
|
||||
errorResponse := models.ErrorResponse{
|
||||
@@ -317,7 +317,7 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
||||
node.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
|
||||
//Create a JWT for the node
|
||||
tokenString, _ := functions.CreateJWT(node.MacAddress, groupName)
|
||||
tokenString, _ := functions.CreateJWT(node.MacAddress, networkName)
|
||||
|
||||
if tokenString == "" {
|
||||
//returnErrorResponse(w, r, errorResponse)
|
||||
@@ -341,26 +341,26 @@ func CreateNode(node models.Node, groupName string) (models.Node, error) {
|
||||
//return response for if node is pending
|
||||
if !node.IsPending {
|
||||
|
||||
functions.DecrimentKey(node.Group, node.AccessKey)
|
||||
functions.DecrimentKey(node.Network, node.AccessKey)
|
||||
|
||||
}
|
||||
|
||||
SetGroupNodesLastModified(node.Group)
|
||||
SetNetworkNodesLastModified(node.Network)
|
||||
|
||||
return node, err
|
||||
}
|
||||
|
||||
func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, error) {
|
||||
func NodeCheckIn(node models.Node, networkName string) (models.CheckInResponse, error) {
|
||||
|
||||
var response models.CheckInResponse
|
||||
|
||||
parentgroup, err := functions.GetParentGroup(groupName)
|
||||
parentnetwork, err := functions.GetParentNetwork(networkName)
|
||||
if err != nil{
|
||||
err = fmt.Errorf("%w; Couldnt retrieve Group " + groupName + ": ", err)
|
||||
err = fmt.Errorf("%w; Couldnt retrieve Network " + networkName + ": ", err)
|
||||
return response, err
|
||||
}
|
||||
|
||||
parentnode, err := functions.GetNodeByMacAddress(groupName, node.MacAddress)
|
||||
parentnode, err := functions.GetNodeByMacAddress(networkName, node.MacAddress)
|
||||
if err != nil{
|
||||
err = fmt.Errorf("%w; Couldnt Get Node " + node.MacAddress, err)
|
||||
return response, err
|
||||
@@ -371,9 +371,9 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
||||
return response, err
|
||||
}
|
||||
|
||||
grouplm := parentgroup.GroupLastModified
|
||||
peerslm := parentgroup.NodesLastModified
|
||||
gkeyupdate := parentgroup.KeyUpdateTimeStamp
|
||||
networklm := parentnetwork.NetworkLastModified
|
||||
peerslm := parentnetwork.NodesLastModified
|
||||
gkeyupdate := parentnetwork.KeyUpdateTimeStamp
|
||||
nkeyupdate := parentnode.KeyUpdateTimeStamp
|
||||
peerlistlm := parentnode.LastPeerUpdate
|
||||
parentnodelm := parentnode.LastModified
|
||||
@@ -383,7 +383,7 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
||||
response.NeedConfigUpdate = true
|
||||
}
|
||||
|
||||
if parentnodelm < grouplm {
|
||||
if parentnodelm < networklm {
|
||||
response.NeedConfigUpdate = true
|
||||
}
|
||||
if peerlistlm < peerslm {
|
||||
@@ -394,7 +394,7 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
||||
}
|
||||
if time.Now().Unix() > parentnode.ExpirationDateTime {
|
||||
response.NeedDelete = true
|
||||
_, err = DeleteNode(node.MacAddress, groupName)
|
||||
_, err = DeleteNode(node.MacAddress, networkName)
|
||||
} else {
|
||||
err = TimestampNode(parentnode, true, false, false)
|
||||
|
||||
@@ -408,16 +408,16 @@ func NodeCheckIn(node models.Node, groupName string) (models.CheckInResponse, er
|
||||
return response, err
|
||||
}
|
||||
|
||||
func SetGroupNodesLastModified(groupName string) error {
|
||||
func SetNetworkNodesLastModified(networkName string) error {
|
||||
|
||||
timestamp := time.Now().Unix()
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"nameid": groupName}
|
||||
filter := bson.M{"netid": networkName}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
@@ -453,7 +453,7 @@ func TimestampNode(node models.Node, updatecheckin bool, updatepeers bool, updat
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"macaddress": node.MacAddress, "group": node.Group}
|
||||
filter := bson.M{"macaddress": node.MacAddress, "network": node.Network}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
|
@@ -27,7 +27,7 @@ func HandleRESTRequests(wg *sync.WaitGroup) {
|
||||
|
||||
nodeHandlers(r)
|
||||
userHandlers(r)
|
||||
groupHandlers(r)
|
||||
networkHandlers(r)
|
||||
fileHandlers(r)
|
||||
serverHandlers(r)
|
||||
|
||||
|
@@ -19,20 +19,20 @@ import (
|
||||
"github.com/gravitl/netmaker/config"
|
||||
)
|
||||
|
||||
func groupHandlers(r *mux.Router) {
|
||||
r.HandleFunc("/api/groups", securityCheck(http.HandlerFunc(getGroups))).Methods("GET")
|
||||
r.HandleFunc("/api/groups", securityCheck(http.HandlerFunc(createGroup))).Methods("POST")
|
||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(getGroup))).Methods("GET")
|
||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(updateGroup))).Methods("PUT")
|
||||
r.HandleFunc("/api/groups/{groupname}", securityCheck(http.HandlerFunc(deleteGroup))).Methods("DELETE")
|
||||
r.HandleFunc("/api/groups/{groupname}/keyupdate", securityCheck(http.HandlerFunc(keyUpdate))).Methods("POST")
|
||||
r.HandleFunc("/api/groups/{groupname}/keys", securityCheck(http.HandlerFunc(createAccessKey))).Methods("POST")
|
||||
r.HandleFunc("/api/groups/{groupname}/keys", securityCheck(http.HandlerFunc(getAccessKeys))).Methods("GET")
|
||||
r.HandleFunc("/api/groups/{groupname}/keys/{name}", securityCheck(http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
|
||||
func networkHandlers(r *mux.Router) {
|
||||
r.HandleFunc("/api/networks", securityCheck(http.HandlerFunc(getNetworks))).Methods("GET")
|
||||
r.HandleFunc("/api/networks", securityCheck(http.HandlerFunc(createNetwork))).Methods("POST")
|
||||
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(getNetwork))).Methods("GET")
|
||||
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(updateNetwork))).Methods("PUT")
|
||||
r.HandleFunc("/api/networks/{networkname}", securityCheck(http.HandlerFunc(deleteNetwork))).Methods("DELETE")
|
||||
r.HandleFunc("/api/networks/{networkname}/keyupdate", securityCheck(http.HandlerFunc(keyUpdate))).Methods("POST")
|
||||
r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(http.HandlerFunc(createAccessKey))).Methods("POST")
|
||||
r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(http.HandlerFunc(getAccessKeys))).Methods("GET")
|
||||
r.HandleFunc("/api/networks/{networkname}/keys/{name}", securityCheck(http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
|
||||
}
|
||||
|
||||
//Security check is middleware for every function and just checks to make sure that its the master calling
|
||||
//Only admin should have access to all these group-level actions
|
||||
//Only admin should have access to all these network-level actions
|
||||
//or maybe some Users once implemented
|
||||
func securityCheck(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -41,14 +41,14 @@ func securityCheck(next http.Handler) http.HandlerFunc {
|
||||
}
|
||||
|
||||
var params = mux.Vars(r)
|
||||
hasgroup := params["groupname"] != ""
|
||||
groupexists, err := functions.GroupExists(params["groupname"])
|
||||
hasnetwork := params["networkname"] != ""
|
||||
networkexists, err := functions.NetworkExists(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||
return
|
||||
} else if hasgroup && !groupexists {
|
||||
} else if hasnetwork && !networkexists {
|
||||
errorResponse = models.ErrorResponse{
|
||||
Code: http.StatusNotFound, Message: "W1R3: This group does not exist.",
|
||||
Code: http.StatusNotFound, Message: "W1R3: This network does not exist.",
|
||||
}
|
||||
returnErrorResponse(w, r, errorResponse)
|
||||
return
|
||||
@@ -87,22 +87,22 @@ func authenticateMaster(tokenString string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
//simple get all groups function
|
||||
func getGroups(w http.ResponseWriter, r *http.Request) {
|
||||
//simple get all networks function
|
||||
func getNetworks(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
groups, err := functions.ListGroups()
|
||||
networks, err := functions.ListNetworks()
|
||||
|
||||
if err != nil {
|
||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||
return
|
||||
} else {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(groups)
|
||||
json.NewEncoder(w).Encode(networks)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func validateGroup(operation string, group models.Group) error {
|
||||
func validateNetwork(operation string, network models.Network) error {
|
||||
|
||||
v := validator.New()
|
||||
|
||||
@@ -112,26 +112,26 @@ func validateGroup(operation string, group models.Group) error {
|
||||
})
|
||||
|
||||
_ = v.RegisterValidation("privaterange_valid", func(fl validator.FieldLevel) bool {
|
||||
isvalid := !*group.IsPrivate || functions.IsIpv4CIDR(fl.Field().String())
|
||||
isvalid := !*network.IsPrivate || functions.IsIpv4CIDR(fl.Field().String())
|
||||
return isvalid
|
||||
})
|
||||
|
||||
_ = v.RegisterValidation("nameid_valid", func(fl validator.FieldLevel) bool {
|
||||
_ = v.RegisterValidation("netid_valid", func(fl validator.FieldLevel) bool {
|
||||
isFieldUnique := false
|
||||
inCharSet := false
|
||||
if operation == "update" { isFieldUnique = true } else{
|
||||
isFieldUnique, _ = functions.IsGroupNameUnique(fl.Field().String())
|
||||
inCharSet = functions.NameInGroupCharSet(fl.Field().String())
|
||||
isFieldUnique, _ = functions.IsNetworkNameUnique(fl.Field().String())
|
||||
inCharSet = functions.NameInNetworkCharSet(fl.Field().String())
|
||||
}
|
||||
return isFieldUnique && inCharSet
|
||||
})
|
||||
|
||||
_ = v.RegisterValidation("displayname_unique", func(fl validator.FieldLevel) bool {
|
||||
isFieldUnique, _ := functions.IsGroupDisplayNameUnique(fl.Field().String())
|
||||
isFieldUnique, _ := functions.IsNetworkDisplayNameUnique(fl.Field().String())
|
||||
return isFieldUnique || operation == "update"
|
||||
})
|
||||
|
||||
err := v.Struct(group)
|
||||
err := v.Struct(network)
|
||||
|
||||
if err != nil {
|
||||
for _, e := range err.(validator.ValidationErrors) {
|
||||
@@ -141,22 +141,22 @@ func validateGroup(operation string, group models.Group) error {
|
||||
return err
|
||||
}
|
||||
|
||||
//Simple get group function
|
||||
func getGroup(w http.ResponseWriter, r *http.Request) {
|
||||
//Simple get network function
|
||||
func getNetwork(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// set header.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&group)
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -165,7 +165,7 @@ func getGroup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(group)
|
||||
json.NewEncoder(w).Encode(network)
|
||||
}
|
||||
|
||||
func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -174,43 +174,43 @@ func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
group, err := functions.GetParentGroup(params["groupname"])
|
||||
network, err := functions.GetParentNetwork(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"addressrange", group.AddressRange},
|
||||
{"displayname", group.DisplayName},
|
||||
{"defaultlistenport", group.DefaultListenPort},
|
||||
{"defaultpostup", group.DefaultPostUp},
|
||||
{"defaultpreup", group.DefaultPreUp},
|
||||
{"defaultkeepalive", group.DefaultKeepalive},
|
||||
{"keyupdatetimestamp", group.KeyUpdateTimeStamp},
|
||||
{"defaultsaveconfig", group.DefaultSaveConfig},
|
||||
{"defaultinterface", group.DefaultInterface},
|
||||
{"nodeslastmodified", group.NodesLastModified},
|
||||
{"grouplastmodified", group.GroupLastModified},
|
||||
{"allowmanualsignup", group.AllowManualSignUp},
|
||||
{"defaultcheckininterval", group.DefaultCheckInInterval},
|
||||
{"addressrange", network.AddressRange},
|
||||
{"displayname", network.DisplayName},
|
||||
{"defaultlistenport", network.DefaultListenPort},
|
||||
{"defaultpostup", network.DefaultPostUp},
|
||||
{"defaultpreup", network.DefaultPreUp},
|
||||
{"defaultkeepalive", network.DefaultKeepalive},
|
||||
{"keyupdatetimestamp", network.KeyUpdateTimeStamp},
|
||||
{"defaultsaveconfig", network.DefaultSaveConfig},
|
||||
{"defaultinterface", network.DefaultInterface},
|
||||
{"nodeslastmodified", network.NodesLastModified},
|
||||
{"networklastmodified", network.NetworkLastModified},
|
||||
{"allowmanualsignup", network.AllowManualSignUp},
|
||||
{"defaultcheckininterval", network.DefaultCheckInInterval},
|
||||
}},
|
||||
}
|
||||
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -220,56 +220,56 @@ func keyUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(group)
|
||||
json.NewEncoder(w).Encode(network)
|
||||
}
|
||||
|
||||
//Update a group
|
||||
func updateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
//Update a network
|
||||
func updateNetwork(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
group, err := functions.GetParentGroup(params["groupname"])
|
||||
network, err := functions.GetParentNetwork(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
var groupChange models.Group
|
||||
var networkChange models.Network
|
||||
|
||||
haschange := false
|
||||
hasrangeupdate := false
|
||||
hasprivaterangeupdate := false
|
||||
|
||||
_ = json.NewDecoder(r.Body).Decode(&groupChange)
|
||||
_ = json.NewDecoder(r.Body).Decode(&networkChange)
|
||||
|
||||
if groupChange.AddressRange == "" {
|
||||
groupChange.AddressRange = group.AddressRange
|
||||
if networkChange.AddressRange == "" {
|
||||
networkChange.AddressRange = network.AddressRange
|
||||
}
|
||||
if groupChange.NameID == "" {
|
||||
groupChange.NameID = group.NameID
|
||||
if networkChange.NetID == "" {
|
||||
networkChange.NetID = network.NetID
|
||||
}
|
||||
|
||||
|
||||
err = validateGroup("update", groupChange)
|
||||
err = validateNetwork("update", networkChange)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
//NOTE: Group.NameID is intentionally NOT editable. It acts as a static ID for the group.
|
||||
//NOTE: Network.NetID is intentionally NOT editable. It acts as a static ID for the network.
|
||||
//DisplayName can be changed instead, which is what shows on the front end
|
||||
|
||||
if groupChange.AddressRange != "" {
|
||||
if networkChange.AddressRange != "" {
|
||||
|
||||
group.AddressRange = groupChange.AddressRange
|
||||
network.AddressRange = networkChange.AddressRange
|
||||
|
||||
var isAddressOK bool = functions.IsIpv4CIDR(groupChange.AddressRange)
|
||||
var isAddressOK bool = functions.IsIpv4CIDR(networkChange.AddressRange)
|
||||
if !isAddressOK {
|
||||
err := errors.New("Invalid Range of " + groupChange.AddressRange + " for addresses.")
|
||||
err := errors.New("Invalid Range of " + networkChange.AddressRange + " for addresses.")
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
@@ -277,83 +277,83 @@ func updateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
hasrangeupdate = true
|
||||
|
||||
}
|
||||
if groupChange.PrivateRange != "" {
|
||||
group.PrivateRange = groupChange.PrivateRange
|
||||
if networkChange.PrivateRange != "" {
|
||||
network.PrivateRange = networkChange.PrivateRange
|
||||
|
||||
var isAddressOK bool = functions.IsIpv4CIDR(groupChange.PrivateRange)
|
||||
var isAddressOK bool = functions.IsIpv4CIDR(networkChange.PrivateRange)
|
||||
if !isAddressOK {
|
||||
err := errors.New("Invalid Range of " + groupChange.PrivateRange + " for internal addresses.")
|
||||
err := errors.New("Invalid Range of " + networkChange.PrivateRange + " for internal addresses.")
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
haschange = true
|
||||
hasprivaterangeupdate = true
|
||||
}
|
||||
if groupChange.IsPrivate != nil {
|
||||
group.IsPrivate = groupChange.IsPrivate
|
||||
if networkChange.IsPrivate != nil {
|
||||
network.IsPrivate = networkChange.IsPrivate
|
||||
}
|
||||
if groupChange.DefaultListenPort != 0 {
|
||||
group.DefaultListenPort = groupChange.DefaultListenPort
|
||||
if networkChange.DefaultListenPort != 0 {
|
||||
network.DefaultListenPort = networkChange.DefaultListenPort
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DefaultPreUp != "" {
|
||||
group.DefaultPreUp = groupChange.DefaultPreUp
|
||||
if networkChange.DefaultPreUp != "" {
|
||||
network.DefaultPreUp = networkChange.DefaultPreUp
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DefaultInterface != "" {
|
||||
group.DefaultInterface = groupChange.DefaultInterface
|
||||
if networkChange.DefaultInterface != "" {
|
||||
network.DefaultInterface = networkChange.DefaultInterface
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DefaultPostUp != "" {
|
||||
group.DefaultPostUp = groupChange.DefaultPostUp
|
||||
if networkChange.DefaultPostUp != "" {
|
||||
network.DefaultPostUp = networkChange.DefaultPostUp
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DefaultKeepalive != 0 {
|
||||
group.DefaultKeepalive = groupChange.DefaultKeepalive
|
||||
if networkChange.DefaultKeepalive != 0 {
|
||||
network.DefaultKeepalive = networkChange.DefaultKeepalive
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DisplayName != "" {
|
||||
group.DisplayName = groupChange.DisplayName
|
||||
if networkChange.DisplayName != "" {
|
||||
network.DisplayName = networkChange.DisplayName
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.DefaultCheckInInterval != 0 {
|
||||
group.DefaultCheckInInterval = groupChange.DefaultCheckInInterval
|
||||
if networkChange.DefaultCheckInInterval != 0 {
|
||||
network.DefaultCheckInInterval = networkChange.DefaultCheckInInterval
|
||||
haschange = true
|
||||
}
|
||||
if groupChange.AllowManualSignUp != nil {
|
||||
group.AllowManualSignUp = groupChange.AllowManualSignUp
|
||||
if networkChange.AllowManualSignUp != nil {
|
||||
network.AllowManualSignUp = networkChange.AllowManualSignUp
|
||||
haschange = true
|
||||
}
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
|
||||
if haschange {
|
||||
group.SetGroupLastModified()
|
||||
network.SetNetworkLastModified()
|
||||
}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"addressrange", group.AddressRange},
|
||||
{"displayname", group.DisplayName},
|
||||
{"defaultlistenport", group.DefaultListenPort},
|
||||
{"defaultpostup", group.DefaultPostUp},
|
||||
{"defaultpreup", group.DefaultPreUp},
|
||||
{"defaultkeepalive", group.DefaultKeepalive},
|
||||
{"defaultsaveconfig", group.DefaultSaveConfig},
|
||||
{"defaultinterface", group.DefaultInterface},
|
||||
{"nodeslastmodified", group.NodesLastModified},
|
||||
{"grouplastmodified", group.GroupLastModified},
|
||||
{"allowmanualsignup", group.AllowManualSignUp},
|
||||
{"privaterange", group.PrivateRange},
|
||||
{"isprivate", group.IsPrivate},
|
||||
{"defaultcheckininterval", group.DefaultCheckInInterval},
|
||||
{"addressrange", network.AddressRange},
|
||||
{"displayname", network.DisplayName},
|
||||
{"defaultlistenport", network.DefaultListenPort},
|
||||
{"defaultpostup", network.DefaultPostUp},
|
||||
{"defaultpreup", network.DefaultPreUp},
|
||||
{"defaultkeepalive", network.DefaultKeepalive},
|
||||
{"defaultsaveconfig", network.DefaultSaveConfig},
|
||||
{"defaultinterface", network.DefaultInterface},
|
||||
{"nodeslastmodified", network.NodesLastModified},
|
||||
{"networklastmodified", network.NetworkLastModified},
|
||||
{"allowmanualsignup", network.AllowManualSignUp},
|
||||
{"privaterange", network.PrivateRange},
|
||||
{"isprivate", network.IsPrivate},
|
||||
{"defaultcheckininterval", network.DefaultCheckInInterval},
|
||||
}},
|
||||
}
|
||||
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
defer cancel()
|
||||
|
||||
if err != nil {
|
||||
@@ -364,52 +364,52 @@ func updateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
//Cycles through nodes and gives them new IP's based on the new range
|
||||
//Pretty cool, but also pretty inefficient currently
|
||||
if hasrangeupdate {
|
||||
err = functions.UpdateGroupNodeAddresses(params["groupname"])
|
||||
err = functions.UpdateNetworkNodeAddresses(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
}
|
||||
if hasprivaterangeupdate {
|
||||
err = functions.UpdateGroupPrivateAddresses(params["groupname"])
|
||||
err = functions.UpdateNetworkPrivateAddresses(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
}
|
||||
returngroup, err := functions.GetParentGroup(group.NameID)
|
||||
returnnetwork, err := functions.GetParentNetwork(network.NetID)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(returngroup)
|
||||
json.NewEncoder(w).Encode(returnnetwork)
|
||||
}
|
||||
|
||||
//Delete a group
|
||||
//Delete a network
|
||||
//Will stop you if there's any nodes associated
|
||||
func deleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
func deleteNetwork(w http.ResponseWriter, r *http.Request) {
|
||||
// Set header
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
nodecount, err := functions.GetGroupNodeNumber(params["groupname"])
|
||||
nodecount, err := functions.GetNetworkNodeNumber(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w, r, formatError(err, "internal"))
|
||||
return
|
||||
} else if nodecount > 0 {
|
||||
errorResponse := models.ErrorResponse{
|
||||
Code: http.StatusForbidden, Message: "W1R3: Node check failed. All nodes must be deleted before deleting group.",
|
||||
Code: http.StatusForbidden, Message: "W1R3: Node check failed. All nodes must be deleted before deleting network.",
|
||||
}
|
||||
returnErrorResponse(w, r, errorResponse)
|
||||
return
|
||||
}
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
@@ -426,44 +426,44 @@ func deleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(deleteResult)
|
||||
}
|
||||
|
||||
//Create a group
|
||||
//Create a network
|
||||
//Pretty simple
|
||||
func createGroup(w http.ResponseWriter, r *http.Request) {
|
||||
func createNetwork(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
// we decode our body request params
|
||||
err := json.NewDecoder(r.Body).Decode(&group)
|
||||
err := json.NewDecoder(r.Body).Decode(&network)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
//TODO: Not really doing good validation here. Same as createNode, updateNode, and updateGroup
|
||||
//TODO: Not really doing good validation here. Same as createNode, updateNode, and updateNetwork
|
||||
//Need to implement some better validation across the board
|
||||
if group.IsPrivate == nil {
|
||||
if network.IsPrivate == nil {
|
||||
falsevar := false
|
||||
group.IsPrivate = &falsevar
|
||||
network.IsPrivate = &falsevar
|
||||
}
|
||||
|
||||
err = validateGroup("create", group)
|
||||
err = validateNetwork("create", network)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
group.SetDefaults()
|
||||
group.SetNodesLastModified()
|
||||
group.SetGroupLastModified()
|
||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
network.SetDefaults()
|
||||
network.SetNodesLastModified()
|
||||
network.SetNetworkLastModified()
|
||||
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
|
||||
// insert our group into the group table
|
||||
result, err := collection.InsertOne(ctx, group)
|
||||
// insert our network into the network table
|
||||
result, err := collection.InsertOne(ctx, network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -479,18 +479,18 @@ func createGroup(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
|
||||
//TODO: Very little error handling
|
||||
//accesskey is created as a json string inside the Group collection item in mongo
|
||||
//accesskey is created as a json string inside the Network collection item in mongo
|
||||
func createAccessKey(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
var accesskey models.AccessKey
|
||||
|
||||
//start here
|
||||
group, err := functions.GetParentGroup(params["groupname"])
|
||||
network, err := functions.GetParentNetwork(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -517,32 +517,38 @@ func createAccessKey(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
network := params["groupname"]
|
||||
privAddr := ""
|
||||
if *network.IsPrivate {
|
||||
privAddr = network.PrivateRange
|
||||
}
|
||||
|
||||
|
||||
netID := params["networkname"]
|
||||
address := gconf.ServerGRPC + gconf.PortGRPC
|
||||
|
||||
accessstringdec := address + "." + network + "." + accesskey.Value
|
||||
accessstringdec := address + "." + netID + "." + accesskey.Value + "." + privAddr
|
||||
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
||||
|
||||
group.AccessKeys = append(group.AccessKeys, accesskey)
|
||||
network.AccessKeys = append(network.AccessKeys, accesskey)
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
|
||||
// Read update model from body request
|
||||
fmt.Println("Adding key to " + group.NameID)
|
||||
fmt.Println("Adding key to " + network.NetID)
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"accesskeys", group.AccessKeys},
|
||||
{"accesskeys", network.AccessKeys},
|
||||
}},
|
||||
}
|
||||
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -563,15 +569,15 @@ func getAccessKeys(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
//var keys []models.DisplayKey
|
||||
var keys []models.AccessKey
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&group)
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
err := collection.FindOne(ctx, filter, options.FindOne().SetProjection(bson.M{"_id": 0})).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -579,7 +585,7 @@ func getAccessKeys(w http.ResponseWriter, r *http.Request) {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
keydata, err := json.Marshal(group.AccessKeys)
|
||||
keydata, err := json.Marshal(network.AccessKeys)
|
||||
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
@@ -600,41 +606,41 @@ func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
keyname := params["name"]
|
||||
|
||||
//start here
|
||||
group, err := functions.GetParentGroup(params["groupname"])
|
||||
network, err := functions.GetParentNetwork(params["networkname"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
//basically, turn the list of access keys into the list of access keys before and after the item
|
||||
//have not done any error handling for if there's like...1 item. I think it works? need to test.
|
||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
||||
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||
|
||||
currentkey:= group.AccessKeys[i]
|
||||
currentkey:= network.AccessKeys[i]
|
||||
if currentkey.Name == keyname {
|
||||
group.AccessKeys = append(group.AccessKeys[:i],
|
||||
group.AccessKeys[i+1:]...)
|
||||
network.AccessKeys = append(network.AccessKeys[:i],
|
||||
network.AccessKeys[i+1:]...)
|
||||
}
|
||||
}
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"nameid": params["groupname"]}
|
||||
filter := bson.M{"netid": params["networkname"]}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"accesskeys", group.AccessKeys},
|
||||
{"accesskeys", network.AccessKeys},
|
||||
}},
|
||||
}
|
||||
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
err = collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -643,7 +649,7 @@ func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var keys []models.AccessKey
|
||||
keydata, err := json.Marshal(group.AccessKeys)
|
||||
keydata, err := json.Marshal(network.AccessKeys)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
@@ -19,9 +19,9 @@ type NodeServiceServer struct {
|
||||
func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeReq) (*nodepb.ReadNodeRes, error) {
|
||||
// convert string id (from proto) to mongoDB ObjectId
|
||||
macaddress := req.GetMacaddress()
|
||||
groupName := req.GetGroup()
|
||||
networkName := req.GetNetwork()
|
||||
|
||||
node, err := GetNode(macaddress, groupName)
|
||||
node, err := GetNode(macaddress, networkName)
|
||||
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("Something went wrong: %v", err))
|
||||
@@ -40,7 +40,7 @@ func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeRe
|
||||
Address: node.Address,
|
||||
Endpoint: node.Endpoint,
|
||||
Password: node.Password,
|
||||
Nodegroup: node.Group,
|
||||
Nodenetwork: node.Network,
|
||||
Interface: node.Interface,
|
||||
Localaddress: node.LocalAddress,
|
||||
Preup: node.PreUp,
|
||||
@@ -71,13 +71,13 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
||||
PersistentKeepalive: data.GetKeepalive(),
|
||||
Password: data.GetPassword(),
|
||||
Interface: data.GetInterface(),
|
||||
Group: data.GetNodegroup(),
|
||||
Network: data.GetNodenetwork(),
|
||||
IsPending: data.GetIspending(),
|
||||
PublicKey: data.GetPublickey(),
|
||||
ListenPort: data.GetListenport(),
|
||||
}
|
||||
|
||||
err := ValidateNode("create", node.Group, node)
|
||||
err := ValidateNode("create", node.Network, node)
|
||||
|
||||
if err != nil {
|
||||
// return internal gRPC error to be handled later
|
||||
@@ -85,24 +85,24 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
||||
}
|
||||
|
||||
//Check to see if key is valid
|
||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for groups
|
||||
validKey := functions.IsKeyValid(node.Group, node.AccessKey)
|
||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for networks
|
||||
validKey := functions.IsKeyValid(node.Network, node.AccessKey)
|
||||
|
||||
if !validKey {
|
||||
group, _ := functions.GetParentGroup(node.Group)
|
||||
//Check to see if group will allow manual sign up
|
||||
network, _ := functions.GetParentNetwork(node.Network)
|
||||
//Check to see if network will allow manual sign up
|
||||
//may want to switch this up with the valid key check and avoid a DB call that way.
|
||||
if *group.AllowManualSignUp {
|
||||
if *network.AllowManualSignUp {
|
||||
node.IsPending = true
|
||||
} else {
|
||||
return nil, status.Errorf(
|
||||
codes.Internal,
|
||||
fmt.Sprintf("Invalid key, and group does not allow no-key signups"),
|
||||
fmt.Sprintf("Invalid key, and network does not allow no-key signups"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
node, err = CreateNode(node, node.Group)
|
||||
node, err = CreateNode(node, node.Network)
|
||||
|
||||
if err != nil {
|
||||
// return internal gRPC error to be handled later
|
||||
@@ -121,16 +121,16 @@ func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNo
|
||||
Endpoint: node.Endpoint,
|
||||
Password: node.Password,
|
||||
Interface: node.Interface,
|
||||
Nodegroup: node.Group,
|
||||
Nodenetwork: node.Network,
|
||||
Ispending: node.IsPending,
|
||||
Publickey: node.PublicKey,
|
||||
Listenport: node.ListenPort,
|
||||
Keepalive: node.PersistentKeepalive,
|
||||
},
|
||||
}
|
||||
err = SetGroupNodesLastModified(node.Group)
|
||||
err = SetNetworkNodesLastModified(node.Network)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update group last modified date: %v", err))
|
||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
|
||||
}
|
||||
|
||||
return response, nil
|
||||
@@ -147,7 +147,7 @@ func (s *NodeServiceServer) CheckIn(ctx context.Context, req *nodepb.CheckInReq)
|
||||
MacAddress: data.GetMacaddress(),
|
||||
Address: data.GetAddress(),
|
||||
Endpoint: data.GetEndpoint(),
|
||||
Group: data.GetNodegroup(),
|
||||
Network: data.GetNodenetwork(),
|
||||
Password: data.GetPassword(),
|
||||
LocalAddress: data.GetLocaladdress(),
|
||||
ListenPort: data.GetListenport(),
|
||||
@@ -155,7 +155,7 @@ func (s *NodeServiceServer) CheckIn(ctx context.Context, req *nodepb.CheckInReq)
|
||||
PublicKey: data.GetPublickey(),
|
||||
}
|
||||
|
||||
checkinresponse, err := NodeCheckIn(node, node.Group)
|
||||
checkinresponse, err := NodeCheckIn(node, node.Network)
|
||||
|
||||
if err != nil {
|
||||
// return internal gRPC error to be handled later
|
||||
@@ -195,7 +195,7 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
||||
Endpoint: data.GetEndpoint(),
|
||||
Password: data.GetPassword(),
|
||||
PersistentKeepalive: data.GetKeepalive(),
|
||||
Group: data.GetNodegroup(),
|
||||
Network: data.GetNodenetwork(),
|
||||
Interface: data.GetInterface(),
|
||||
PreUp: data.GetPreup(),
|
||||
PostUp: data.GetPostup(),
|
||||
@@ -207,14 +207,14 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
||||
|
||||
// Convert the Id string to a MongoDB ObjectId
|
||||
macaddress := nodechange.MacAddress
|
||||
groupName := nodechange.Group
|
||||
networkName := nodechange.Network
|
||||
|
||||
err := ValidateNode("update", groupName, nodechange)
|
||||
err := ValidateNode("update", networkName, nodechange)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
node, err := functions.GetNodeByMacAddress(groupName, macaddress)
|
||||
node, err := functions.GetNodeByMacAddress(networkName, macaddress)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(
|
||||
codes.NotFound,
|
||||
@@ -242,7 +242,7 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
||||
Interface: newnode.Interface,
|
||||
Preup: newnode.PreUp,
|
||||
Postup: newnode.PostUp,
|
||||
Nodegroup: newnode.Group,
|
||||
Nodenetwork: newnode.Network,
|
||||
Ispending: newnode.IsPending,
|
||||
Publickey: newnode.PublicKey,
|
||||
Listenport: newnode.ListenPort,
|
||||
@@ -255,9 +255,9 @@ func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNo
|
||||
func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNodeReq) (*nodepb.DeleteNodeRes, error) {
|
||||
fmt.Println("beginning node delete")
|
||||
macaddress := req.GetMacaddress()
|
||||
group := req.GetGroupName()
|
||||
network := req.GetNetworkName()
|
||||
|
||||
success, err := DeleteNode(macaddress, group)
|
||||
success, err := DeleteNode(macaddress, network)
|
||||
|
||||
if err != nil || !success {
|
||||
fmt.Println("Error deleting node.")
|
||||
@@ -265,12 +265,12 @@ func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNo
|
||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find/delete node with mac address %s", macaddress))
|
||||
}
|
||||
|
||||
fmt.Println("updating group last modified of " + req.GetGroupName())
|
||||
err = SetGroupNodesLastModified(req.GetGroupName())
|
||||
fmt.Println("updating network last modified of " + req.GetNetworkName())
|
||||
err = SetNetworkNodesLastModified(req.GetNetworkName())
|
||||
if err != nil {
|
||||
fmt.Println("Error updating Group")
|
||||
fmt.Println("Error updating Network")
|
||||
fmt.Println(err)
|
||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update group last modified date: %v", err))
|
||||
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
|
||||
}
|
||||
|
||||
|
||||
@@ -284,7 +284,7 @@ func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.Node
|
||||
//data := &models.PeersResponse{}
|
||||
// collection.Find returns a cursor for our (empty) query
|
||||
//cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
|
||||
peers, err := GetPeersList(req.GetGroup())
|
||||
peers, err := GetPeersList(req.GetNetwork())
|
||||
|
||||
if err != nil {
|
||||
return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
|
||||
@@ -305,7 +305,7 @@ func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.Node
|
||||
})
|
||||
}
|
||||
|
||||
node, err := functions.GetNodeByMacAddress(req.GetGroup(), req.GetMacaddress())
|
||||
node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
|
||||
if err != nil {
|
||||
return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
|
||||
}
|
||||
|
@@ -21,17 +21,17 @@ import (
|
||||
func nodeHandlers(r *mux.Router) {
|
||||
|
||||
r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/{group}", authorize(true, "group", http.HandlerFunc(getGroupNodes))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
|
||||
r.HandleFunc("/api/nodes/{group}/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
|
||||
r.HandleFunc("/api/nodes/{group}/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
|
||||
// r.HandleFunc("/api/nodes/{group}/{macaddress}/creategateway", authorize(true, "master", http.HandlerFunc(createGateway))).Methods("POST")
|
||||
// r.HandleFunc("/api/nodes/{group}/{macaddress}/deletegateway", authorize(true, "master", http.HandlerFunc(deleteGateway))).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/{group}/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/{group}/nodes", createNode).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/adm/{group}/lastmodified", authorize(true, "group", http.HandlerFunc(getLastModified))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/adm/{group}/authenticate", authenticate).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/{network}", authorize(true, "network", http.HandlerFunc(getNetworkNodes))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
|
||||
r.HandleFunc("/api/nodes/{network}/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
|
||||
r.HandleFunc("/api/nodes/{network}/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
|
||||
// r.HandleFunc("/api/nodes/{network}/{macaddress}/creategateway", authorize(true, "master", http.HandlerFunc(createGateway))).Methods("POST")
|
||||
// r.HandleFunc("/api/nodes/{network}/{macaddress}/deletegateway", authorize(true, "master", http.HandlerFunc(deleteGateway))).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/{network}/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/{network}/nodes", createNode).Methods("POST")
|
||||
r.HandleFunc("/api/nodes/adm/{network}/lastmodified", authorize(true, "network", http.HandlerFunc(getLastModified))).Methods("GET")
|
||||
r.HandleFunc("/api/nodes/adm/{network}/authenticate", authenticate).Methods("POST")
|
||||
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ func authenticate(response http.ResponseWriter, request *http.Request) {
|
||||
return
|
||||
} else {
|
||||
//Create a new JWT for the node
|
||||
tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Group)
|
||||
tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Network)
|
||||
|
||||
if tokenString == "" {
|
||||
returnErrorResponse(response, request, errorResponse)
|
||||
@@ -121,11 +121,11 @@ func authenticate(response http.ResponseWriter, request *http.Request) {
|
||||
//The middleware for most requests to the API
|
||||
//They all pass through here first
|
||||
//This will validate the JWT (or check for master token)
|
||||
//This will also check against the authGroup and make sure the node should be accessing that endpoint,
|
||||
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
||||
//even if it's technically ok
|
||||
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
||||
//TODO: Consider better RBAC implementations
|
||||
func authorize(groupCheck bool, authGroup string, next http.Handler) http.HandlerFunc {
|
||||
func authorize(networkCheck bool, authNetwork string, next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var errorResponse = models.ErrorResponse{
|
||||
@@ -134,13 +134,13 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
groupexists, _ := functions.GroupExists(params["group"])
|
||||
networkexists, _ := functions.NetworkExists(params["network"])
|
||||
|
||||
//check that the request is for a valid group
|
||||
//if (groupCheck && !groupexists) || err != nil {
|
||||
if (groupCheck && !groupexists) {
|
||||
//check that the request is for a valid network
|
||||
//if (networkCheck && !networkexists) || err != nil {
|
||||
if (networkCheck && !networkexists) {
|
||||
errorResponse = models.ErrorResponse{
|
||||
Code: http.StatusNotFound, Message: "W1R3: This group does not exist. ",
|
||||
Code: http.StatusNotFound, Message: "W1R3: This network does not exist. ",
|
||||
}
|
||||
returnErrorResponse(w, r, errorResponse)
|
||||
return
|
||||
@@ -190,15 +190,15 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
||||
isAuthorized = true
|
||||
|
||||
//for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
|
||||
//So each route defines which access group should be allowed to access it
|
||||
//So each route defines which access network should be allowed to access it
|
||||
} else {
|
||||
switch authGroup {
|
||||
switch authNetwork {
|
||||
case "all":
|
||||
isAuthorized = true
|
||||
case "nodes":
|
||||
isAuthorized = (macaddress != "")
|
||||
case "group":
|
||||
node, err := functions.GetNodeByMacAddress(params["group"], macaddress)
|
||||
case "network":
|
||||
node, err := functions.GetNodeByMacAddress(params["network"], macaddress)
|
||||
if err != nil {
|
||||
errorResponse = models.ErrorResponse{
|
||||
Code: http.StatusUnauthorized, Message: "W1R3: Missing Auth Token.",
|
||||
@@ -206,7 +206,7 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
||||
returnErrorResponse(w, r, errorResponse)
|
||||
return
|
||||
}
|
||||
isAuthorized = (node.Group == params["group"])
|
||||
isAuthorized = (node.Network == params["network"])
|
||||
case "node":
|
||||
isAuthorized = (macaddress == params["macaddress"])
|
||||
case "master":
|
||||
@@ -229,8 +229,8 @@ func authorize(groupCheck bool, authGroup string, next http.Handler) http.Handle
|
||||
}
|
||||
}
|
||||
|
||||
//Gets all nodes associated with group, including pending nodes
|
||||
func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
||||
//Gets all nodes associated with network, including pending nodes
|
||||
func getNetworkNodes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -241,7 +241,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"group": params["group"]}
|
||||
filter := bson.M{"network": params["network"]}
|
||||
|
||||
//Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
|
||||
cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
|
||||
@@ -256,7 +256,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
||||
for cur.Next(context.TODO()) {
|
||||
|
||||
//Using a different model for the ReturnNode (other than regular node).
|
||||
//Either we should do this for ALL structs (so Groups and Keys)
|
||||
//Either we should do this for ALL structs (so Networks and Keys)
|
||||
//OR we should just use the original struct
|
||||
//My preference is to make some new return structs
|
||||
//TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
|
||||
@@ -284,7 +284,7 @@ func getGroupNodes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
}
|
||||
|
||||
//A separate function to get all nodes, not just nodes for a particular group.
|
||||
//A separate function to get all nodes, not just nodes for a particular network.
|
||||
//Not quite sure if this is necessary. Probably necessary based on front end but may want to review after iteration 1 if it's being used or not
|
||||
func getAllNodes(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -332,15 +332,15 @@ func getAllNodes(w http.ResponseWriter, r *http.Request) {
|
||||
//This function get's called when a node "checks in" at check in interval
|
||||
//Honestly I'm not sure what all it should be doing
|
||||
//TODO: Implement the necessary stuff, including the below
|
||||
//Check the last modified of the group
|
||||
//Check the last modified of the network
|
||||
//Check the last modified of the nodes
|
||||
//Write functions for responding to these two thingies
|
||||
func checkIn(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
//TODO: Current thoughts:
|
||||
//Dont bother with a grouplastmodified
|
||||
//Dont bother with a networklastmodified
|
||||
//Instead, implement a "configupdate" boolean on nodes
|
||||
//when there is a group update that requrires a config update, then the node will pull its new config
|
||||
//when there is a network update that requrires a config update, then the node will pull its new config
|
||||
|
||||
// set header.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
@@ -351,13 +351,13 @@ func checkIn(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
|
||||
//Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
|
||||
//node = functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
||||
//node = functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
||||
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||
|
||||
//old code was inefficient, this is all we need.
|
||||
time := time.Now().String()
|
||||
@@ -380,7 +380,7 @@ func checkIn(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
//TODO: check node last modified vs group last modified
|
||||
//TODO: check node last modified vs network last modified
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(node)
|
||||
|
||||
@@ -393,7 +393,7 @@ func getNode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var params = mux.Vars(r)
|
||||
|
||||
node, err := GetNode(params["macaddress"], params["group"])
|
||||
node, err := GetNode(params["macaddress"], params["network"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -402,23 +402,23 @@ func getNode(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(node)
|
||||
}
|
||||
|
||||
//Get the time that a group of nodes was last modified.
|
||||
//Get the time that a network of nodes was last modified.
|
||||
//TODO: This needs to be refactored
|
||||
//Potential way to do this: On UpdateNode, set a new field for "LastModified"
|
||||
//If we go with the existing way, we need to at least set group.NodesLastModified on UpdateNode
|
||||
//If we go with the existing way, we need to at least set network.NodesLastModified on UpdateNode
|
||||
func getLastModified(w http.ResponseWriter, r *http.Request) {
|
||||
// set header.
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
var params = mux.Vars(r)
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": params["group"]}
|
||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
||||
filter := bson.M{"netid": params["network"]}
|
||||
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -428,7 +428,7 @@ func getLastModified(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(string(group.NodesLastModified)))
|
||||
w.Write([]byte(string(network.NodesLastModified)))
|
||||
|
||||
}
|
||||
|
||||
@@ -444,19 +444,19 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
||||
Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
|
||||
}
|
||||
|
||||
groupName := params["group"]
|
||||
networkName := params["network"]
|
||||
|
||||
//Check if group exists first
|
||||
//Check if network exists first
|
||||
//TODO: This is inefficient. Let's find a better way.
|
||||
//Just a few rows down we grab the group anyway
|
||||
groupexists, err := functions.GroupExists(groupName)
|
||||
//Just a few rows down we grab the network anyway
|
||||
networkexists, err := functions.NetworkExists(networkName)
|
||||
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
} else if !groupexists {
|
||||
} else if !networkexists {
|
||||
errorResponse = models.ErrorResponse{
|
||||
Code: http.StatusNotFound, Message: "W1R3: Group does not exist! ",
|
||||
Code: http.StatusNotFound, Message: "W1R3: Network does not exist! ",
|
||||
}
|
||||
returnErrorResponse(w, r, errorResponse)
|
||||
return
|
||||
@@ -471,23 +471,23 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
node.Group = groupName
|
||||
node.Network = networkName
|
||||
|
||||
|
||||
group, err := node.GetGroup()
|
||||
network, err := node.GetNetwork()
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
//Check to see if key is valid
|
||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for groups
|
||||
validKey := functions.IsKeyValid(groupName, node.AccessKey)
|
||||
//TODO: Triple inefficient!!! This is the third call to the DB we make for networks
|
||||
validKey := functions.IsKeyValid(networkName, node.AccessKey)
|
||||
|
||||
if !validKey {
|
||||
//Check to see if group will allow manual sign up
|
||||
//Check to see if network will allow manual sign up
|
||||
//may want to switch this up with the valid key check and avoid a DB call that way.
|
||||
if *group.AllowManualSignUp {
|
||||
if *network.AllowManualSignUp {
|
||||
node.IsPending = true
|
||||
} else {
|
||||
errorResponse = models.ErrorResponse{
|
||||
@@ -498,13 +498,13 @@ func createNode(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
err = ValidateNode("create", groupName, node)
|
||||
err = ValidateNode("create", networkName, node)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
}
|
||||
|
||||
node, err = CreateNode(node, groupName)
|
||||
node, err = CreateNode(node, networkName)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -522,7 +522,7 @@ func uncordonNode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var node models.Node
|
||||
|
||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
||||
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -533,7 +533,7 @@ func uncordonNode(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
||||
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||
|
||||
node.SetLastModified()
|
||||
|
||||
@@ -567,7 +567,7 @@ func createGateway(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
var node models.Node
|
||||
|
||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
||||
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -578,11 +578,11 @@ func createGateway(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"macaddress": params["macaddress"], "group": params["group"]}
|
||||
filter := bson.M{"macaddress": params["macaddress"], "network": params["network"]}
|
||||
|
||||
node.SetLastModified()
|
||||
|
||||
err = ValidateNode("create", params["group"], node)
|
||||
err = ValidateNode("create", params["network"], node)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -622,7 +622,7 @@ func updateNode(w http.ResponseWriter, r *http.Request) {
|
||||
var node models.Node
|
||||
|
||||
//start here
|
||||
node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
|
||||
node, err := functions.GetNodeByMacAddress(params["network"], params["macaddress"])
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -634,14 +634,14 @@ func updateNode(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// we decode our body request params
|
||||
_ = json.NewDecoder(r.Body).Decode(&nodechange)
|
||||
if nodechange.Group == "" {
|
||||
nodechange.Group = node.Group
|
||||
if nodechange.Network == "" {
|
||||
nodechange.Network = node.Network
|
||||
}
|
||||
if nodechange.MacAddress == "" {
|
||||
nodechange.MacAddress = node.MacAddress
|
||||
}
|
||||
|
||||
err = ValidateNode("update", params["group"], nodechange)
|
||||
err = ValidateNode("update", params["network"], nodechange)
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
return
|
||||
@@ -665,7 +665,7 @@ func deleteNode(w http.ResponseWriter, r *http.Request) {
|
||||
// get params
|
||||
var params = mux.Vars(r)
|
||||
|
||||
success, err := DeleteNode(params["macaddress"], params["group"])
|
||||
success, err := DeleteNode(params["macaddress"], params["network"])
|
||||
|
||||
if err != nil {
|
||||
returnErrorResponse(w,r,formatError(err, "internal"))
|
||||
|
@@ -16,7 +16,7 @@ func serverHandlers(r *mux.Router) {
|
||||
}
|
||||
|
||||
//Security check is middleware for every function and just checks to make sure that its the master calling
|
||||
//Only admin should have access to all these group-level actions
|
||||
//Only admin should have access to all these network-level actions
|
||||
//or maybe some Users once implemented
|
||||
func securityCheckServer(next http.Handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
@@ -116,7 +116,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) {
|
||||
//The middleware for most requests to the API
|
||||
//They all pass through here first
|
||||
//This will validate the JWT (or check for master token)
|
||||
//This will also check against the authGroup and make sure the node should be accessing that endpoint,
|
||||
//This will also check against the authNetwork and make sure the node should be accessing that endpoint,
|
||||
//even if it's technically ok
|
||||
//This is kind of a poor man's RBAC. There's probably a better/smarter way.
|
||||
//TODO: Consider better RBAC implementations
|
||||
|
52
docs/API.md
52
docs/API.md
@@ -1,30 +1,30 @@
|
||||
# API Reference Doc
|
||||
|
||||
### Nodes
|
||||
**Get Peer List:** "/api/{group}/peerlist", "GET"
|
||||
**Get List Last Modified Date:** "/api/{group}/lastmodified", "GET"
|
||||
**Get Node Details:** "/api/{group}/nodes/{macaddress}", "GET"
|
||||
**Create Node:** "/api/{group}/nodes", "POST"
|
||||
**Uncordon Node:** "/api/{group}/nodes/{macaddress}/uncordon", "POST"
|
||||
**Check In Node:** "/api/{group}/nodes/{macaddress}/checkin", "POST"
|
||||
**Update Node:** "/api/{group}/nodes/{macaddress}", "PUT"
|
||||
**Delete Node:** "/api/{group}/nodes/{macaddress}", "DELETE"
|
||||
**Get Group Nodes:** "/api/{group}/nodes", "GET"
|
||||
**Get Peer List:** "/api/{network}/peerlist", "GET"
|
||||
**Get List Last Modified Date:** "/api/{network}/lastmodified", "GET"
|
||||
**Get Node Details:** "/api/{network}/nodes/{macaddress}", "GET"
|
||||
**Create Node:** "/api/{network}/nodes", "POST"
|
||||
**Uncordon Node:** "/api/{network}/nodes/{macaddress}/uncordon", "POST"
|
||||
**Check In Node:** "/api/{network}/nodes/{macaddress}/checkin", "POST"
|
||||
**Update Node:** "/api/{network}/nodes/{macaddress}", "PUT"
|
||||
**Delete Node:** "/api/{network}/nodes/{macaddress}", "DELETE"
|
||||
**Get Network Nodes:** "/api/{network}/nodes", "GET"
|
||||
**Get All Nodes:** "/api/nodes", "GET"
|
||||
**Authenticate:** "/api/{group}/authenticate", "POST"
|
||||
**Authenticate:** "/api/{network}/authenticate", "POST"
|
||||
|
||||
|
||||
### Groups
|
||||
**Get Groups:** "/api/groups", "GET"
|
||||
**Get Group Details:** "/api/group/{groupname}", "GET"
|
||||
**Get Number of Nodes in Group:** "/api/group/{groupname}/numnodes", "GET"
|
||||
**Create Group:** "/api/groups", "POST"
|
||||
**Update Group:** "/api/groups/{groupname}", "PUT"
|
||||
**Delete Group:** "/api/groups/{groupname}", "DELETE"
|
||||
### Networks
|
||||
**Get Networks:** "/api/networks", "GET"
|
||||
**Get Network Details:** "/api/network/{networkname}", "GET"
|
||||
**Get Number of Nodes in Network:** "/api/network/{networkname}/numnodes", "GET"
|
||||
**Create Network:** "/api/networks", "POST"
|
||||
**Update Network:** "/api/networks/{networkname}", "PUT"
|
||||
**Delete Network:** "/api/networks/{networkname}", "DELETE"
|
||||
|
||||
**Create Access Key:** "/api/groups/{groupname}/keys", "POST"
|
||||
**Get Access Key:** "/api/groups/{groupname}/keys", "GET"
|
||||
**Delete Access Key:** "/api/groups/{groupname}/keys/{keyname}", "DELETE"
|
||||
**Create Access Key:** "/api/networks/{networkname}/keys", "POST"
|
||||
**Get Access Key:** "/api/networks/{networkname}/keys", "GET"
|
||||
**Delete Access Key:** "/api/networks/{networkname}/keys/{keyname}", "DELETE"
|
||||
|
||||
### Users (only used for interface admin user at this time)
|
||||
**Create Admin User:** "/users/createadmin", "POST"
|
||||
@@ -44,19 +44,19 @@
|
||||
|
||||
**Note About Token:** This is a configurable value stored under config/environments/dev.yaml and can be changed before startup. It's a hack for testing, just provides an easy way to authorize, and should be removed and changed in the future.
|
||||
|
||||
#### Create a Group
|
||||
curl -d '{"addressrange":"10.70.0.0/16","nameid":"skynet"}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups
|
||||
#### Create a Network
|
||||
curl -d '{"addressrange":"10.70.0.0/16","netid":"skynet"}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks
|
||||
|
||||
#### Create a Key
|
||||
curl -d '{"uses":10}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups localhost:8081/api/groups/skynet/keys
|
||||
curl -d '{"uses":10}' -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks localhost:8081/api/networks/skynet/keys
|
||||
|
||||
#### Create a Node
|
||||
curl -d '{ "endpoint": 100.200.100.200, "publickey": aorijqalrik3ajflaqrdajhkr,"macaddress": "8c:90:b5:06:f1:d9","password": "reallysecret","localaddress": "172.16.16.1","accesskey": "aA3bVG0rnItIRXDx","listenport": 6400}' -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/skynet/nodes
|
||||
|
||||
#### Get Groups
|
||||
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/groups | jq
|
||||
#### Get Networks
|
||||
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/networks | jq
|
||||
|
||||
#### Get Group Nodes
|
||||
#### Get Network Nodes
|
||||
curl -H "Authorization: Bearer secretkey" -H 'Content-Type: application/json' localhost:8081/api/skynet/nodes | jq
|
||||
|
||||
#### Update Node Settings
|
||||
|
@@ -5,9 +5,9 @@
|
||||
3. Pull this repo: `git clone https://github.com/gravitl/netmaker.git`
|
||||
4. Switch to the directory and source the default env vars `cd netmaker && source defaultvars.sh`
|
||||
5. Run the server: `go run ./`
|
||||
### Optional (For Testing): Create Groups and Nodes
|
||||
### Optional (For Testing): Create Networks and Nodes
|
||||
|
||||
1. Create Group: `./test/groupcreate.sh`
|
||||
1. Create Network: `./test/networkcreate.sh`
|
||||
2. Create Key: `./test/keycreate.sh` (save the response for step 3)
|
||||
3. Open ./test/nodescreate.sh and replace ACCESSKEY with value from #2
|
||||
4. Create Nodes: `./test/nodescreate.sh`
|
||||
@@ -21,10 +21,10 @@ On each machine you would like to add to the network, do the following:
|
||||
|
||||
1. Confirm wireguard is installed: `sudo apt install wireguard-tools`
|
||||
2. Confirm ipv4 forwarding is enabled: `sysctl -w net.ipv4.ip_forward=1`
|
||||
3. Create a key or enable manual node signup at the group level
|
||||
3. Create a key or enable manual node signup at the network level
|
||||
4. Get the binary: `sudo wget 52.55.6.84:8081/meshclient/files/meshclient`
|
||||
5. Make it executable: `sudo chmod +x meshclient`
|
||||
6. Run the install command: `sudo ./meshclient -c install -g <group name> -s <server:port> -k <key value>`
|
||||
6. Run the install command: `sudo ./meshclient -c install -g <network name> -s <server:port> -k <key value>`
|
||||
|
||||
This will install netclient.service and netclient.timer in systemd, which will run periodically to call the netclient binary, which will check to see if there are any updates that it needs and update WireGuard appropriately.
|
||||
|
||||
|
@@ -2,12 +2,12 @@
|
||||
|
||||
### 0.1
|
||||
**Server:**
|
||||
- [x] Create Groups (virtual networks)
|
||||
- [x] Allow default settings for nodes from groups
|
||||
- [x] Create Networks (virtual networks)
|
||||
- [x] Allow default settings for nodes from networks
|
||||
- [x] Admin/Superuser key
|
||||
- [x] Create multiuse keys for node signup
|
||||
- [x] JWT-based auth for post-signup
|
||||
- [x] CRUD for groups
|
||||
- [x] CRUD for networks
|
||||
- [x] CRUD for nodes
|
||||
- [x] Track all important info about node for networking (port, endpoints, pub key, etc)
|
||||
- [x] Timestamps for determining if nodes need updates
|
||||
@@ -31,21 +31,21 @@
|
||||
- [ ] Troubleshooting
|
||||
|
||||
**Server:**
|
||||
- [ ] Allow tracking multiple groups per node
|
||||
- [ ] Allow tracking multiple networks per node
|
||||
- [ ] Configure Check-in thresholds
|
||||
- [ ] Separate sign-up endpoint to allow VPN-only comms after joining network
|
||||
- [ ] Swagger Docs
|
||||
- [ ] Build Out README
|
||||
- [ ] Encode Server, Port, and Group into Keys
|
||||
- [ ] Encode Server, Port, and Network into Keys
|
||||
- [ ] Switch to Unique ID for nodes instead of MacAddress
|
||||
- [ ] Public Key refresh
|
||||
- [ ] Enable ipv6 addresses
|
||||
- [ ] Have a "default" group created at startup
|
||||
- [ ] Have a "default" network created at startup
|
||||
|
||||
**Agent:**
|
||||
- [ ] Test / get working on multiple linux platforms
|
||||
- [ ] Set private DNS via etc hosts (node name + ip). Make it optional flag on agent.
|
||||
- [ ] Decode Server, Port, and Group from Key
|
||||
- [ ] Decode Server, Port, and Network from Key
|
||||
- [ ] Service ID / unit file for SystemD Service
|
||||
- [ ] Allow multiple interfaces
|
||||
- [ ] Use "Check in interval" from server
|
||||
@@ -55,7 +55,7 @@
|
||||
### 0.3
|
||||
**Server:**
|
||||
- [ ] Swagger Docs
|
||||
- [ ] Group/Node labels
|
||||
- [ ] Network/Node labels
|
||||
- [ ] "Read Only" mode for nodes (can't update their settings centrally, only read)
|
||||
- [ ] "No-GUI mode:" Similar to existing, just do more e2e testing and make sure flow makes sense
|
||||
- [ ] Let users set prefixes (node, interface)
|
||||
@@ -87,7 +87,7 @@
|
||||
- [ ] Load balance / fault tolerant server
|
||||
- [ ] Change DB / make more scaleable (SQL?)
|
||||
- [ ] Redis
|
||||
- [ ] Group/Node labels
|
||||
- [ ] Network/Node labels
|
||||
|
||||
**Agent:**
|
||||
- [ ] userspace via Docker or Golang
|
||||
|
@@ -22,14 +22,14 @@ import (
|
||||
)
|
||||
|
||||
//Takes in an arbitrary field and value for field and checks to see if any other
|
||||
//node has that value for the same field within the group
|
||||
//node has that value for the same field within the network
|
||||
|
||||
func CreateServerToken(network string) (string, error) {
|
||||
func CreateServerToken(netID string) (string, error) {
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
var accesskey models.AccessKey
|
||||
|
||||
group, err := GetParentGroup(network)
|
||||
network, err := GetParentNetwork(netID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -43,29 +43,29 @@ func CreateServerToken(network string) (string, error) {
|
||||
}
|
||||
address := "localhost" + gconf.PortGRPC
|
||||
|
||||
accessstringdec := address + "." + network + "." + accesskey.Value
|
||||
accessstringdec := address + "." + netID + "." + accesskey.Value
|
||||
accesskey.AccessString = base64.StdEncoding.EncodeToString([]byte(accessstringdec))
|
||||
|
||||
group.AccessKeys = append(group.AccessKeys, accesskey)
|
||||
network.AccessKeys = append(network.AccessKeys, accesskey)
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"nameid": network}
|
||||
filter := bson.M{"netid": netID}
|
||||
|
||||
// Read update model from body request
|
||||
fmt.Println("Adding key to " + group.NameID)
|
||||
fmt.Println("Adding key to " + network.NetID)
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"accesskeys", group.AccessKeys},
|
||||
{"accesskeys", network.AccessKeys},
|
||||
}},
|
||||
}
|
||||
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -75,7 +75,7 @@ func CreateServerToken(network string) (string, error) {
|
||||
return accesskey.AccessString, nil
|
||||
}
|
||||
|
||||
func IsFieldUnique(group string, field string, value string) bool {
|
||||
func IsFieldUnique(network string, field string, value string) bool {
|
||||
|
||||
var node models.Node
|
||||
isunique := true
|
||||
@@ -83,7 +83,7 @@ func IsFieldUnique(group string, field string, value string) bool {
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{field: value, "group": group}
|
||||
filter := bson.M{field: value, "network": network}
|
||||
|
||||
err := collection.FindOne(ctx, filter).Decode(&node)
|
||||
|
||||
@@ -100,13 +100,13 @@ func IsFieldUnique(group string, field string, value string) bool {
|
||||
return isunique
|
||||
}
|
||||
|
||||
func GroupExists(name string) (bool, error) {
|
||||
func NetworkExists(name string) (bool, error) {
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": name}
|
||||
filter := bson.M{"netid": name}
|
||||
|
||||
var result bson.M
|
||||
err := collection.FindOne(ctx, filter).Decode(&result)
|
||||
@@ -124,16 +124,16 @@ func GroupExists(name string) (bool, error) {
|
||||
}
|
||||
|
||||
//TODO: This is very inefficient (N-squared). Need to find a better way.
|
||||
//Takes a list of nodes in a group and iterates through
|
||||
//Takes a list of nodes in a network and iterates through
|
||||
//for each node, it gets a unique address. That requires checking against all other nodes once more
|
||||
func UpdateGroupNodeAddresses(groupName string) error {
|
||||
func UpdateNetworkNodeAddresses(networkName string) error {
|
||||
|
||||
//Connection mongoDB with mongoconn class
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"group": groupName}
|
||||
filter := bson.M{"network": networkName}
|
||||
cur, err := collection.Find(ctx, filter)
|
||||
|
||||
if err != nil {
|
||||
@@ -151,7 +151,7 @@ func UpdateGroupNodeAddresses(groupName string) error {
|
||||
fmt.Println("error in node address assignment!")
|
||||
return err
|
||||
}
|
||||
ipaddr, iperr := UniqueAddress(groupName)
|
||||
ipaddr, iperr := UniqueAddress(networkName)
|
||||
if iperr != nil {
|
||||
fmt.Println("error in node address assignment!")
|
||||
return iperr
|
||||
@@ -171,14 +171,14 @@ func UpdateGroupNodeAddresses(groupName string) error {
|
||||
return err
|
||||
}
|
||||
//TODO TODO TODO!!!!!
|
||||
func UpdateGroupPrivateAddresses(groupName string) error {
|
||||
func UpdateNetworkPrivateAddresses(networkName string) error {
|
||||
|
||||
//Connection mongoDB with mongoconn class
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"group": groupName}
|
||||
filter := bson.M{"network": networkName}
|
||||
cur, err := collection.Find(ctx, filter)
|
||||
|
||||
if err != nil {
|
||||
@@ -196,7 +196,7 @@ func UpdateGroupPrivateAddresses(groupName string) error {
|
||||
fmt.Println("error in node address assignment!")
|
||||
return err
|
||||
}
|
||||
ipaddr, iperr := UniqueAddress(groupName)
|
||||
ipaddr, iperr := UniqueAddress(networkName)
|
||||
if iperr != nil {
|
||||
fmt.Println("error in node address assignment!")
|
||||
return iperr
|
||||
@@ -216,12 +216,12 @@ func UpdateGroupPrivateAddresses(groupName string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
//Checks to see if any other groups have the same name (id)
|
||||
func IsGroupNameUnique(name string) (bool, error ){
|
||||
//Checks to see if any other networks have the same name (id)
|
||||
func IsNetworkNameUnique(name string) (bool, error ){
|
||||
|
||||
isunique := true
|
||||
|
||||
dbs, err := ListGroups()
|
||||
dbs, err := ListNetworks()
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -229,7 +229,7 @@ func IsGroupNameUnique(name string) (bool, error ){
|
||||
|
||||
for i := 0; i < len(dbs); i++ {
|
||||
|
||||
if name == dbs[i].NameID {
|
||||
if name == dbs[i].NetID {
|
||||
isunique = false
|
||||
}
|
||||
}
|
||||
@@ -237,11 +237,11 @@ func IsGroupNameUnique(name string) (bool, error ){
|
||||
return isunique, nil
|
||||
}
|
||||
|
||||
func IsGroupDisplayNameUnique(name string) (bool, error){
|
||||
func IsNetworkDisplayNameUnique(name string) (bool, error){
|
||||
|
||||
isunique := true
|
||||
|
||||
dbs, err := ListGroups()
|
||||
dbs, err := ListNetworks()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -257,13 +257,13 @@ func IsGroupDisplayNameUnique(name string) (bool, error){
|
||||
return isunique, nil
|
||||
}
|
||||
|
||||
func GetGroupNodeNumber(groupName string) (int, error){
|
||||
func GetNetworkNodeNumber(networkName string) (int, error){
|
||||
|
||||
collection := mongoconn.Client.Database("wirecat").Collection("nodes")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"group": groupName}
|
||||
filter := bson.M{"network": networkName}
|
||||
count, err := collection.CountDocuments(ctx, filter)
|
||||
returncount := int(count)
|
||||
|
||||
@@ -278,56 +278,56 @@ func GetGroupNodeNumber(groupName string) (int, error){
|
||||
}
|
||||
|
||||
|
||||
//Kind of a weird name. Should just be GetGroups I think. Consider changing.
|
||||
//Anyway, returns all the groups
|
||||
func ListGroups() ([]models.Group, error){
|
||||
//Kind of a weird name. Should just be GetNetworks I think. Consider changing.
|
||||
//Anyway, returns all the networks
|
||||
func ListNetworks() ([]models.Network, error){
|
||||
|
||||
var groups []models.Group
|
||||
var networks []models.Network
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
|
||||
|
||||
if err != nil {
|
||||
return groups, err
|
||||
return networks, err
|
||||
}
|
||||
|
||||
defer cancel()
|
||||
|
||||
for cur.Next(context.TODO()) {
|
||||
|
||||
var group models.Group
|
||||
err := cur.Decode(&group)
|
||||
var network models.Network
|
||||
err := cur.Decode(&network)
|
||||
if err != nil {
|
||||
return groups, err
|
||||
return networks, err
|
||||
}
|
||||
|
||||
// add group our array
|
||||
groups = append(groups, group)
|
||||
// add network our array
|
||||
networks = append(networks, network)
|
||||
}
|
||||
|
||||
if err := cur.Err(); err != nil {
|
||||
return groups, err
|
||||
return networks, err
|
||||
}
|
||||
|
||||
return groups, err
|
||||
return networks, err
|
||||
}
|
||||
|
||||
//Checks to see if access key is valid
|
||||
//Does so by checking against all keys and seeing if any have the same value
|
||||
//may want to hash values before comparing...consider this
|
||||
//TODO: No error handling!!!!
|
||||
func IsKeyValid(groupname string, keyvalue string) bool{
|
||||
func IsKeyValid(networkname string, keyvalue string) bool{
|
||||
|
||||
group, _ := GetParentGroup(groupname)
|
||||
network, _ := GetParentNetwork(networkname)
|
||||
var key models.AccessKey
|
||||
foundkey := false
|
||||
isvalid := false
|
||||
|
||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
||||
currentkey:= group.AccessKeys[i]
|
||||
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||
currentkey:= network.AccessKeys[i]
|
||||
if currentkey.Value == keyvalue {
|
||||
key = currentkey
|
||||
foundkey = true
|
||||
@@ -341,27 +341,27 @@ func IsKeyValid(groupname string, keyvalue string) bool{
|
||||
return isvalid
|
||||
}
|
||||
//TODO: Contains a fatal error return. Need to change
|
||||
//This just gets a group object from a group name
|
||||
//Should probably just be GetGroup. kind of a dumb name.
|
||||
//Used in contexts where it's not the Parent group.
|
||||
func GetParentGroup(groupname string) (models.Group, error) {
|
||||
//This just gets a network object from a network name
|
||||
//Should probably just be GetNetwork. kind of a dumb name.
|
||||
//Used in contexts where it's not the Parent network.
|
||||
func GetParentNetwork(networkname string) (models.Network, error) {
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": groupname}
|
||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
||||
filter := bson.M{"netid": networkname}
|
||||
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
if err != nil {
|
||||
return group, err
|
||||
return network, err
|
||||
}
|
||||
|
||||
return group, nil
|
||||
return network, nil
|
||||
}
|
||||
|
||||
//Check for valid IPv4 address
|
||||
@@ -418,9 +418,9 @@ func GetNodeObj(id primitive.ObjectID) models.Node {
|
||||
return node
|
||||
}
|
||||
|
||||
//This checks to make sure a group name is valid.
|
||||
//This checks to make sure a network name is valid.
|
||||
//Switch to REGEX?
|
||||
func NameInGroupCharSet(name string) bool{
|
||||
func NameInNetworkCharSet(name string) bool{
|
||||
|
||||
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
|
||||
|
||||
@@ -449,11 +449,11 @@ func NameInNodeCharSet(name string) bool{
|
||||
//The mac address acts as the Unique ID for nodes.
|
||||
//Is this a dumb thing to do? I thought it was cool but maybe it's dumb.
|
||||
//It doesn't really provide a tangible benefit over a random ID
|
||||
func GetNodeByMacAddress(group string, macaddress string) (models.Node, error) {
|
||||
func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
|
||||
|
||||
var node models.Node
|
||||
|
||||
filter := bson.M{"macaddress": macaddress, "group": group}
|
||||
filter := bson.M{"macaddress": macaddress, "network": network}
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
|
||||
@@ -474,17 +474,17 @@ func GetNodeByMacAddress(group string, macaddress string) (models.Node, error) {
|
||||
//and checks against all nodes to see if it's taken, until it finds one.
|
||||
//TODO: We do not handle a case where we run out of addresses.
|
||||
//We will need to handle that eventually
|
||||
func UniqueAddress(groupName string) (string, error){
|
||||
func UniqueAddress(networkName string) (string, error){
|
||||
|
||||
var group models.Group
|
||||
group, err := GetParentGroup(groupName)
|
||||
var network models.Network
|
||||
network, err := GetParentNetwork(networkName)
|
||||
if err != nil {
|
||||
fmt.Println("UniqueAddress encountered an error")
|
||||
return "666", err
|
||||
}
|
||||
|
||||
offset := true
|
||||
ip, ipnet, err := net.ParseCIDR(group.AddressRange)
|
||||
ip, ipnet, err := net.ParseCIDR(network.AddressRange)
|
||||
if err != nil {
|
||||
fmt.Println("UniqueAddress encountered an error")
|
||||
return "666", err
|
||||
@@ -494,12 +494,12 @@ func UniqueAddress(groupName string) (string, error){
|
||||
offset = false
|
||||
continue
|
||||
}
|
||||
if IsIPUnique(groupName, ip.String()){
|
||||
if IsIPUnique(networkName, ip.String()){
|
||||
return ip.String(), err
|
||||
}
|
||||
}
|
||||
//TODO
|
||||
err1 := errors.New("ERROR: No unique addresses available. Check group subnet.")
|
||||
err1 := errors.New("ERROR: No unique addresses available. Check network subnet.")
|
||||
return "W1R3: NO UNIQUE ADDRESSES AVAILABLE", err1
|
||||
}
|
||||
|
||||
@@ -565,7 +565,7 @@ func GenKeyName() string {
|
||||
|
||||
//checks if IP is unique in the address range
|
||||
//used by UniqueAddress
|
||||
func IsIPUnique(group string, ip string) bool {
|
||||
func IsIPUnique(network string, ip string) bool {
|
||||
|
||||
var node models.Node
|
||||
|
||||
@@ -574,7 +574,7 @@ func IsIPUnique(group string, ip string) bool {
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("nodes")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"address": ip, "group": group}
|
||||
filter := bson.M{"address": ip, "network": network}
|
||||
|
||||
err := collection.FindOne(ctx, filter).Decode(&node)
|
||||
|
||||
@@ -593,41 +593,41 @@ func IsIPUnique(group string, ip string) bool {
|
||||
|
||||
//called once key has been used by createNode
|
||||
//reduces value by one and deletes if necessary
|
||||
func DecrimentKey(groupName string, keyvalue string) {
|
||||
func DecrimentKey(networkName string, keyvalue string) {
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
group, err := GetParentGroup(groupName)
|
||||
network, err := GetParentNetwork(networkName)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
for i := len(group.AccessKeys) - 1; i >= 0; i-- {
|
||||
for i := len(network.AccessKeys) - 1; i >= 0; i-- {
|
||||
|
||||
currentkey := group.AccessKeys[i]
|
||||
currentkey := network.AccessKeys[i]
|
||||
if currentkey.Value == keyvalue {
|
||||
group.AccessKeys[i].Uses--
|
||||
if group.AccessKeys[i].Uses < 1 {
|
||||
network.AccessKeys[i].Uses--
|
||||
if network.AccessKeys[i].Uses < 1 {
|
||||
//this is the part where it will call the delete
|
||||
//not sure if there's edge cases I'm missing
|
||||
DeleteKey(group, i)
|
||||
DeleteKey(network, i)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": group.NameID}
|
||||
filter := bson.M{"netid": network.NetID}
|
||||
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"accesskeys", group.AccessKeys},
|
||||
{"accesskeys", network.AccessKeys},
|
||||
}},
|
||||
}
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
@@ -636,26 +636,26 @@ func DecrimentKey(groupName string, keyvalue string) {
|
||||
}
|
||||
}
|
||||
//takes the logic from controllers.deleteKey
|
||||
func DeleteKey(group models.Group, i int) {
|
||||
func DeleteKey(network models.Network, i int) {
|
||||
|
||||
group.AccessKeys = append(group.AccessKeys[:i],
|
||||
group.AccessKeys[i+1:]...)
|
||||
network.AccessKeys = append(network.AccessKeys[:i],
|
||||
network.AccessKeys[i+1:]...)
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
// Create filter
|
||||
filter := bson.M{"nameid": group.NameID}
|
||||
filter := bson.M{"netid": network.NetID}
|
||||
|
||||
// prepare update model.
|
||||
update := bson.D{
|
||||
{"$set", bson.D{
|
||||
{"accesskeys", group.AccessKeys},
|
||||
{"accesskeys", network.AccessKeys},
|
||||
}},
|
||||
}
|
||||
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&group)
|
||||
errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
|
@@ -10,11 +10,11 @@ import (
|
||||
var jwtSecretKey = []byte("(BytesOverTheWire)")
|
||||
|
||||
// CreateJWT func will used to create the JWT while signing in and signing out
|
||||
func CreateJWT(macaddress string, group string) (response string, err error) {
|
||||
func CreateJWT(macaddress string, network string) (response string, err error) {
|
||||
expirationTime := time.Now().Add(5 * time.Minute)
|
||||
claims := &models.Claims{
|
||||
MacAddress: macaddress,
|
||||
Group: group,
|
||||
Network: network,
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
@@ -61,7 +61,7 @@ func VerifyUserToken(tokenString string) (username string, isadmin bool, err err
|
||||
}
|
||||
|
||||
// VerifyToken func will used to Verify the JWT Token while using APIS
|
||||
func VerifyToken(tokenString string) (macaddress string, group string, err error) {
|
||||
func VerifyToken(tokenString string) (macaddress string, network string, err error) {
|
||||
claims := &models.Claims{}
|
||||
|
||||
//this may be a stupid way of serving up a master key
|
||||
@@ -75,7 +75,7 @@ func VerifyToken(tokenString string) (macaddress string, group string, err error
|
||||
})
|
||||
|
||||
if token != nil {
|
||||
return claims.MacAddress, claims.Group, nil
|
||||
return claims.MacAddress, claims.Network, nil
|
||||
}
|
||||
return "", "", err
|
||||
}
|
||||
|
344
group_test.go
344
group_test.go
@@ -11,19 +11,19 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var Groups []models.Group
|
||||
var Networks []models.Network
|
||||
|
||||
func TestCreateGroup(t *testing.T) {
|
||||
group := models.Group{}
|
||||
group.NameID = "skynet"
|
||||
group.AddressRange = "10.71.0.0/16"
|
||||
t.Run("CreateGroup", func(t *testing.T) {
|
||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
||||
func TestCreateNetwork(t *testing.T) {
|
||||
network := models.Network{}
|
||||
network.NetID = "skynet"
|
||||
network.AddressRange = "10.71.0.0/16"
|
||||
t.Run("CreateNetwork", func(t *testing.T) {
|
||||
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "badkey")
|
||||
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -41,23 +41,23 @@ func TestCreateGroup(t *testing.T) {
|
||||
//issue #42
|
||||
t.Skip()
|
||||
})
|
||||
t.Run("DuplicateGroup", func(t *testing.T) {
|
||||
t.Run("DuplicateNetwork", func(t *testing.T) {
|
||||
//issue #42
|
||||
t.Skip()
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroups(t *testing.T) {
|
||||
func TestGetNetworks(t *testing.T) {
|
||||
t.Run("ValidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
||||
err = json.NewDecoder(response.Body).Decode(&Networks)
|
||||
assert.Nil(t, err, err)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -69,19 +69,19 @@ func TestGetGroups(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroup(t *testing.T) {
|
||||
func TestGetNetwork(t *testing.T) {
|
||||
t.Run("ValidToken", func(t *testing.T) {
|
||||
var group models.Group
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network models.Network
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&group)
|
||||
err = json.NewDecoder(response.Body).Decode(&network)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "skynet", group.DisplayName)
|
||||
assert.Equal(t, "skynet", network.DisplayName)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -91,31 +91,31 @@ func TestGetGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroupNodeNumber(t *testing.T) {
|
||||
func TestGetNetworkNodeNumber(t *testing.T) {
|
||||
t.Run("ValidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message int
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
//assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
//assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -125,21 +125,21 @@ func TestGetGroupNodeNumber(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/numnodes", "secretkey")
|
||||
t.Run("BadNetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/numnodes", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteGroup(t *testing.T) {
|
||||
func TestDeleteNetwork(t *testing.T) {
|
||||
t.Run("InvalidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -150,7 +150,7 @@ func TestDeleteGroup(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("ValidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message mongo.DeleteResult
|
||||
@@ -160,21 +160,21 @@ func TestDeleteGroup(t *testing.T) {
|
||||
assert.Equal(t, int64(1), message.DeletedCount)
|
||||
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
t.Run("BadNetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("NodesExist", func(t *testing.T) {
|
||||
t.Skip()
|
||||
})
|
||||
//Create Group for follow-on tests
|
||||
createGroup(t)
|
||||
//Create Network for follow-on tests
|
||||
createNetwork(t)
|
||||
}
|
||||
|
||||
func TestCreateAccessKey(t *testing.T) {
|
||||
@@ -182,7 +182,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
key.Name = "skynet"
|
||||
key.Uses = 10
|
||||
t.Run("MultiUse", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -197,7 +197,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
t.Run("ZeroUse", func(t *testing.T) {
|
||||
//t.Skip()
|
||||
key.Uses = 0
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -211,14 +211,14 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
||||
//t.Skip()
|
||||
//this will fail
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
deleteKey(t, key.Name, "skynet")
|
||||
})
|
||||
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -228,14 +228,14 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
||||
t.Run("BadNetwork", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
@@ -243,7 +243,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
func TestDeleteKey(t *testing.T) {
|
||||
t.Run("KeyValid", func(t *testing.T) {
|
||||
//fails -- deletecount not returned
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message mongo.DeleteResult
|
||||
@@ -254,7 +254,7 @@ func TestDeleteKey(t *testing.T) {
|
||||
})
|
||||
t.Run("InValidKey", func(t *testing.T) {
|
||||
//fails -- status message not returned
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/badkey", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/badkey", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -263,18 +263,18 @@ func TestDeleteKey(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("KeyInValidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup/keys/skynet", "secretkey")
|
||||
t.Run("KeyInValidNetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork/keys/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -289,7 +289,7 @@ func TestDeleteKey(t *testing.T) {
|
||||
func TestGetKeys(t *testing.T) {
|
||||
createKey(t)
|
||||
t.Run("Valid", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -298,18 +298,18 @@ func TestGetKeys(t *testing.T) {
|
||||
assert.Nil(t, err, err)
|
||||
})
|
||||
//deletekeys
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
||||
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -321,29 +321,29 @@ func TestGetKeys(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateGroup(t *testing.T) {
|
||||
var returnedGroup models.Group
|
||||
t.Run("UpdateNameID", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
func TestUpdateNetwork(t *testing.T) {
|
||||
var returnedNetwork models.Network
|
||||
t.Run("UpdateNetID", func(t *testing.T) {
|
||||
type Network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.NameID, returnedGroup.NameID)
|
||||
assert.Equal(t, network.NetID, returnedNetwork.NetID)
|
||||
})
|
||||
t.Run("NameIDInvalidCredentials", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("NetIDInvalidCredentials", func(t *testing.T) {
|
||||
type Network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
var network Network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -352,83 +352,83 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("InvalidNetwork", func(t *testing.T) {
|
||||
type Network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
var network Network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusNotFound, message.Code)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateNameIDTooLong", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("UpdateNetIDTooLong", func(t *testing.T) {
|
||||
type Network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat-skynet"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.NetID = "wirecat-skynet"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateAddress", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
AddressRange string
|
||||
}
|
||||
var group Group
|
||||
group.AddressRange = "10.0.0.1/24"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.AddressRange = "10.0.0.1/24"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.AddressRange, returnedGroup.AddressRange)
|
||||
assert.Equal(t, network.AddressRange, returnedNetwork.AddressRange)
|
||||
})
|
||||
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
AddressRange string
|
||||
}
|
||||
var group Group
|
||||
group.AddressRange = "10.0.0.1/36"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.AddressRange = "10.0.0.1/36"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateDisplayName", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DisplayName string
|
||||
}
|
||||
var group Group
|
||||
group.DisplayName = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DisplayName = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
||||
assert.Equal(t, network.DisplayName, returnedNetwork.DisplayName)
|
||||
|
||||
})
|
||||
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DisplayName string
|
||||
}
|
||||
var group Group
|
||||
var network Network
|
||||
//create name that is longer than 100 chars
|
||||
name := ""
|
||||
for i := 0; i < 101; i++ {
|
||||
name = name + "a"
|
||||
}
|
||||
group.DisplayName = name
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.DisplayName = name
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -438,41 +438,41 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateInterface", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultInterface string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultInterface = "netmaker"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultInterface = "netmaker"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultInterface, returnedGroup.DefaultInterface)
|
||||
assert.Equal(t, network.DefaultInterface, returnedNetwork.DefaultInterface)
|
||||
|
||||
})
|
||||
t.Run("UpdateListenPort", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 6000
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultListenPort = 6000
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
||||
assert.Equal(t, network.DefaultListenPort, returnedNetwork.DefaultListenPort)
|
||||
})
|
||||
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 1023
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultListenPort = 1023
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -482,54 +482,54 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdatePostUP", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultPostUp string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultPostUp, returnedGroup.DefaultPostUp)
|
||||
assert.Equal(t, network.DefaultPostUp, returnedNetwork.DefaultPostUp)
|
||||
})
|
||||
t.Run("UpdatePreUP", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultPreUp string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultPreUp = "test string"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultPreUp = "test string"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultPreUp, returnedGroup.DefaultPreUp)
|
||||
assert.Equal(t, network.DefaultPreUp, returnedNetwork.DefaultPreUp)
|
||||
})
|
||||
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultKeepalive int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultKeepalive = 60
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultKeepalive = 60
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultKeepalive, returnedGroup.DefaultKeepalive)
|
||||
assert.Equal(t, network.DefaultKeepalive, returnedNetwork.DefaultKeepalive)
|
||||
})
|
||||
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultKeepAlive int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultKeepAlive = 1001
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultKeepAlive = 1001
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -541,57 +541,57 @@ func TestUpdateGroup(t *testing.T) {
|
||||
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
||||
//causes panic
|
||||
t.Skip()
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultSaveConfig *bool
|
||||
}
|
||||
var group Group
|
||||
var network Network
|
||||
value := false
|
||||
group.DefaultSaveConfig = &value
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.DefaultSaveConfig = &value
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, *group.DefaultSaveConfig, *returnedGroup.DefaultSaveConfig)
|
||||
assert.Equal(t, *network.DefaultSaveConfig, *returnedNetwork.DefaultSaveConfig)
|
||||
})
|
||||
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
||||
t.Skip()
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
AllowManualSignUp *bool
|
||||
}
|
||||
var group Group
|
||||
var network Network
|
||||
value := true
|
||||
group.AllowManualSignUp = &value
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.AllowManualSignUp = &value
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, *group.AllowManualSignUp, *returnedGroup.AllowManualSignUp)
|
||||
assert.Equal(t, *network.AllowManualSignUp, *returnedNetwork.AllowManualSignUp)
|
||||
})
|
||||
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultCheckInInterval int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultCheckInInterval = 6000
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultCheckInInterval = 6000
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultCheckInInterval, returnedGroup.DefaultCheckInInterval)
|
||||
assert.Equal(t, network.DefaultCheckInInterval, returnedNetwork.DefaultCheckInInterval)
|
||||
})
|
||||
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DefaultCheckInInterval int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultCheckInInterval = 100001
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultCheckInInterval = 100001
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -601,20 +601,20 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("MultipleFields", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
DisplayName string
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 7777
|
||||
group.DisplayName = "multi"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network Network
|
||||
network.DefaultListenPort = 7777
|
||||
network.DisplayName = "multi"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedNetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
||||
assert.Equal(t, network.DisplayName, returnedNetwork.DisplayName)
|
||||
assert.Equal(t, network.DefaultListenPort, returnedNetwork.DefaultListenPort)
|
||||
})
|
||||
}
|
||||
|
133
grpc/node.pb.go
133
grpc/node.pb.go
@@ -123,7 +123,7 @@ type Node struct {
|
||||
Endpoint string `protobuf:"bytes,6,opt,name=endpoint,proto3" json:"endpoint,omitempty"`
|
||||
Macaddress string `protobuf:"bytes,7,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||
Password string `protobuf:"bytes,8,opt,name=password,proto3" json:"password,omitempty"`
|
||||
Nodegroup string `protobuf:"bytes,9,opt,name=nodegroup,proto3" json:"nodegroup,omitempty"`
|
||||
Nodenetwork string `protobuf:"bytes,9,opt,name=nodenetwork,proto3" json:"nodenetwork,omitempty"`
|
||||
Ispending bool `protobuf:"varint,10,opt,name=ispending,proto3" json:"ispending,omitempty"`
|
||||
Postup string `protobuf:"bytes,11,opt,name=postup,proto3" json:"postup,omitempty"`
|
||||
Preup string `protobuf:"bytes,12,opt,name=preup,proto3" json:"preup,omitempty"`
|
||||
@@ -222,9 +222,9 @@ func (m *Node) GetPassword() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Node) GetNodegroup() string {
|
||||
func (m *Node) GetNodenetwork() string {
|
||||
if m != nil {
|
||||
return m.Nodegroup
|
||||
return m.Nodenetwork
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -637,7 +637,7 @@ func (m *UpdateNodeRes) GetNode() *Node {
|
||||
|
||||
type ReadNodeReq struct {
|
||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||
Group string `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"`
|
||||
Network string `protobuf:"bytes,2,opt,name=network,proto3" json:"network,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
@@ -675,9 +675,9 @@ func (m *ReadNodeReq) GetMacaddress() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *ReadNodeReq) GetGroup() string {
|
||||
func (m *ReadNodeReq) GetNetwork() string {
|
||||
if m != nil {
|
||||
return m.Group
|
||||
return m.Network
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -723,7 +723,7 @@ func (m *ReadNodeRes) GetNode() *Node {
|
||||
|
||||
type DeleteNodeReq struct {
|
||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||
GroupName string `protobuf:"bytes,2,opt,name=groupName,proto3" json:"groupName,omitempty"`
|
||||
NetworkName string `protobuf:"bytes,2,opt,name=networkName,proto3" json:"networkName,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
@@ -761,9 +761,9 @@ func (m *DeleteNodeReq) GetMacaddress() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *DeleteNodeReq) GetGroupName() string {
|
||||
func (m *DeleteNodeReq) GetNetworkName() string {
|
||||
if m != nil {
|
||||
return m.GroupName
|
||||
return m.NetworkName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -809,7 +809,7 @@ func (m *DeleteNodeRes) GetSuccess() bool {
|
||||
|
||||
type GetPeersReq struct {
|
||||
Macaddress string `protobuf:"bytes,1,opt,name=macaddress,proto3" json:"macaddress,omitempty"`
|
||||
Group string `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"`
|
||||
Network string `protobuf:"bytes,2,opt,name=network,proto3" json:"network,omitempty"`
|
||||
XXX_NoUnkeyedLiteral struct{} `json:"-"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
XXX_sizecache int32 `json:"-"`
|
||||
@@ -847,9 +847,9 @@ func (m *GetPeersReq) GetMacaddress() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *GetPeersReq) GetGroup() string {
|
||||
func (m *GetPeersReq) GetNetwork() string {
|
||||
if m != nil {
|
||||
return m.Group
|
||||
return m.Network
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -994,59 +994,58 @@ func init() {
|
||||
func init() { proto.RegisterFile("grpc/node.proto", fileDescriptor_d13bd996b67da4ef) }
|
||||
|
||||
var fileDescriptor_d13bd996b67da4ef = []byte{
|
||||
// 850 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x56, 0xdd, 0x6a, 0xe3, 0x46,
|
||||
0x14, 0xc6, 0x5e, 0x3b, 0x96, 0x8f, 0xe3, 0x24, 0x3b, 0xc9, 0x96, 0x41, 0x84, 0x10, 0x44, 0x29,
|
||||
0xd9, 0xd2, 0xc4, 0x69, 0x0a, 0xa5, 0x77, 0x85, 0xa6, 0x50, 0x0a, 0xed, 0x52, 0x54, 0x7a, 0xd3,
|
||||
0xbb, 0x89, 0xe6, 0x44, 0x2b, 0xac, 0xcc, 0x8c, 0x35, 0x92, 0x43, 0x1e, 0xa0, 0x8f, 0xd6, 0x37,
|
||||
0xea, 0x65, 0x2f, 0xca, 0xfc, 0xc8, 0xfa, 0x89, 0x9b, 0x64, 0x73, 0xe7, 0xf3, 0xcd, 0xf9, 0x3f,
|
||||
0xdf, 0x39, 0x16, 0xec, 0xa7, 0x85, 0x4a, 0x16, 0x42, 0x72, 0xbc, 0x50, 0x85, 0x2c, 0x25, 0x19,
|
||||
0x99, 0xdf, 0x11, 0x87, 0xdd, 0x5f, 0x64, 0x9a, 0x89, 0x18, 0x57, 0x15, 0xea, 0x92, 0x9c, 0x00,
|
||||
0xdc, 0xb1, 0x84, 0x71, 0x5e, 0xa0, 0xd6, 0x74, 0x70, 0x3a, 0x38, 0x9b, 0xc6, 0x2d, 0x84, 0x84,
|
||||
0x10, 0x28, 0xa6, 0xf5, 0xbd, 0x2c, 0x38, 0x1d, 0xda, 0xd7, 0x8d, 0x4c, 0x28, 0x4c, 0x04, 0x96,
|
||||
0xf7, 0xb2, 0x58, 0xd2, 0x37, 0xf6, 0xa9, 0x16, 0xa3, 0xaf, 0x61, 0xee, 0xa3, 0x68, 0x25, 0x85,
|
||||
0x46, 0x72, 0x0a, 0x33, 0x96, 0x24, 0xa8, 0x75, 0x29, 0x97, 0x28, 0x7c, 0x9c, 0x36, 0x14, 0xfd,
|
||||
0x33, 0x82, 0xd1, 0x07, 0xc9, 0x91, 0xec, 0xc1, 0x30, 0xe3, 0x5e, 0x63, 0x98, 0x71, 0x42, 0x60,
|
||||
0x24, 0xd8, 0x1d, 0xfa, 0xe8, 0xf6, 0xb7, 0x89, 0x5c, 0xa7, 0xec, 0x23, 0xd7, 0xf9, 0x9e, 0x00,
|
||||
0xe4, 0x99, 0x2e, 0x51, 0x28, 0x59, 0x94, 0x74, 0x74, 0x3a, 0x38, 0x1b, 0xc7, 0x2d, 0x84, 0x1c,
|
||||
0xc3, 0x54, 0x55, 0x37, 0x79, 0x96, 0x2c, 0xf1, 0x81, 0x8e, 0xad, 0x6d, 0x03, 0x98, 0x6a, 0x51,
|
||||
0x70, 0x25, 0x33, 0x51, 0xd2, 0x1d, 0x57, 0x6d, 0x2d, 0xf7, 0x3a, 0x35, 0x79, 0xb2, 0x53, 0x41,
|
||||
0xaf, 0x53, 0xc7, 0x30, 0x35, 0xdd, 0x4f, 0x0b, 0x59, 0x29, 0x3a, 0x75, 0x51, 0x37, 0x80, 0x79,
|
||||
0xcd, 0xb4, 0x42, 0xc1, 0x33, 0x91, 0x52, 0x38, 0x1d, 0x9c, 0x05, 0x71, 0x03, 0x90, 0xcf, 0x60,
|
||||
0x47, 0x49, 0x5d, 0x56, 0x8a, 0xce, 0xac, 0xa1, 0x97, 0xc8, 0x11, 0x8c, 0x55, 0x81, 0x95, 0xa2,
|
||||
0xbb, 0x16, 0x76, 0x82, 0xf1, 0xb5, 0x44, 0x54, 0x2c, 0xcf, 0xd6, 0x48, 0xe7, 0xb6, 0xfc, 0x06,
|
||||
0x30, 0x35, 0x68, 0xb6, 0xc6, 0x44, 0x8a, 0xdb, 0x2c, 0xa5, 0x7b, 0x36, 0x54, 0x0b, 0x31, 0xd6,
|
||||
0x6e, 0x26, 0xa6, 0x3b, 0xfb, 0x2e, 0xcf, 0x0d, 0x60, 0xf3, 0x14, 0x25, 0x16, 0xb7, 0x2c, 0x41,
|
||||
0x7a, 0xe0, 0x5e, 0x37, 0x80, 0x19, 0x71, 0xce, 0x74, 0x99, 0x7c, 0xc4, 0x64, 0x99, 0x09, 0xfa,
|
||||
0xd6, 0x8d, 0xb8, 0x05, 0x91, 0x08, 0x76, 0x8d, 0x78, 0x27, 0x79, 0x76, 0x9b, 0x21, 0xa7, 0xc4,
|
||||
0xaa, 0x74, 0x30, 0x72, 0x06, 0xfb, 0x5e, 0xdd, 0x7a, 0x5e, 0xb3, 0x9c, 0x1e, 0xda, 0x2a, 0xfa,
|
||||
0xb0, 0xf5, 0x26, 0x13, 0x96, 0xd7, 0x13, 0x39, 0xf2, 0xde, 0x5a, 0x98, 0xc9, 0xc9, 0x74, 0x2b,
|
||||
0xf9, 0xc8, 0x44, 0x8a, 0x9a, 0xbe, 0x73, 0x39, 0xb5, 0xa0, 0xe8, 0xaf, 0x21, 0xec, 0x5f, 0x1b,
|
||||
0xcf, 0x3f, 0x37, 0x64, 0xa5, 0x30, 0xd1, 0x95, 0xad, 0xda, 0xd2, 0x30, 0x88, 0x6b, 0x91, 0x7c,
|
||||
0x01, 0x7b, 0x02, 0x91, 0x2b, 0xc4, 0xa2, 0x52, 0x9c, 0x95, 0x8e, 0x95, 0x41, 0xdc, 0x43, 0xc9,
|
||||
0x97, 0x70, 0x60, 0x10, 0xd7, 0x55, 0xaf, 0xf9, 0xc6, 0x6a, 0x3e, 0xc2, 0x4d, 0x8e, 0x86, 0x0a,
|
||||
0x77, 0xa8, 0x35, 0x4b, 0xd1, 0x52, 0x76, 0x1a, 0xb7, 0xa1, 0x2e, 0x3f, 0xc6, 0x7d, 0x7e, 0x7c,
|
||||
0x0e, 0x73, 0xe3, 0x73, 0x89, 0x0f, 0x3e, 0xd0, 0x8e, 0xd5, 0xe8, 0x82, 0x66, 0xf2, 0x06, 0xe0,
|
||||
0x98, 0x63, 0x89, 0x96, 0xbd, 0x41, 0xdc, 0x42, 0xa2, 0xbf, 0x07, 0x30, 0xff, 0x0d, 0xb1, 0xd0,
|
||||
0x9b, 0x2e, 0xbc, 0x7e, 0x53, 0x5e, 0xbf, 0x9d, 0xfd, 0x99, 0x4e, 0xb6, 0xcc, 0xf4, 0x49, 0x86,
|
||||
0x47, 0x0b, 0x98, 0x5f, 0x17, 0xc8, 0x4a, 0x34, 0xb7, 0x24, 0xc6, 0x15, 0x39, 0x01, 0x7b, 0xf8,
|
||||
0xec, 0x24, 0x67, 0x57, 0x70, 0x61, 0x2f, 0xa2, 0x7d, 0x74, 0x07, 0xb1, 0x67, 0xa0, 0x5f, 0x62,
|
||||
0xf0, 0x87, 0xed, 0xe9, 0x27, 0x44, 0x68, 0x1b, 0x3c, 0x1f, 0xe1, 0x1a, 0x66, 0x31, 0x32, 0xde,
|
||||
0xf8, 0x7f, 0xfa, 0x44, 0x1f, 0xc1, 0xd8, 0x1d, 0x16, 0x77, 0x21, 0x9d, 0x10, 0x9d, 0xb7, 0x9d,
|
||||
0x3c, 0x1f, 0xf3, 0x57, 0x98, 0xff, 0x68, 0x99, 0xf0, 0xd2, 0xa8, 0xc7, 0x30, 0xb5, 0x81, 0x3e,
|
||||
0x34, 0xb7, 0xb9, 0x01, 0xa2, 0xf7, 0x5d, 0x77, 0xfa, 0xff, 0x77, 0xca, 0x54, 0xfb, 0x13, 0x96,
|
||||
0x9e, 0x7b, 0xaf, 0xad, 0xf6, 0xbb, 0xb6, 0x13, 0x4d, 0xde, 0xc3, 0xd8, 0x6c, 0xa3, 0xf6, 0xe5,
|
||||
0x1e, 0xba, 0x72, 0x3b, 0xfc, 0x8e, 0x9d, 0x46, 0xf4, 0x15, 0xc0, 0x66, 0xff, 0x57, 0x2f, 0x68,
|
||||
0x53, 0xa3, 0xad, 0xc9, 0xf7, 0x9b, 0x63, 0x55, 0x78, 0xaf, 0xde, 0xf0, 0x9d, 0x33, 0xec, 0x1d,
|
||||
0x96, 0xb8, 0xaf, 0x7d, 0xf5, 0xef, 0x10, 0x66, 0xc6, 0xfb, 0xef, 0x58, 0xac, 0xb3, 0x04, 0xc9,
|
||||
0x25, 0x8c, 0xed, 0xff, 0x26, 0x21, 0xce, 0x41, 0xfb, 0xaf, 0x3a, 0x3c, 0xec, 0x60, 0x7e, 0x4b,
|
||||
0xbf, 0x05, 0x68, 0xe8, 0x4b, 0xbc, 0x4a, 0x67, 0x03, 0xc2, 0x2d, 0xa0, 0x26, 0x97, 0x10, 0xd4,
|
||||
0xf4, 0x20, 0x6f, 0x9d, 0x42, 0x8b, 0x73, 0xe1, 0x23, 0x48, 0x9b, 0x48, 0x0d, 0x8d, 0xeb, 0x48,
|
||||
0x9d, 0x4d, 0x08, 0xb7, 0x80, 0xd6, 0xae, 0xa1, 0x42, 0x6d, 0xd7, 0xe1, 0x5a, 0xb8, 0x05, 0xd4,
|
||||
0xe4, 0x0a, 0x82, 0x7a, 0xa4, 0x75, 0x86, 0x2d, 0x9e, 0x84, 0x8f, 0x20, 0x7d, 0x39, 0x20, 0xe7,
|
||||
0x30, 0xf1, 0x3d, 0x27, 0x07, 0xbd, 0x11, 0xac, 0xc2, 0x3e, 0xa2, 0x7f, 0x58, 0xfc, 0x79, 0x9e,
|
||||
0x4a, 0x99, 0xe6, 0x78, 0x91, 0xca, 0x9c, 0x89, 0xf4, 0x42, 0x16, 0xe9, 0xc2, 0x7e, 0x2d, 0xdd,
|
||||
0x54, 0xb7, 0x8b, 0xf2, 0x41, 0xa1, 0x5e, 0x2c, 0x85, 0xbc, 0x17, 0xf6, 0x3b, 0x4a, 0xdd, 0xdc,
|
||||
0xec, 0xd8, 0xc7, 0x6f, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x28, 0x40, 0xb5, 0xd0, 0x5d, 0x09,
|
||||
0x00, 0x00,
|
||||
// 847 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x96, 0xdd, 0x6e, 0xe3, 0x44,
|
||||
0x14, 0xc7, 0x95, 0x6c, 0xd2, 0xb8, 0x27, 0x4d, 0xdb, 0x9d, 0xee, 0xa2, 0x91, 0x85, 0xaa, 0xc8,
|
||||
0x42, 0xa8, 0x8b, 0x68, 0x53, 0x8a, 0x84, 0xb8, 0x43, 0x62, 0x91, 0x56, 0x48, 0xb0, 0x02, 0x23,
|
||||
0x6e, 0xb8, 0x9b, 0x7a, 0x4e, 0xbd, 0x56, 0x9c, 0x99, 0xa9, 0xc7, 0x49, 0xd5, 0x07, 0xe0, 0xd1,
|
||||
0x78, 0x27, 0x2e, 0xb8, 0x40, 0xf3, 0xe1, 0x78, 0xec, 0x86, 0x76, 0xd9, 0xbd, 0xcb, 0xfc, 0xe6,
|
||||
0x7c, 0xcc, 0x39, 0xf3, 0x9f, 0x13, 0xc3, 0x51, 0x5e, 0xa9, 0x6c, 0x21, 0x24, 0xc7, 0x0b, 0x55,
|
||||
0xc9, 0x5a, 0x92, 0x91, 0xf9, 0x9d, 0x70, 0x38, 0xf8, 0x49, 0xe6, 0x85, 0x48, 0xf1, 0x76, 0x8d,
|
||||
0xba, 0x26, 0xa7, 0x00, 0x2b, 0x96, 0x31, 0xce, 0x2b, 0xd4, 0x9a, 0x0e, 0xe6, 0x83, 0xb3, 0xfd,
|
||||
0x34, 0x20, 0x24, 0x86, 0x48, 0x31, 0xad, 0xef, 0x64, 0xc5, 0xe9, 0xd0, 0xee, 0x6e, 0xd7, 0x84,
|
||||
0xc2, 0x44, 0x60, 0x7d, 0x27, 0xab, 0x25, 0x7d, 0x66, 0xb7, 0x9a, 0x65, 0xf2, 0x15, 0xcc, 0x7c,
|
||||
0x16, 0xad, 0xa4, 0xd0, 0x48, 0xe6, 0x30, 0x65, 0x59, 0x86, 0x5a, 0xd7, 0x72, 0x89, 0xc2, 0xe7,
|
||||
0x09, 0x51, 0xf2, 0xf7, 0x08, 0x46, 0x6f, 0x25, 0x47, 0x72, 0x08, 0xc3, 0x82, 0x7b, 0x8b, 0x61,
|
||||
0xc1, 0x09, 0x81, 0x91, 0x60, 0x2b, 0xf4, 0xd9, 0xed, 0x6f, 0x93, 0xb9, 0x39, 0xb2, 0xcf, 0xdc,
|
||||
0x9c, 0xf7, 0x14, 0xa0, 0x2c, 0x74, 0x8d, 0x42, 0xc9, 0xaa, 0xa6, 0xa3, 0xf9, 0xe0, 0x6c, 0x9c,
|
||||
0x06, 0x84, 0x7c, 0x0a, 0xfb, 0x6a, 0x7d, 0x5d, 0x16, 0xd9, 0x12, 0xef, 0xe9, 0xd8, 0xfa, 0xb6,
|
||||
0xc0, 0x54, 0x8b, 0x82, 0x2b, 0x59, 0x88, 0x9a, 0xee, 0xb9, 0x6a, 0x9b, 0x75, 0xaf, 0x53, 0x93,
|
||||
0x47, 0x3b, 0x15, 0xf5, 0x3a, 0x35, 0x87, 0xa9, 0xe9, 0x7e, 0xd3, 0xad, 0x7d, 0x57, 0x7e, 0x80,
|
||||
0xcc, 0xb9, 0x0a, 0xad, 0x50, 0xf0, 0x42, 0xe4, 0x14, 0xe6, 0x83, 0xb3, 0x28, 0x6d, 0x01, 0xf9,
|
||||
0x04, 0xf6, 0x94, 0xd4, 0xf5, 0x5a, 0xd1, 0xa9, 0x75, 0xf5, 0x2b, 0xf2, 0x02, 0xc6, 0xaa, 0xc2,
|
||||
0xb5, 0xa2, 0x07, 0x16, 0xbb, 0x85, 0x89, 0xb5, 0x44, 0x54, 0xac, 0x2c, 0x36, 0x48, 0x67, 0xb6,
|
||||
0x05, 0x2d, 0x30, 0x75, 0x68, 0xb6, 0xc1, 0x4c, 0x8a, 0x9b, 0x22, 0xa7, 0x87, 0x36, 0x55, 0x40,
|
||||
0x8c, 0xb7, 0xbb, 0x17, 0xd3, 0xa1, 0x23, 0xd7, 0xa1, 0x2d, 0xb0, 0xe7, 0x14, 0x35, 0x56, 0x37,
|
||||
0x2c, 0x43, 0x7a, 0xec, 0x76, 0xb7, 0xc0, 0xd4, 0x59, 0x32, 0x5d, 0x67, 0xef, 0x30, 0x5b, 0x16,
|
||||
0x82, 0x3e, 0x77, 0x75, 0x06, 0x88, 0x24, 0x70, 0x60, 0x96, 0x2b, 0xc9, 0x8b, 0x9b, 0x02, 0x39,
|
||||
0x25, 0xd6, 0xa4, 0xc3, 0xc8, 0x19, 0x1c, 0x79, 0x73, 0x1b, 0x79, 0xc3, 0x4a, 0x7a, 0x62, 0xab,
|
||||
0xe8, 0x63, 0x1b, 0x4d, 0x66, 0xac, 0x6c, 0x6e, 0xe5, 0x85, 0x8f, 0x16, 0x30, 0x73, 0x26, 0xd3,
|
||||
0xad, 0xec, 0x1d, 0x13, 0x39, 0x6a, 0xfa, 0xd2, 0x9d, 0x29, 0x40, 0xc9, 0x9f, 0x43, 0x38, 0x7a,
|
||||
0x6d, 0x22, 0xff, 0xd8, 0x0a, 0x96, 0xc2, 0x44, 0xaf, 0x6d, 0xd5, 0x56, 0x8a, 0x51, 0xda, 0x2c,
|
||||
0xc9, 0xe7, 0x70, 0x28, 0x10, 0xb9, 0x42, 0xac, 0xd6, 0x8a, 0xb3, 0xda, 0x29, 0x33, 0x4a, 0x7b,
|
||||
0x94, 0x7c, 0x01, 0xc7, 0x86, 0xb8, 0xae, 0x7a, 0xcb, 0x67, 0xd6, 0xf2, 0x01, 0x6f, 0xf4, 0xb1,
|
||||
0x42, 0xad, 0x59, 0x8e, 0x56, 0xb6, 0x5e, 0x1f, 0x1e, 0x75, 0xf5, 0x31, 0xee, 0xeb, 0xe3, 0x33,
|
||||
0x98, 0x99, 0x98, 0x4b, 0xbc, 0xf7, 0x89, 0xf6, 0xac, 0x45, 0x17, 0x9a, 0x9b, 0x37, 0x80, 0x63,
|
||||
0x89, 0x35, 0x5a, 0x05, 0x47, 0x69, 0x40, 0x92, 0xbf, 0x06, 0x30, 0xfb, 0x05, 0xb1, 0xd2, 0xdb,
|
||||
0x2e, 0x7c, 0xf8, 0x6b, 0xf9, 0xf0, 0x17, 0xda, 0xbf, 0xd3, 0xc9, 0x8e, 0x3b, 0x7d, 0x54, 0xe1,
|
||||
0xc9, 0x02, 0x66, 0xaf, 0x2b, 0x64, 0x35, 0x9a, 0x79, 0x92, 0xe2, 0x2d, 0x39, 0x05, 0x3b, 0xfc,
|
||||
0xec, 0x4d, 0x4e, 0xaf, 0xe0, 0xc2, 0x4e, 0x45, 0xbb, 0xe9, 0x86, 0x62, 0xcf, 0x41, 0xbf, 0x8f,
|
||||
0xc3, 0xef, 0xb6, 0xa7, 0xff, 0x23, 0x43, 0xe8, 0xf0, 0x74, 0x86, 0x37, 0x30, 0x4d, 0x91, 0xf1,
|
||||
0x36, 0xfe, 0xe3, 0x63, 0x3a, 0x18, 0xc5, 0xc3, 0xee, 0x28, 0x3e, 0x0f, 0x03, 0x3d, 0x9d, 0xf7,
|
||||
0x57, 0x98, 0xfd, 0x60, 0xd5, 0xf0, 0xbe, 0x99, 0x8d, 0x74, 0x5d, 0xaa, 0xb7, 0xed, 0x94, 0x0e,
|
||||
0x51, 0xf2, 0xaa, 0x1b, 0x52, 0xff, 0xf7, 0xdb, 0x32, 0x55, 0xbf, 0xc1, 0xda, 0x6b, 0xf0, 0x63,
|
||||
0xaa, 0xfe, 0x36, 0x0c, 0xa4, 0xc9, 0x2b, 0x18, 0x9b, 0x97, 0xa9, 0x7d, 0xd9, 0x27, 0xae, 0xec,
|
||||
0x8e, 0xd6, 0x53, 0x67, 0x91, 0x7c, 0x09, 0xb0, 0x9d, 0x05, 0x4f, 0xdf, 0xeb, 0xcf, 0x81, 0xb5,
|
||||
0x26, 0xdf, 0x6d, 0x07, 0x57, 0xe5, 0xa3, 0x7a, 0xc7, 0x97, 0xce, 0xb1, 0x37, 0x64, 0xd2, 0xbe,
|
||||
0xf5, 0xd5, 0x3f, 0x43, 0x98, 0x9a, 0xe8, 0xbf, 0x61, 0xb5, 0x29, 0x32, 0x24, 0x97, 0x30, 0xb6,
|
||||
0xff, 0xa3, 0x84, 0xb8, 0x00, 0xe1, 0x5f, 0x77, 0x7c, 0xd2, 0x61, 0xfe, 0xc5, 0x7e, 0x03, 0xd0,
|
||||
0x4a, 0x99, 0x78, 0x93, 0xce, 0x6b, 0x88, 0x77, 0x40, 0x4d, 0x2e, 0x21, 0x6a, 0x64, 0x42, 0x9e,
|
||||
0x3b, 0x83, 0x40, 0x7f, 0xf1, 0x03, 0xa4, 0x4d, 0xa6, 0x56, 0xd2, 0x4d, 0xa6, 0xce, 0xab, 0x88,
|
||||
0x77, 0x40, 0xeb, 0xd7, 0xca, 0xa1, 0xf1, 0xeb, 0x68, 0x2e, 0xde, 0x01, 0x35, 0xb9, 0x82, 0xa8,
|
||||
0xb9, 0xd2, 0xe6, 0x84, 0x81, 0x56, 0xe2, 0x07, 0x48, 0x5f, 0x0e, 0xc8, 0x39, 0x4c, 0x7c, 0xcf,
|
||||
0xc9, 0x71, 0xef, 0x0a, 0x6e, 0xe3, 0x3e, 0xd1, 0xdf, 0x2f, 0xfe, 0x38, 0xcf, 0xa5, 0xcc, 0x4b,
|
||||
0xbc, 0xc8, 0x65, 0xc9, 0x44, 0x7e, 0x21, 0xab, 0x7c, 0x61, 0xbf, 0x9e, 0xae, 0xd7, 0x37, 0x8b,
|
||||
0xfa, 0x5e, 0xa1, 0x5e, 0x2c, 0x85, 0xbc, 0x13, 0xf6, 0xbb, 0x4a, 0x5d, 0x5f, 0xef, 0xd9, 0xcd,
|
||||
0xaf, 0xff, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x18, 0x12, 0x66, 0x6d, 0x09, 0x00, 0x00,
|
||||
}
|
||||
|
@@ -29,7 +29,7 @@ message Node {
|
||||
string endpoint = 6;
|
||||
string macaddress = 7;
|
||||
string password = 8;
|
||||
string nodegroup = 9;
|
||||
string nodenetwork = 9;
|
||||
bool ispending = 10;
|
||||
string postup = 11;
|
||||
string preup = 12;
|
||||
@@ -81,7 +81,7 @@ message UpdateNodeRes {
|
||||
|
||||
message ReadNodeReq {
|
||||
string macaddress = 1;
|
||||
string group = 2;
|
||||
string network = 2;
|
||||
}
|
||||
|
||||
message ReadNodeRes {
|
||||
@@ -90,7 +90,7 @@ message ReadNodeRes {
|
||||
|
||||
message DeleteNodeReq {
|
||||
string macaddress = 1;
|
||||
string groupName = 2;
|
||||
string networkName = 2;
|
||||
}
|
||||
|
||||
message DeleteNodeRes {
|
||||
@@ -99,7 +99,7 @@ message DeleteNodeRes {
|
||||
|
||||
message GetPeersReq {
|
||||
string macaddress = 1;
|
||||
string group = 2;
|
||||
string network = 2;
|
||||
}
|
||||
|
||||
message GetPeersRes {
|
||||
|
79
main.go
79
main.go
@@ -5,6 +5,7 @@ package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"flag"
|
||||
"github.com/gravitl/netmaker/models"
|
||||
"github.com/gravitl/netmaker/controllers"
|
||||
"github.com/gravitl/netmaker/serverctl"
|
||||
@@ -18,8 +19,10 @@ import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"net"
|
||||
"context"
|
||||
"strconv"
|
||||
"sync"
|
||||
"os/signal"
|
||||
service "github.com/gravitl/netmaker/controllers"
|
||||
@@ -32,34 +35,59 @@ var PortGRPC string
|
||||
|
||||
//Start MongoDB Connection and start API Request Handler
|
||||
func main() {
|
||||
|
||||
var clientmode string
|
||||
var defaultnet string
|
||||
flag.StringVar(&clientmode, "clientmode", "on", "Have a client on the server")
|
||||
flag.StringVar(&defaultnet, "defaultnet", "on", "Create a default network")
|
||||
flag.Parse()
|
||||
if clientmode == "on" {
|
||||
|
||||
cmd := exec.Command("id", "-u")
|
||||
output, err := cmd.Output()
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
i, err := strconv.Atoi(string(output[:len(output)-1]))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if i != 0 {
|
||||
log.Fatal("To run in client mode requires root privileges. Either turn off client mode with the --clientmode=off flag, or run with sudo.")
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Server starting...")
|
||||
mongoconn.ConnectDatabase()
|
||||
installserver := false
|
||||
if !(defaultnet == "off") {
|
||||
if config.Config.Server.CreateDefault {
|
||||
created, err := createDefaultNetwork()
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating default network: %v", err)
|
||||
}
|
||||
if created {
|
||||
if created && clientmode != "off" {
|
||||
installserver = true
|
||||
}
|
||||
}
|
||||
|
||||
var waitgroup sync.WaitGroup
|
||||
}
|
||||
var waitnetwork sync.WaitGroup
|
||||
|
||||
if config.Config.Server.AgentBackend {
|
||||
waitgroup.Add(1)
|
||||
go runGRPC(&waitgroup, installserver)
|
||||
waitnetwork.Add(1)
|
||||
go runGRPC(&waitnetwork, installserver)
|
||||
}
|
||||
|
||||
if config.Config.Server.RestBackend {
|
||||
waitgroup.Add(1)
|
||||
controller.HandleRESTRequests(&waitgroup)
|
||||
waitnetwork.Add(1)
|
||||
controller.HandleRESTRequests(&waitnetwork)
|
||||
}
|
||||
if !config.Config.Server.RestBackend && !config.Config.Server.AgentBackend {
|
||||
fmt.Println("Oops! No Server Mode selected. Nothing being served.")
|
||||
}
|
||||
waitgroup.Wait()
|
||||
waitnetwork.Wait()
|
||||
fmt.Println("Exiting now.")
|
||||
}
|
||||
|
||||
@@ -193,35 +221,38 @@ func setGlobalConfig(globalconf models.GlobalConfig) (error) {
|
||||
func createDefaultNetwork() (bool, error) {
|
||||
|
||||
iscreated := false
|
||||
exists, err := functions.GroupExists(config.Config.Server.DefaultNetName)
|
||||
exists, err := functions.NetworkExists(config.Config.Server.DefaultNetName)
|
||||
|
||||
if exists || err != nil {
|
||||
fmt.Println("Default group already exists")
|
||||
fmt.Println("Skipping default group create")
|
||||
fmt.Println("Default network already exists")
|
||||
fmt.Println("Skipping default network create")
|
||||
return iscreated, err
|
||||
} else {
|
||||
|
||||
var group models.Group
|
||||
var network models.Network
|
||||
|
||||
group.NameID = config.Config.Server.DefaultNetName
|
||||
group.AddressRange = config.Config.Server.DefaultNetRange
|
||||
group.DisplayName = config.Config.Server.DefaultNetName
|
||||
group.SetDefaults()
|
||||
group.SetNodesLastModified()
|
||||
group.SetGroupLastModified()
|
||||
group.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
network.NetID = config.Config.Server.DefaultNetName
|
||||
network.AddressRange = config.Config.Server.DefaultNetRange
|
||||
network.DisplayName = config.Config.Server.DefaultNetName
|
||||
network.SetDefaults()
|
||||
network.SetNodesLastModified()
|
||||
network.SetNetworkLastModified()
|
||||
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
priv := false
|
||||
network.IsPrivate = &priv
|
||||
network.KeyUpdateTimeStamp = time.Now().Unix()
|
||||
allow := true
|
||||
group.AllowManualSignUp = &allow
|
||||
network.AllowManualSignUp = &allow
|
||||
|
||||
fmt.Println("Creating default group.")
|
||||
fmt.Println("Creating default network.")
|
||||
|
||||
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
|
||||
// insert our group into the group table
|
||||
_, err = collection.InsertOne(ctx, group)
|
||||
// insert our network into the network table
|
||||
_, err = collection.InsertOne(ctx, network)
|
||||
defer cancel()
|
||||
|
||||
}
|
||||
|
@@ -6,15 +6,15 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
//Group Struct
|
||||
//Network Struct
|
||||
//At some point, need to replace all instances of Name with something else like Identifier
|
||||
type Group struct {
|
||||
type Network struct {
|
||||
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
|
||||
AddressRange string `json:"addressrange" bson:"addressrange" validate:"required,addressrange_valid"`
|
||||
DisplayName string `json:"displayname,omitempty" bson:"displayname,omitempty" validate:"omitempty,displayname_unique,min=1,max=100"`
|
||||
NameID string `json:"nameid" bson:"nameid" validate:"required,nameid_valid,min=1,max=12"`
|
||||
NetID string `json:"netid" bson:"netid" validate:"required,netid_valid,min=1,max=12"`
|
||||
NodesLastModified int64 `json:"nodeslastmodified" bson:"nodeslastmodified"`
|
||||
GroupLastModified int64 `json:"grouplastmodified" bson:"grouplastmodified"`
|
||||
NetworkLastModified int64 `json:"networklastmodified" bson:"networklastmodified"`
|
||||
DefaultInterface string `json:"defaulinterface" bson:"defaultinterface"`
|
||||
DefaultListenPort int32 `json:"defaultlistenport,omitempty" bson:"defaultlistenport,omitempty" validate:"omitempty,numeric,min=1024,max=65535"`
|
||||
DefaultPostUp string `json:"defaultpostup" bson:"defaultpostup"`
|
||||
@@ -31,42 +31,42 @@ type Group struct {
|
||||
|
||||
//TODO:
|
||||
//Not sure if we need the below two functions. Got rid of one of the calls. May want to revisit
|
||||
func(group *Group) SetNodesLastModified(){
|
||||
group.NodesLastModified = time.Now().Unix()
|
||||
func(network *Network) SetNodesLastModified(){
|
||||
network.NodesLastModified = time.Now().Unix()
|
||||
}
|
||||
|
||||
func(group *Group) SetGroupLastModified(){
|
||||
group.GroupLastModified = time.Now().Unix()
|
||||
func(network *Network) SetNetworkLastModified(){
|
||||
network.NetworkLastModified = time.Now().Unix()
|
||||
}
|
||||
|
||||
func(group *Group) SetDefaults(){
|
||||
if group.DisplayName == "" {
|
||||
group.DisplayName = group.NameID
|
||||
func(network *Network) SetDefaults(){
|
||||
if network.DisplayName == "" {
|
||||
network.DisplayName = network.NetID
|
||||
}
|
||||
if group.DefaultInterface == "" {
|
||||
group.DefaultInterface = "nm-" + group.NameID
|
||||
if network.DefaultInterface == "" {
|
||||
network.DefaultInterface = "nm-" + network.NetID
|
||||
}
|
||||
if group.DefaultListenPort == 0 {
|
||||
group.DefaultListenPort = 51821
|
||||
if network.DefaultListenPort == 0 {
|
||||
network.DefaultListenPort = 51821
|
||||
}
|
||||
if group.DefaultPreUp == "" {
|
||||
if network.DefaultPreUp == "" {
|
||||
|
||||
}
|
||||
if group.DefaultSaveConfig == nil {
|
||||
if network.DefaultSaveConfig == nil {
|
||||
defaultsave := true
|
||||
group.DefaultSaveConfig = &defaultsave
|
||||
network.DefaultSaveConfig = &defaultsave
|
||||
}
|
||||
if group.DefaultKeepalive == 0 {
|
||||
group.DefaultKeepalive = 20
|
||||
if network.DefaultKeepalive == 0 {
|
||||
network.DefaultKeepalive = 20
|
||||
}
|
||||
if group.DefaultPostUp == "" {
|
||||
if network.DefaultPostUp == "" {
|
||||
}
|
||||
//Check-In Interval for Nodes, In Seconds
|
||||
if group.DefaultCheckInInterval == 0 {
|
||||
group.DefaultCheckInInterval = 30
|
||||
if network.DefaultCheckInInterval == 0 {
|
||||
network.DefaultCheckInInterval = 30
|
||||
}
|
||||
if group.AllowManualSignUp == nil {
|
||||
if network.AllowManualSignUp == nil {
|
||||
signup := false
|
||||
group.AllowManualSignUp = &signup
|
||||
network.AllowManualSignUp = &signup
|
||||
}
|
||||
}
|
@@ -26,7 +26,7 @@ type Node struct {
|
||||
Endpoint string `json:"endpoint" bson:"endpoint" validate:"endpoint_check"`
|
||||
PostUp string `json:"postup" bson:"postup"`
|
||||
PreUp string `json:"preup" bson:"preup"`
|
||||
AllowedIPs string `json:"preup" bson:"preup"`
|
||||
AllowedIPs string `json:"allowedips" bson:"allowedips"`
|
||||
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate: "omitempty,numeric,max=1000"`
|
||||
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
||||
AccessKey string `json:"accesskey" bson:"accesskey"`
|
||||
@@ -39,7 +39,7 @@ type Node struct {
|
||||
MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,macaddress_valid,macaddress_unique"`
|
||||
CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
|
||||
Password string `json:"password" bson:"password" validate:"password_check"`
|
||||
Group string `json:"group" bson:"group" validate:"group_exists"`
|
||||
Network string `json:"network" bson:"network" validate:"network_exists"`
|
||||
IsPending bool `json:"ispending" bson:"ispending"`
|
||||
IsGateway bool `json:"isgateway" bson:"isgateway"`
|
||||
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
||||
@@ -48,27 +48,27 @@ type Node struct {
|
||||
|
||||
|
||||
//TODO: Contains a fatal error return. Need to change
|
||||
//Used in contexts where it's not the Parent group.
|
||||
func(node *Node) GetGroup() (Group, error){
|
||||
//Used in contexts where it's not the Parent network.
|
||||
func(node *Node) GetNetwork() (Network, error){
|
||||
|
||||
var group Group
|
||||
var network Network
|
||||
|
||||
collection := mongoconn.GroupDB
|
||||
//collection := mongoconn.Client.Database("netmaker").Collection("groups")
|
||||
collection := mongoconn.NetworkDB
|
||||
//collection := mongoconn.Client.Database("netmaker").Collection("networks")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
|
||||
filter := bson.M{"nameid": node.Group}
|
||||
err := collection.FindOne(ctx, filter).Decode(&group)
|
||||
filter := bson.M{"netid": node.Network}
|
||||
err := collection.FindOne(ctx, filter).Decode(&network)
|
||||
|
||||
defer cancel()
|
||||
|
||||
if err != nil {
|
||||
//log.Fatal(err)
|
||||
return group, err
|
||||
return network, err
|
||||
}
|
||||
|
||||
return group, err
|
||||
return network, err
|
||||
}
|
||||
|
||||
|
||||
@@ -103,13 +103,13 @@ func(node *Node) SetDefaultName(){
|
||||
//This should exist on the node.go struct. I'm sure there was a reason?
|
||||
func(node *Node) SetDefaults() {
|
||||
|
||||
//TODO: Maybe I should make Group a part of the node struct. Then we can just query the Group object for stuff.
|
||||
parentGroup, _ := node.GetGroup()
|
||||
//TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
|
||||
parentNetwork, _ := node.GetNetwork()
|
||||
|
||||
node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
|
||||
|
||||
if node.ListenPort == 0 {
|
||||
node.ListenPort = parentGroup.DefaultListenPort
|
||||
node.ListenPort = parentNetwork.DefaultListenPort
|
||||
}
|
||||
if node.PreUp == "" {
|
||||
//Empty because we dont set it
|
||||
@@ -118,20 +118,20 @@ func(node *Node) SetDefaults() {
|
||||
//TODO: This is dumb and doesn't work
|
||||
//Need to change
|
||||
if node.SaveConfig == nil {
|
||||
defaultsave := *parentGroup.DefaultSaveConfig
|
||||
defaultsave := *parentNetwork.DefaultSaveConfig
|
||||
node.SaveConfig = &defaultsave
|
||||
}
|
||||
if node.Interface == "" {
|
||||
node.Interface = parentGroup.DefaultInterface
|
||||
node.Interface = parentNetwork.DefaultInterface
|
||||
}
|
||||
if node.PersistentKeepalive == 0 {
|
||||
node.PersistentKeepalive = parentGroup.DefaultKeepalive
|
||||
node.PersistentKeepalive = parentNetwork.DefaultKeepalive
|
||||
}
|
||||
if node.PostUp == "" {
|
||||
postup := parentGroup.DefaultPostUp
|
||||
postup := parentNetwork.DefaultPostUp
|
||||
node.PostUp = postup
|
||||
}
|
||||
node.CheckInInterval = parentGroup.DefaultCheckInInterval
|
||||
node.CheckInInterval = parentNetwork.DefaultCheckInInterval
|
||||
|
||||
}
|
||||
|
||||
|
@@ -1,4 +1,4 @@
|
||||
//TODO: Either add a returnGroup and returnKey, or delete this
|
||||
//TODO: Either add a returnNetwork and returnKey, or delete this
|
||||
package models
|
||||
|
||||
type ReturnNode struct {
|
||||
@@ -16,7 +16,7 @@ type ReturnNode struct {
|
||||
PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive"`
|
||||
SaveConfig *bool `json:"saveconfig" bson:"saveconfig"`
|
||||
Interface string `json:"interface" bson:"interface"`
|
||||
Group string `json:"group" bson:"group"`
|
||||
Network string `json:"network" bson:"network"`
|
||||
IsPending *bool `json:"ispending" bson:"ispending"`
|
||||
IsGateway *bool `json:"isgateway" bson:"ispending"`
|
||||
GatewayRange string `json:"gatewayrange" bson:"gatewayrange"`
|
||||
|
@@ -32,7 +32,7 @@ type SuccessfulUserLoginResponse struct {
|
||||
// Claims is a struct that will be encoded to a JWT.
|
||||
// jwt.StandardClaims is an embedded type to provide expiry time
|
||||
type Claims struct {
|
||||
Group string
|
||||
Network string
|
||||
MacAddress string
|
||||
jwt.StandardClaims
|
||||
}
|
||||
@@ -49,7 +49,7 @@ type ErrorResponse struct {
|
||||
}
|
||||
|
||||
type NodeAuth struct {
|
||||
Group string
|
||||
Network string
|
||||
Password string
|
||||
MacAddress string
|
||||
}
|
||||
|
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
var Client *mongo.Client
|
||||
var NodeDB *mongo.Collection
|
||||
var GroupDB *mongo.Collection
|
||||
var NetworkDB *mongo.Collection
|
||||
var user string
|
||||
var pass string
|
||||
var host string
|
||||
@@ -94,7 +94,7 @@ func ConnectDatabase() {
|
||||
}
|
||||
|
||||
NodeDB = Client.Database("netmaker").Collection("nodes")
|
||||
GroupDB = Client.Database("netmaker").Collection("groups")
|
||||
NetworkDB = Client.Database("netmaker").Collection("networks")
|
||||
|
||||
log.Println("Database Connected.")
|
||||
}
|
||||
|
@@ -26,7 +26,7 @@ type ServerConfig struct {
|
||||
type NodeConfig struct {
|
||||
Name string `yaml:"name"`
|
||||
Interface string `yaml:"interface"`
|
||||
Group string `yaml:"group"`
|
||||
Network string `yaml:"network"`
|
||||
Password string `yaml:"password"`
|
||||
MacAddress string `yaml:"macaddress"`
|
||||
LocalAddress string `yaml:"localaddress"`
|
||||
|
@@ -73,7 +73,7 @@ func GetFreePort(rangestart int32) (int32, error){
|
||||
return portno, err
|
||||
}
|
||||
|
||||
func Install(accesskey string, password string, server string, group string, noauto bool, accesstoken string, inputname string) error {
|
||||
func Install(accesskey string, password string, server string, network string, noauto bool, accesstoken string, inputname string) error {
|
||||
|
||||
tserver := ""
|
||||
tnetwork := ""
|
||||
@@ -81,9 +81,9 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
trange := ""
|
||||
var localrange *net.IPNet
|
||||
islocal := false
|
||||
if FileExists("/etc/systemd/system/netclient-"+group+".timer") ||
|
||||
FileExists("/etc/netclient/netconfig-"+group) {
|
||||
err := errors.New("ALREADY_INSTALLED. Netclient appears to already be installed for network " + group + ". To re-install, please remove by executing 'sudo netclient -c remove -n " + group + "'. Then re-run the install command.")
|
||||
if FileExists("/etc/systemd/system/netclient-"+network+".timer") ||
|
||||
FileExists("/etc/netclient/netconfig-"+network) {
|
||||
err := errors.New("ALREADY_INSTALLED. Netclient appears to already be installed for network " + network + ". To re-install, please remove by executing 'sudo netclient -c remove -n " + network + "'. Then re-run the install command.")
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -98,29 +98,32 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
tnetwork = tokenvals[1]
|
||||
tkey = tokenvals[2]
|
||||
trange = tokenvals[3]
|
||||
if server == "" {
|
||||
printrange := ""
|
||||
if server == "localhost:50051" {
|
||||
server = tserver
|
||||
}
|
||||
if group == "" {
|
||||
group = tnetwork
|
||||
if network == "nonetwork" {
|
||||
network = tnetwork
|
||||
}
|
||||
if accesskey == "" {
|
||||
if accesskey == "badkey" {
|
||||
accesskey = tkey
|
||||
}
|
||||
if trange != "" {
|
||||
islocal = true
|
||||
_, localrange, err = net.ParseCIDR(trange)
|
||||
printrange = localrange.String()
|
||||
|
||||
} else {
|
||||
trange = "Not a local network. Will use public address for endpoint."
|
||||
printrange = "Not a local network. Will use public address for endpoint."
|
||||
}
|
||||
|
||||
fmt.Println("Decoded values from token:")
|
||||
fmt.Println(" Server: " + tserver)
|
||||
fmt.Println(" Network: " + tnetwork)
|
||||
fmt.Println(" Key: " + tkey)
|
||||
fmt.Println(" Local Range: " + localrange.String())
|
||||
fmt.Println(" Server: " + server)
|
||||
fmt.Println(" Network: " + network)
|
||||
fmt.Println(" Key: " + accesskey)
|
||||
fmt.Println(" Local Range: " + printrange)
|
||||
}
|
||||
|
||||
wgclient, err := wgctrl.New()
|
||||
|
||||
if err != nil {
|
||||
@@ -128,7 +131,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
}
|
||||
defer wgclient.Close()
|
||||
|
||||
cfg, err := config.ReadConfig(group)
|
||||
cfg, err := config.ReadConfig(network)
|
||||
if err != nil {
|
||||
log.Printf("No Config Yet. Will Write: %v", err)
|
||||
}
|
||||
@@ -153,7 +156,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
}
|
||||
}
|
||||
fmt.Println(" AccessKey: " + accesskey)
|
||||
err = config.WriteServer(server, accesskey, group)
|
||||
err = config.WriteServer(server, accesskey, network)
|
||||
if err != nil {
|
||||
fmt.Println("Error encountered while writing Server Config.")
|
||||
return err
|
||||
@@ -171,15 +174,15 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
}
|
||||
fmt.Println(" Password: " + password)
|
||||
|
||||
if group == "badgroup" {
|
||||
if nodecfg.Group == "" && tnetwork == "" {
|
||||
if network == "badnetwork" {
|
||||
if nodecfg.Network == "" && tnetwork == "" {
|
||||
//create error here
|
||||
log.Fatal("no group provided")
|
||||
log.Fatal("no network provided")
|
||||
} else {
|
||||
group = nodecfg.Group
|
||||
network = nodecfg.Network
|
||||
}
|
||||
}
|
||||
fmt.Println(" Group: " + group)
|
||||
fmt.Println(" Network: " + network)
|
||||
|
||||
var macaddress string
|
||||
var localaddress string
|
||||
@@ -338,7 +341,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
Password: password,
|
||||
Macaddress: macaddress,
|
||||
Accesskey: accesskey,
|
||||
Nodegroup: group,
|
||||
Nodenetwork: network,
|
||||
Listenport: listenport,
|
||||
Keepalive: keepalive,
|
||||
Localaddress: localaddress,
|
||||
@@ -372,7 +375,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
fmt.Println("NODE RECIEVED SETTINGS: ")
|
||||
fmt.Println(" Password: " + node.Password)
|
||||
fmt.Println(" WG Address: " + node.Address)
|
||||
fmt.Println(" Group: " + node.Nodegroup)
|
||||
fmt.Println(" Network: " + node.Nodenetwork)
|
||||
fmt.Println(" Public Endpoint: " + node.Endpoint)
|
||||
fmt.Println(" Local Address: " + node.Localaddress)
|
||||
fmt.Println(" Name: " + node.Name)
|
||||
@@ -392,19 +395,19 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
fmt.Println("Awaiting approval from Admin before configuring WireGuard.")
|
||||
if !noauto {
|
||||
fmt.Println("Configuring Netmaker Service.")
|
||||
err = ConfigureSystemD(group)
|
||||
err = ConfigureSystemD(network)
|
||||
return err
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
peers, err := getPeers(node.Macaddress, group, server)
|
||||
peers, err := getPeers(node.Macaddress, network, server)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("retrived peers, setting wireguard config.")
|
||||
err = storePrivKey(privkeystring, group)
|
||||
err = storePrivKey(privkeystring, network)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -413,7 +416,7 @@ func Install(accesskey string, password string, server string, group string, noa
|
||||
return err
|
||||
}
|
||||
if !noauto {
|
||||
err = ConfigureSystemD(group)
|
||||
err = ConfigureSystemD(network)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -450,12 +453,12 @@ func getPublicIP() (string, error) {
|
||||
}
|
||||
|
||||
func modConfig(node *nodepb.Node) error{
|
||||
group := node.Nodegroup
|
||||
if group == "" {
|
||||
return errors.New("No Group Provided")
|
||||
network := node.Nodenetwork
|
||||
if network == "" {
|
||||
return errors.New("No Network Provided")
|
||||
}
|
||||
//modconfig := config.Config
|
||||
modconfig, err := config.ReadConfig(group)
|
||||
modconfig, err := config.ReadConfig(network)
|
||||
//modconfig.ReadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -467,8 +470,8 @@ func modConfig(node *nodepb.Node) error{
|
||||
if node.Interface != ""{
|
||||
nodecfg.Interface = node.Interface
|
||||
}
|
||||
if node.Nodegroup != ""{
|
||||
nodecfg.Group = node.Nodegroup
|
||||
if node.Nodenetwork != ""{
|
||||
nodecfg.Network = node.Nodenetwork
|
||||
}
|
||||
if node.Macaddress != ""{
|
||||
nodecfg.MacAddress = node.Macaddress
|
||||
@@ -498,7 +501,7 @@ func modConfig(node *nodepb.Node) error{
|
||||
nodecfg.PostChanges = node.Postchanges
|
||||
}
|
||||
modconfig.Node = nodecfg
|
||||
err = config.Write(modconfig, group)
|
||||
err = config.Write(modconfig, network)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -533,7 +536,7 @@ func initWireguard(node *nodepb.Node, privkey string, peers []wgtypes.PeerConfig
|
||||
wgclient, err := wgctrl.New()
|
||||
//modcfg := config.Config
|
||||
//modcfg.ReadConfig()
|
||||
modcfg, err := config.ReadConfig(node.Nodegroup)
|
||||
modcfg, err := config.ReadConfig(node.Nodenetwork)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -730,7 +733,7 @@ func setWGConfig(network string) error {
|
||||
nodecfg := cfg.Node
|
||||
node := getNode(network)
|
||||
|
||||
peers, err := getPeers(node.Macaddress, nodecfg.Group, servercfg.Address)
|
||||
peers, err := getPeers(node.Macaddress, nodecfg.Network, servercfg.Address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -915,7 +918,7 @@ func CheckIn(network string) error {
|
||||
newinterface := getNode(network).Interface
|
||||
readreq := &nodepb.ReadNodeReq{
|
||||
Macaddress: node.Macaddress,
|
||||
Group: node.Nodegroup,
|
||||
Network: node.Nodenetwork,
|
||||
}
|
||||
readres, err := wcclient.ReadNode(ctx, readreq, grpc.Header(&header))
|
||||
if err != nil {
|
||||
@@ -942,7 +945,7 @@ func CheckIn(network string) error {
|
||||
fmt.Println("Updating config from remote server.")
|
||||
req := &nodepb.ReadNodeReq{
|
||||
Macaddress: node.Macaddress,
|
||||
Group: node.Nodegroup,
|
||||
Network: node.Nodenetwork,
|
||||
}
|
||||
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
||||
if err != nil {
|
||||
@@ -1029,11 +1032,11 @@ func CheckIn(network string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func needInterfaceUpdate(ctx context.Context, mac string, group string, iface string) (bool, string, error) {
|
||||
func needInterfaceUpdate(ctx context.Context, mac string, network string, iface string) (bool, string, error) {
|
||||
var header metadata.MD
|
||||
req := &nodepb.ReadNodeReq{
|
||||
Macaddress: mac,
|
||||
Group: group,
|
||||
Network: network,
|
||||
}
|
||||
readres, err := wcclient.ReadNode(ctx, req, grpc.Header(&header))
|
||||
if err != nil {
|
||||
@@ -1057,7 +1060,7 @@ func getNode(network string) nodepb.Node {
|
||||
|
||||
node.Name = nodecfg.Name
|
||||
node.Interface = nodecfg.Interface
|
||||
node.Nodegroup = nodecfg.Group
|
||||
node.Nodenetwork = nodecfg.Network
|
||||
node.Localaddress = nodecfg.LocalAddress
|
||||
node.Address = nodecfg.WGAddress
|
||||
node.Listenport = nodecfg.Port
|
||||
@@ -1112,7 +1115,7 @@ func Remove(network string) error {
|
||||
ctx,
|
||||
&nodepb.DeleteNodeReq{
|
||||
Macaddress: node.MacAddress,
|
||||
GroupName: node.Group,
|
||||
NetworkName: node.Network,
|
||||
},
|
||||
grpc.Header(&header),
|
||||
)
|
||||
@@ -1197,13 +1200,13 @@ func DeleteInterface(ifacename string) error{
|
||||
return err
|
||||
}
|
||||
|
||||
func getPeers(macaddress string, group string, server string) ([]wgtypes.PeerConfig, error) {
|
||||
func getPeers(macaddress string, network string, server string) ([]wgtypes.PeerConfig, error) {
|
||||
//need to implement checkin on server side
|
||||
var peers []wgtypes.PeerConfig
|
||||
var wcclient nodepb.NodeServiceClient
|
||||
cfg, err := config.ReadConfig(group)
|
||||
cfg, err := config.ReadConfig(network)
|
||||
if err != nil {
|
||||
log.Fatalf("Issue retrieving config for network: " + group + ". Please investigate: %v", err)
|
||||
log.Fatalf("Issue retrieving config for network: " + network + ". Please investigate: %v", err)
|
||||
}
|
||||
nodecfg := cfg.Node
|
||||
keepalive := nodecfg.KeepAlive
|
||||
@@ -1224,11 +1227,11 @@ func getPeers(macaddress string, group string, server string) ([]wgtypes.PeerCon
|
||||
|
||||
req := &nodepb.GetPeersReq{
|
||||
Macaddress: macaddress,
|
||||
Group: group,
|
||||
Network: network,
|
||||
}
|
||||
ctx := context.Background()
|
||||
fmt.Println("Authenticating with GRPC Server")
|
||||
ctx, err = SetJWT(wcclient, group)
|
||||
ctx, err = SetJWT(wcclient, network)
|
||||
if err != nil {
|
||||
fmt.Println("Failed to authenticate.")
|
||||
return peers, err
|
||||
|
@@ -20,7 +20,7 @@ const (
|
||||
)
|
||||
|
||||
var password string
|
||||
var group string
|
||||
var network string
|
||||
var server string
|
||||
var accesskey string
|
||||
|
||||
@@ -38,7 +38,7 @@ func main() {
|
||||
taccesstoken := flag.String("t", "badtoken", "an token generated by the server and used for one-time access (install only)")
|
||||
tname := flag.String("name", "noname", "give the node a name at runtime")
|
||||
tserver := flag.String("s", "localhost:50051", "The location (including port) of the remote gRPC server.")
|
||||
tnetwork := flag.String("n", "nonetwork", "The node group you are attempting to join.")
|
||||
tnetwork := flag.String("n", "nonetwork", "The node network you are attempting to join.")
|
||||
tnoauto := flag.Bool("na", false, "No auto mode. If true, netmclient will not be installed as a system service and you will have to retrieve updates manually via checkin command.")
|
||||
tnoforward := flag.Bool("nf", false, "No Forward mode. If true, netclient will not check for IP forwarding. This may break functionality")
|
||||
command := flag.String("c", "required", "The command to run")
|
||||
@@ -153,7 +153,7 @@ func main() {
|
||||
fmt.Println("Required, '-n'. No network provided. Exiting.")
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println("Beginning node check in for group " + *tnetwork)
|
||||
fmt.Println("Beginning node check in for network " + *tnetwork)
|
||||
err := functions.CheckIn(*tnetwork)
|
||||
if err != nil {
|
||||
fmt.Println("Error checking in: ", err)
|
||||
|
@@ -44,9 +44,9 @@ type AuthorizeTestCase struct {
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
mongoconn.ConnectDatabase()
|
||||
var waitgroup sync.WaitGroup
|
||||
waitgroup.Add(1)
|
||||
go controller.HandleRESTRequests(&waitgroup)
|
||||
var waitnetwork sync.Waitnetwork
|
||||
waitnetwork.Add(1)
|
||||
go controller.HandleRESTRequests(&waitnetwork)
|
||||
//wait for http server to start
|
||||
time.Sleep(time.Second * 1)
|
||||
os.Exit(m.Run())
|
||||
@@ -117,11 +117,11 @@ func deleteAdmin(t *testing.T) {
|
||||
assert.Nil(t, err, err)
|
||||
}
|
||||
|
||||
func createGroup(t *testing.T) {
|
||||
group := models.Group{}
|
||||
group.NameID = "skynet"
|
||||
group.AddressRange = "10.71.0.0/16"
|
||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
||||
func createnetwork(t *testing.T) {
|
||||
network := models.network{}
|
||||
network.NetID = "skynet"
|
||||
network.AddressRange = "10.71.0.0/16"
|
||||
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
}
|
||||
@@ -130,7 +130,7 @@ func createKey(t *testing.T) {
|
||||
key := models.AccessKey{}
|
||||
key.Name = "skynet"
|
||||
key.Uses = 10
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -140,7 +140,7 @@ func createKey(t *testing.T) {
|
||||
}
|
||||
|
||||
func getKey(t *testing.T, name string) models.AccessKey {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -155,8 +155,8 @@ func getKey(t *testing.T, name string) models.AccessKey {
|
||||
return models.AccessKey{}
|
||||
}
|
||||
|
||||
func deleteKey(t *testing.T, key, group string) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/"+group+"/keys/"+key, "secretkey")
|
||||
func deleteKey(t *testing.T, key, network string) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/"+network+"/keys/"+key, "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
//api does not return Deleted Count at this time
|
||||
//defer response.Body.Close()
|
||||
@@ -167,31 +167,31 @@ func deleteKey(t *testing.T, key, group string) {
|
||||
//assert.Equal(t, int64(1), message.DeletedCount)
|
||||
}
|
||||
|
||||
func groupExists(t *testing.T) bool {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
||||
func networkExists(t *testing.T) bool {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
||||
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||
assert.Nil(t, err, err)
|
||||
if Groups == nil {
|
||||
if networks == nil {
|
||||
return false
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func deleteGroups(t *testing.T) {
|
||||
func deletenetworks(t *testing.T) {
|
||||
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
||||
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||
assert.Nil(t, err, err)
|
||||
for _, group := range Groups {
|
||||
name := group.DisplayName
|
||||
_, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/"+name, "secretkey")
|
||||
for _, network := range networks {
|
||||
name := network.DisplayName
|
||||
_, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/"+name, "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
}
|
||||
}
|
||||
|
@@ -11,20 +11,20 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var Groups []models.Group
|
||||
var networks []models.network
|
||||
|
||||
func TestCreateGroup(t *testing.T) {
|
||||
group := models.Group{}
|
||||
group.NameID = "skynet"
|
||||
group.AddressRange = "10.71.0.0/16"
|
||||
deleteGroups(t)
|
||||
t.Run("CreateGroup", func(t *testing.T) {
|
||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "secretkey")
|
||||
func TestCreatenetwork(t *testing.T) {
|
||||
network := models.network{}
|
||||
network.NetID = "skynet"
|
||||
network.AddressRange = "10.71.0.0/16"
|
||||
deletenetworks(t)
|
||||
t.Run("Createnetwork", func(t *testing.T) {
|
||||
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, group, http.MethodPost, "http://localhost:8081/api/groups", "badkey")
|
||||
response, err := api(t, network, http.MethodPost, "http://localhost:8081/api/networks", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -42,23 +42,23 @@ func TestCreateGroup(t *testing.T) {
|
||||
//issue #42
|
||||
t.Skip()
|
||||
})
|
||||
t.Run("DuplicateGroup", func(t *testing.T) {
|
||||
t.Run("Duplicatenetwork", func(t *testing.T) {
|
||||
//issue #42
|
||||
t.Skip()
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroups(t *testing.T) {
|
||||
func TestGetnetworks(t *testing.T) {
|
||||
t.Run("ValidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&Groups)
|
||||
err = json.NewDecoder(response.Body).Decode(&networks)
|
||||
assert.Nil(t, err, err)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -70,19 +70,19 @@ func TestGetGroups(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroup(t *testing.T) {
|
||||
func TestGetnetwork(t *testing.T) {
|
||||
t.Run("ValidToken", func(t *testing.T) {
|
||||
var group models.Group
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network models.network
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
err = json.NewDecoder(response.Body).Decode(&group)
|
||||
err = json.NewDecoder(response.Body).Decode(&network)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "skynet", group.DisplayName)
|
||||
assert.Equal(t, "skynet", network.DisplayName)
|
||||
})
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -92,31 +92,31 @@ func TestGetGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetGroupNodeNumber(t *testing.T) {
|
||||
func TestGetnetworkNodeNumber(t *testing.T) {
|
||||
t.Run("ValidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message int
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
//assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
//assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/numnodes", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/numnodes", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -126,21 +126,21 @@ func TestGetGroupNodeNumber(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/numnodes", "secretkey")
|
||||
t.Run("Badnetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/numnodes", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteGroup(t *testing.T) {
|
||||
func TestDeletenetwork(t *testing.T) {
|
||||
t.Run("InvalidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -151,7 +151,7 @@ func TestDeleteGroup(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("ValidKey", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message mongo.DeleteResult
|
||||
@@ -161,21 +161,21 @@ func TestDeleteGroup(t *testing.T) {
|
||||
assert.Equal(t, int64(1), message.DeletedCount)
|
||||
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
t.Run("Badnetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("NodesExist", func(t *testing.T) {
|
||||
t.Skip()
|
||||
})
|
||||
//Create Group for follow-on tests
|
||||
createGroup(t)
|
||||
//Create network for follow-on tests
|
||||
createnetwork(t)
|
||||
}
|
||||
|
||||
func TestCreateAccessKey(t *testing.T) {
|
||||
@@ -183,7 +183,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
key.Name = "skynet"
|
||||
key.Uses = 10
|
||||
t.Run("MultiUse", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -198,7 +198,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
t.Run("ZeroUse", func(t *testing.T) {
|
||||
//t.Skip()
|
||||
key.Uses = 0
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -212,14 +212,14 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
t.Run("DuplicateAccessKey", func(t *testing.T) {
|
||||
//t.Skip()
|
||||
//this will fail
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
deleteKey(t, key.Name, "skynet")
|
||||
})
|
||||
|
||||
t.Run("InvalidToken", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -229,14 +229,14 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnauthorized, message.Code)
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
})
|
||||
t.Run("BadGroup", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
||||
t.Run("Badnetwork", func(t *testing.T) {
|
||||
response, err := api(t, key, http.MethodPost, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
}
|
||||
@@ -244,7 +244,7 @@ func TestCreateAccessKey(t *testing.T) {
|
||||
func TestDeleteKey(t *testing.T) {
|
||||
t.Run("KeyValid", func(t *testing.T) {
|
||||
//fails -- deletecount not returned
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message mongo.DeleteResult
|
||||
@@ -255,7 +255,7 @@ func TestDeleteKey(t *testing.T) {
|
||||
})
|
||||
t.Run("InValidKey", func(t *testing.T) {
|
||||
//fails -- status message not returned
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/badkey", "secretkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/badkey", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
@@ -264,18 +264,18 @@ func TestDeleteKey(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: This key does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("KeyInValidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/badgroup/keys/skynet", "secretkey")
|
||||
t.Run("KeyInValidnetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/badnetwork/keys/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/groups/skynet/keys/skynet", "badkey")
|
||||
response, err := api(t, "", http.MethodDelete, "http://localhost:8081/api/networks/skynet/keys/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -290,7 +290,7 @@ func TestDeleteKey(t *testing.T) {
|
||||
func TestGetKeys(t *testing.T) {
|
||||
createKey(t)
|
||||
t.Run("Valid", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "secretkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -299,18 +299,18 @@ func TestGetKeys(t *testing.T) {
|
||||
assert.Nil(t, err, err)
|
||||
})
|
||||
//deletekeys
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/badgroup/keys", "secretkey")
|
||||
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/badnetwork/keys", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidCredentials", func(t *testing.T) {
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/groups/skynet/keys", "badkey")
|
||||
response, err := api(t, "", http.MethodGet, "http://localhost:8081/api/networks/skynet/keys", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
@@ -322,29 +322,29 @@ func TestGetKeys(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateGroup(t *testing.T) {
|
||||
var returnedGroup models.Group
|
||||
t.Run("UpdateNameID", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
func TestUpdatenetwork(t *testing.T) {
|
||||
var returnednetwork models.network
|
||||
t.Run("UpdateNetID", func(t *testing.T) {
|
||||
type network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.NameID, returnedGroup.NameID)
|
||||
assert.Equal(t, network.NetID, returnednetwork.NetID)
|
||||
})
|
||||
t.Run("NameIDInvalidCredentials", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("NetIDInvalidCredentials", func(t *testing.T) {
|
||||
type network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "badkey")
|
||||
var network network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "badkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -353,83 +353,83 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, "W1R3: You are unauthorized to access this endpoint.", message.Message)
|
||||
assert.Equal(t, http.StatusUnauthorized, response.StatusCode)
|
||||
})
|
||||
t.Run("InvalidGroup", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("Invalidnetwork", func(t *testing.T) {
|
||||
type network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/badgroup", "secretkey")
|
||||
var network network
|
||||
network.NetID = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/badnetwork", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
defer response.Body.Close()
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusNotFound, message.Code)
|
||||
assert.Equal(t, "W1R3: This group does not exist.", message.Message)
|
||||
assert.Equal(t, "W1R3: This network does not exist.", message.Message)
|
||||
assert.Equal(t, http.StatusNotFound, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateNameIDTooLong", func(t *testing.T) {
|
||||
type Group struct {
|
||||
NameID string
|
||||
t.Run("UpdateNetIDTooLong", func(t *testing.T) {
|
||||
type network struct {
|
||||
NetID string
|
||||
}
|
||||
var group Group
|
||||
group.NameID = "wirecat-skynet"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.NetID = "wirecat-skynet"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateAddress", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
AddressRange string
|
||||
}
|
||||
var group Group
|
||||
group.AddressRange = "10.0.0.1/24"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.AddressRange = "10.0.0.1/24"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.AddressRange, returnedGroup.AddressRange)
|
||||
assert.Equal(t, network.AddressRange, returnednetwork.AddressRange)
|
||||
})
|
||||
t.Run("UpdateAddressInvalid", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
AddressRange string
|
||||
}
|
||||
var group Group
|
||||
group.AddressRange = "10.0.0.1/36"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.AddressRange = "10.0.0.1/36"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateDisplayName", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DisplayName string
|
||||
}
|
||||
var group Group
|
||||
group.DisplayName = "wirecat"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DisplayName = "wirecat"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
||||
assert.Equal(t, network.DisplayName, returnednetwork.DisplayName)
|
||||
|
||||
})
|
||||
t.Run("UpdateDisplayNameInvalidName", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DisplayName string
|
||||
}
|
||||
var group Group
|
||||
var network network
|
||||
//create name that is longer than 100 chars
|
||||
name := ""
|
||||
for i := 0; i < 101; i++ {
|
||||
name = name + "a"
|
||||
}
|
||||
group.DisplayName = name
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.DisplayName = name
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -439,41 +439,41 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdateInterface", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultInterface string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultInterface = "netmaker"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultInterface = "netmaker"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultInterface, returnedGroup.DefaultInterface)
|
||||
assert.Equal(t, network.DefaultInterface, returnednetwork.DefaultInterface)
|
||||
|
||||
})
|
||||
t.Run("UpdateListenPort", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 6000
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultListenPort = 6000
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
||||
assert.Equal(t, network.DefaultListenPort, returnednetwork.DefaultListenPort)
|
||||
})
|
||||
t.Run("UpdateListenPortInvalidPort", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 1023
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultListenPort = 1023
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -483,54 +483,54 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("UpdatePostUP", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultPostUp string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultPostUp = "sudo wg add-conf wc-netmaker /etc/wireguard/peers/conf"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultPostUp, returnedGroup.DefaultPostUp)
|
||||
assert.Equal(t, network.DefaultPostUp, returnednetwork.DefaultPostUp)
|
||||
})
|
||||
t.Run("UpdatePreUP", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultPreUp string
|
||||
}
|
||||
var group Group
|
||||
group.DefaultPreUp = "test string"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultPreUp = "test string"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultPreUp, returnedGroup.DefaultPreUp)
|
||||
assert.Equal(t, network.DefaultPreUp, returnednetwork.DefaultPreUp)
|
||||
})
|
||||
t.Run("UpdateKeepAlive", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultKeepalive int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultKeepalive = 60
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultKeepalive = 60
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultKeepalive, returnedGroup.DefaultKeepalive)
|
||||
assert.Equal(t, network.DefaultKeepalive, returnednetwork.DefaultKeepalive)
|
||||
})
|
||||
t.Run("UpdateKeepAliveTooBig", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultKeepAlive int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultKeepAlive = 1001
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultKeepAlive = 1001
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -542,57 +542,57 @@ func TestUpdateGroup(t *testing.T) {
|
||||
t.Run("UpdateSaveConfig", func(t *testing.T) {
|
||||
//causes panic
|
||||
t.Skip()
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultSaveConfig *bool
|
||||
}
|
||||
var group Group
|
||||
var network network
|
||||
value := false
|
||||
group.DefaultSaveConfig = &value
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.DefaultSaveConfig = &value
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, *group.DefaultSaveConfig, *returnedGroup.DefaultSaveConfig)
|
||||
assert.Equal(t, *network.DefaultSaveConfig, *returnednetwork.DefaultSaveConfig)
|
||||
})
|
||||
t.Run("UpdateManualSignUP", func(t *testing.T) {
|
||||
t.Skip()
|
||||
type Group struct {
|
||||
type network struct {
|
||||
AllowManualSignUp *bool
|
||||
}
|
||||
var group Group
|
||||
var network network
|
||||
value := true
|
||||
group.AllowManualSignUp = &value
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
network.AllowManualSignUp = &value
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, *group.AllowManualSignUp, *returnedGroup.AllowManualSignUp)
|
||||
assert.Equal(t, *network.AllowManualSignUp, *returnednetwork.AllowManualSignUp)
|
||||
})
|
||||
t.Run("DefaultCheckInterval", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultCheckInInterval int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultCheckInInterval = 6000
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultCheckInInterval = 6000
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DefaultCheckInInterval, returnedGroup.DefaultCheckInInterval)
|
||||
assert.Equal(t, network.DefaultCheckInInterval, returnednetwork.DefaultCheckInInterval)
|
||||
})
|
||||
t.Run("DefaultCheckIntervalTooBig", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DefaultCheckInInterval int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultCheckInInterval = 100001
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultCheckInInterval = 100001
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
var message models.ErrorResponse
|
||||
err = json.NewDecoder(response.Body).Decode(&message)
|
||||
@@ -602,20 +602,20 @@ func TestUpdateGroup(t *testing.T) {
|
||||
assert.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
|
||||
})
|
||||
t.Run("MultipleFields", func(t *testing.T) {
|
||||
type Group struct {
|
||||
type network struct {
|
||||
DisplayName string
|
||||
DefaultListenPort int32
|
||||
}
|
||||
var group Group
|
||||
group.DefaultListenPort = 7777
|
||||
group.DisplayName = "multi"
|
||||
response, err := api(t, group, http.MethodPut, "http://localhost:8081/api/groups/skynet", "secretkey")
|
||||
var network network
|
||||
network.DefaultListenPort = 7777
|
||||
network.DisplayName = "multi"
|
||||
response, err := api(t, network, http.MethodPut, "http://localhost:8081/api/networks/skynet", "secretkey")
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, http.StatusOK, response.StatusCode)
|
||||
defer response.Body.Close()
|
||||
err = json.NewDecoder(response.Body).Decode(&returnedGroup)
|
||||
err = json.NewDecoder(response.Body).Decode(&returnednetwork)
|
||||
assert.Nil(t, err, err)
|
||||
assert.Equal(t, group.DisplayName, returnedGroup.DisplayName)
|
||||
assert.Equal(t, group.DefaultListenPort, returnedGroup.DefaultListenPort)
|
||||
assert.Equal(t, network.DisplayName, returnednetwork.DisplayName)
|
||||
assert.Equal(t, network.DefaultListenPort, returnednetwork.DefaultListenPort)
|
||||
})
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ generate_post_json ()
|
||||
{
|
||||
cat <<EOF
|
||||
{
|
||||
"nameid": "$NAME",
|
||||
"netid": "$NAME",
|
||||
"addressrange": "$ADDRESSRANGE"
|
||||
}
|
||||
EOF
|
||||
@@ -15,4 +15,4 @@ EOF
|
||||
|
||||
POST_JSON=$(generate_post_json)
|
||||
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||
|
@@ -7,7 +7,7 @@ generate_post_json ()
|
||||
{
|
||||
cat <<EOF
|
||||
{
|
||||
"nameid": "$NAME",
|
||||
"netid": "$NAME",
|
||||
"addressrange": "$ADDRESSRANGE"
|
||||
}
|
||||
EOF
|
||||
@@ -15,7 +15,7 @@ EOF
|
||||
|
||||
POST_JSON=$(generate_post_json)
|
||||
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||
|
||||
NAME="skynet"
|
||||
ADDRESSRANGE="100.70.0.0/14"
|
||||
@@ -23,4 +23,4 @@ ADDRESSRANGE="100.70.0.0/14"
|
||||
POST_JSON=$(generate_post_json)
|
||||
|
||||
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks
|
||||
|
@@ -13,4 +13,4 @@ EOF
|
||||
|
||||
POST_JSON=$(generate_post_json)
|
||||
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/groups/skynet/keys
|
||||
curl --max-time 5.0 -d "$POST_JSON" -H 'Content-Type: application/json' -H "authorization: Bearer secretkey" localhost:8081/api/networks/skynet/keys
|
||||
|
Reference in New Issue
Block a user