From 4356aea65a91c8b802db7ec34419f87edaa94198 Mon Sep 17 00:00:00 2001 From: Matthew R Kasun Date: Thu, 14 Oct 2021 11:19:49 -0400 Subject: [PATCH 1/4] prevent creating admin if one already exists --- controllers/userHttpController.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/controllers/userHttpController.go b/controllers/userHttpController.go index 46de2334..76eff695 100644 --- a/controllers/userHttpController.go +++ b/controllers/userHttpController.go @@ -348,8 +348,18 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { var admin models.User // get node from body of request _ = json.NewDecoder(r.Body).Decode(&admin) + hasadmin, err := HasAdmin() + if err != nil { + returnErrorResponse(w, r, formatError(err, "internal")) + return + } + if hasadmin { + returnErrorResponse(w, r, formatError(errors.New("admin user already exists"), "unauthorized")) + return + } admin.IsAdmin = true - admin, err := CreateUser(admin) + fmt.Println(admin) + admin, err = CreateUser(admin) if err != nil { returnErrorResponse(w, r, formatError(err, "badrequest")) From 2bf2e65736610aa78a85e2002230e09d95c4ef17 Mon Sep 17 00:00:00 2001 From: Matthew R Kasun Date: Thu, 14 Oct 2021 11:27:04 -0400 Subject: [PATCH 2/4] removed debugging println --- controllers/userHttpController.go | 69 +++++++++++++------------------ 1 file changed, 29 insertions(+), 40 deletions(-) diff --git a/controllers/userHttpController.go b/controllers/userHttpController.go index 76eff695..74fc8644 100644 --- a/controllers/userHttpController.go +++ b/controllers/userHttpController.go @@ -28,11 +28,11 @@ func userHandlers(r *mux.Router) { r.HandleFunc("/api/users", authorizeUserAdm(http.HandlerFunc(getUsers))).Methods("GET") } -// Node authenticates using its password and retrieves a JWT for authorization. +//Node authenticates using its password and retrieves a JWT for authorization. func authenticateUser(response http.ResponseWriter, request *http.Request) { - // Auth request consists of Mac Address and Password (from node that is authorizing - // in case of Master, auth is ignored and mac is set to "mastermac" + //Auth request consists of Mac Address and Password (from node that is authorizing + //in case of Master, auth is ignored and mac is set to "mastermac" var authRequest models.UserAuthParams var errorResponse = models.ErrorResponse{ Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.", @@ -53,7 +53,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { } if jwt == "" { - // very unlikely that err is !nil and no jwt returned, but handle it anyways. + //very unlikely that err is !nil and no jwt returned, but handle it anyways. returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal")) return } @@ -67,7 +67,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { UserName: username, }, } - // Send back the JWT + //Send back the JWT successJSONResponse, jsonError := json.Marshal(successResponse) if jsonError != nil { @@ -79,7 +79,6 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { response.Write(successJSONResponse) } -// VerifyAuthRequest - verifies an auth request func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { var result models.User if authRequest.UserName == "" { @@ -87,7 +86,7 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { } else if authRequest.Password == "" { return "", errors.New("password can't be empty") } - //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API until approved). + //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved). record, err := database.FetchRecord(database.USERS_TABLE_NAME, authRequest.UserName) if err != nil { return "", errors.New("incorrect credentials") @@ -96,9 +95,9 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { return "", errors.New("incorrect credentials") } - // compare password from request to stored password in database - // might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text... - // TODO: Consider a way of hashing the password client side before sending, or using certificates + //compare password from request to stored password in database + //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text... + //TODO: Consider a way of hashing the password client side before sending, or using certificates if err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password)); err != nil { return "", errors.New("incorrect credentials") } @@ -108,19 +107,19 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { return tokenString, nil } -// 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 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 +//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 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 authorizeUser(next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) - // get the auth token + //get the auth token bearerToken := r.Header.Get("Authorization") username := params["username"] err := ValidateUserToken(bearerToken, username, false) @@ -151,7 +150,6 @@ func authorizeUserAdm(next http.Handler) http.HandlerFunc { } } -// ValidateUserToken - self explained func ValidateUserToken(token string, user string, adminonly bool) error { var tokenSplit = strings.Split(token, " ") //I put this in in case the user doesn't put in a token at all (in which case it's empty) @@ -181,7 +179,6 @@ func ValidateUserToken(token string, user string, adminonly bool) error { return nil } -// HasAdmin - checks if server has an admin func HasAdmin() (bool, error) { collection, err := database.FetchRecords(database.USERS_TABLE_NAME) @@ -221,7 +218,6 @@ func hasAdmin(w http.ResponseWriter, r *http.Request) { } -// GetUser - gets a user func GetUser(username string) (models.ReturnUser, error) { var user models.ReturnUser @@ -235,7 +231,6 @@ func GetUser(username string) (models.ReturnUser, error) { return user, err } -// GetUserInternal - gets an internal user func GetUserInternal(username string) (models.User, error) { var user models.User @@ -249,7 +244,6 @@ func GetUserInternal(username string) (models.User, error) { return user, err } -// GetUsers - gets users func GetUsers() ([]models.ReturnUser, error) { var users []models.ReturnUser @@ -273,7 +267,7 @@ func GetUsers() ([]models.ReturnUser, error) { return users, err } -// Get an individual node. Nothin fancy here folks. +//Get an individual node. Nothin fancy here folks. func getUser(w http.ResponseWriter, r *http.Request) { // set header. w.Header().Set("Content-Type", "application/json") @@ -290,7 +284,7 @@ func getUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -// Get an individual node. Nothin fancy here folks. +//Get an individual node. Nothin fancy here folks. func getUsers(w http.ResponseWriter, r *http.Request) { // set header. w.Header().Set("Content-Type", "application/json") @@ -306,9 +300,8 @@ func getUsers(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(users) } -// CreateUser - creates a user func CreateUser(user models.User) (models.User, error) { - // check if user exists + //check if user exists if _, err := GetUser(user.UserName); err == nil { return models.User{}, errors.New("user exists") } @@ -317,18 +310,18 @@ func CreateUser(user models.User) (models.User, error) { return models.User{}, err } - // encrypt that password so we never see it again + //encrypt that password so we never see it again hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5) if err != nil { return user, err } - // set password to encrypted password + //set password to encrypted password user.Password = string(hash) tokenString, _ := functions.CreateUserJWT(user.UserName, user.Networks, user.IsAdmin) if tokenString == "" { - // returnErrorResponse(w, r, errorResponse) + //returnErrorResponse(w, r, errorResponse) return user, err } @@ -346,7 +339,7 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var admin models.User - // get node from body of request + //get node from body of request _ = json.NewDecoder(r.Body).Decode(&admin) hasadmin, err := HasAdmin() if err != nil { @@ -358,7 +351,6 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { return } admin.IsAdmin = true - fmt.Println(admin) admin, err = CreateUser(admin) if err != nil { @@ -373,7 +365,7 @@ func createUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var user models.User - // get node from body of request + //get node from body of request _ = json.NewDecoder(r.Body).Decode(&user) user, err := CreateUser(user) @@ -386,7 +378,6 @@ func createUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -// UpdateUser - updates a given user func UpdateUser(userchange models.User, user models.User) (models.User, error) { //check if user exists if _, err := GetUser(user.UserName); err != nil { @@ -407,13 +398,13 @@ func UpdateUser(userchange models.User, user models.User) (models.User, error) { user.Networks = userchange.Networks } if userchange.Password != "" { - // encrypt that password so we never see it again + //encrypt that password so we never see it again hash, err := bcrypt.GenerateFromPassword([]byte(userchange.Password), 5) if err != nil { return userchange, err } - // set password to encrypted password + //set password to encrypted password userchange.Password = string(hash) user.Password = userchange.Password @@ -436,7 +427,7 @@ func updateUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) var user models.User - // start here + //start here username := params["username"] user, err := GetUserInternal(username) if err != nil { @@ -464,7 +455,7 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) var user models.User - // start here + //start here username := params["username"] user, err := GetUserInternal(username) if err != nil { @@ -487,7 +478,6 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -// DeleteUser - deletes a given user func DeleteUser(user string) (bool, error) { if userRecord, err := database.FetchRecord(database.USERS_TABLE_NAME, user); err != nil || len(userRecord) == 0 { @@ -523,7 +513,6 @@ func deleteUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(params["username"] + " deleted.") } -// ValidateUser - validates a user model func ValidateUser(operation string, user models.User) error { v := validator.New() From 1c1637b75e05efd38b5a0ae286bef088ae1a2a0b Mon Sep 17 00:00:00 2001 From: Matthew R Kasun Date: Thu, 14 Oct 2021 16:36:14 -0400 Subject: [PATCH 3/4] refactored and added unit test --- controllers/userHttpController.go | 25 ++++++++++++++----------- controllers/userHttpController_test.go | 20 ++++++++++++++++++++ go.mod | 2 +- go.sum | 17 +++++++++++++++++ 4 files changed, 52 insertions(+), 12 deletions(-) diff --git a/controllers/userHttpController.go b/controllers/userHttpController.go index 74fc8644..89ac70c1 100644 --- a/controllers/userHttpController.go +++ b/controllers/userHttpController.go @@ -341,17 +341,8 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { var admin models.User //get node from body of request _ = json.NewDecoder(r.Body).Decode(&admin) - hasadmin, err := HasAdmin() - if err != nil { - returnErrorResponse(w, r, formatError(err, "internal")) - return - } - if hasadmin { - returnErrorResponse(w, r, formatError(errors.New("admin user already exists"), "unauthorized")) - return - } - admin.IsAdmin = true - admin, err = CreateUser(admin) + + admin, err := CreateAdmin(admin) if err != nil { returnErrorResponse(w, r, formatError(err, "badrequest")) @@ -361,6 +352,18 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(admin) } +func CreateAdmin(admin models.User) (models.User, error) { + hasadmin, err := HasAdmin() + if err != nil { + return models.User{}, err + } + if hasadmin { + return models.User{}, errors.New("admin user already exists") + } + admin.IsAdmin = true + return CreateUser(admin) +} + func createUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") diff --git a/controllers/userHttpController_test.go b/controllers/userHttpController_test.go index 4cacdf1a..98f9dfd0 100644 --- a/controllers/userHttpController_test.go +++ b/controllers/userHttpController_test.go @@ -71,6 +71,26 @@ func TestCreateUser(t *testing.T) { }) } +func TestCreateAdmin(t *testing.T) { + database.InitializeDatabase() + deleteAllUsers() + var user models.User + t.Run("NoAdmin", func(t *testing.T) { + user.UserName = "admin" + user.Password = "password" + admin, err := CreateAdmin(user) + assert.Nil(t, err) + assert.Equal(t, user.UserName, admin.UserName) + }) + t.Run("AdminExists", func(t *testing.T) { + user.UserName = "admin2" + user.Password = "password1" + admin, err := CreateAdmin(user) + assert.EqualError(t, err, "admin user already exists") + assert.Equal(t, admin, models.User{}) + }) +} + func TestDeleteUser(t *testing.T) { database.InitializeDatabase() deleteAllUsers() diff --git a/go.mod b/go.mod index fb7785c9..00453777 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/golang/protobuf v1.5.2 // indirect github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 - github.com/lib/pq v1.10.3 // indirect + github.com/lib/pq v1.10.3 github.com/mattn/go-sqlite3 v1.14.8 github.com/rqlite/gorqlite v0.0.0-20210514125552-08ff1e76b22f github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e diff --git a/go.sum b/go.sum index 386280bb..2041583c 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,12 @@ +cloud.google.com/go v0.26.0 h1:e0WKqKTd5BnrG8aKH3J3h+QvEIQtSUcf2n5UZ5ZgLtQ= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/census-instrumentation/opencensus-proto v0.2.1 h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403 h1:cqQfy1jclcSy/FwLjemeg3SR1yaINm74aQyupQ0Bl8M= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= @@ -16,7 +20,9 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad h1:EmNYJhPYy0pOFjCx2PrgtaBXmee0iUX9hLlxE1xHOJE= github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= @@ -31,6 +37,7 @@ github.com/go-playground/validator/v10 v10.5.0 h1:X9rflw/KmpACwT8zdrm1upefpvdy6u github.com/go-playground/validator/v10 v10.5.0/go.mod h1:xm76BBt941f7yWdGnI2DVPFFg1UK3YY04qifoXU3lOk= github.com/golang-jwt/jwt/v4 v4.0.0 h1:RAqyYixv1p7uEnocuy8P1nru5wprCh/MH2BIlW5z5/o= github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -54,12 +61,14 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/josharian/native v0.0.0-20200817173448-b6b71def0850 h1:uhL5Gw7BINiiPAo24A2sxkcDI0Jt/sqp1v5xQCniEFA= github.com/josharian/native v0.0.0-20200817173448-b6b71def0850/go.mod h1:7X/raswPFr05uY3HiLlYeyQntB6OO7E/d2Cu7qoaN2w= @@ -112,10 +121,13 @@ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1 github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -156,6 +168,7 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210504132125-bbd867fde50d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 h1:4CSI6oo7cOjJKajidEljs9h+uP0rRZBPPPhcCbj5mw8= golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -187,6 +200,7 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e h1:XMgFehsDnnLGtjvjOfqWSUzt0alpTR1RSEuznObga2c= golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= @@ -198,6 +212,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= @@ -208,6 +223,7 @@ golang.zx2c4.com/wireguard v0.0.0-20210805125648-3957e9b9dd19/go.mod h1:laHzsbfM golang.zx2c4.com/wireguard/wgctrl v0.0.0-20210913210325-91d1988e44de h1:M9Jc92kgqmVmidpnOeegP2VgO2DfHEcsUWtWMmBwNFQ= golang.zx2c4.com/wireguard/wgctrl v0.0.0-20210913210325-91d1988e44de/go.mod h1:+1XihzyZUBJcSc5WO9SwNA7v26puQwOEDwanaxfNXPQ= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= @@ -236,6 +252,7 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3 h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From f7d8281d65808ee9478fa135b74b29ac34dff9b7 Mon Sep 17 00:00:00 2001 From: Matthew R Kasun Date: Sat, 16 Oct 2021 08:01:38 -0400 Subject: [PATCH 4/4] revert changes to comments before functions --- controllers/userHttpController.go | 68 ++++++++++++++++++------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/controllers/userHttpController.go b/controllers/userHttpController.go index 89ac70c1..999fa89b 100644 --- a/controllers/userHttpController.go +++ b/controllers/userHttpController.go @@ -28,11 +28,11 @@ func userHandlers(r *mux.Router) { r.HandleFunc("/api/users", authorizeUserAdm(http.HandlerFunc(getUsers))).Methods("GET") } -//Node authenticates using its password and retrieves a JWT for authorization. +// Node authenticates using its password and retrieves a JWT for authorization. func authenticateUser(response http.ResponseWriter, request *http.Request) { - //Auth request consists of Mac Address and Password (from node that is authorizing - //in case of Master, auth is ignored and mac is set to "mastermac" + // Auth request consists of Mac Address and Password (from node that is authorizing + // in case of Master, auth is ignored and mac is set to "mastermac" var authRequest models.UserAuthParams var errorResponse = models.ErrorResponse{ Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.", @@ -53,7 +53,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { } if jwt == "" { - //very unlikely that err is !nil and no jwt returned, but handle it anyways. + // very unlikely that err is !nil and no jwt returned, but handle it anyways. returnErrorResponse(response, request, formatError(errors.New("No token returned"), "internal")) return } @@ -67,7 +67,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { UserName: username, }, } - //Send back the JWT + // Send back the JWT successJSONResponse, jsonError := json.Marshal(successResponse) if jsonError != nil { @@ -79,6 +79,7 @@ func authenticateUser(response http.ResponseWriter, request *http.Request) { response.Write(successJSONResponse) } +// VerifyAuthRequest - verifies an auth request func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { var result models.User if authRequest.UserName == "" { @@ -86,7 +87,7 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { } else if authRequest.Password == "" { return "", errors.New("password can't be empty") } - //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved). + //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API until approved). record, err := database.FetchRecord(database.USERS_TABLE_NAME, authRequest.UserName) if err != nil { return "", errors.New("incorrect credentials") @@ -95,9 +96,9 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { return "", errors.New("incorrect credentials") } - //compare password from request to stored password in database - //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text... - //TODO: Consider a way of hashing the password client side before sending, or using certificates + // compare password from request to stored password in database + // might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text... + // TODO: Consider a way of hashing the password client side before sending, or using certificates if err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password)); err != nil { return "", errors.New("incorrect credentials") } @@ -107,19 +108,19 @@ func VerifyAuthRequest(authRequest models.UserAuthParams) (string, error) { return tokenString, nil } -//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 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 +// 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 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 authorizeUser(next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) - //get the auth token + // get the auth token bearerToken := r.Header.Get("Authorization") username := params["username"] err := ValidateUserToken(bearerToken, username, false) @@ -150,6 +151,7 @@ func authorizeUserAdm(next http.Handler) http.HandlerFunc { } } +// ValidateUserToken - self explained func ValidateUserToken(token string, user string, adminonly bool) error { var tokenSplit = strings.Split(token, " ") //I put this in in case the user doesn't put in a token at all (in which case it's empty) @@ -179,6 +181,7 @@ func ValidateUserToken(token string, user string, adminonly bool) error { return nil } +// HasAdmin - checks if server has an admin func HasAdmin() (bool, error) { collection, err := database.FetchRecords(database.USERS_TABLE_NAME) @@ -218,6 +221,7 @@ func hasAdmin(w http.ResponseWriter, r *http.Request) { } +// GetUser - gets a user func GetUser(username string) (models.ReturnUser, error) { var user models.ReturnUser @@ -231,6 +235,7 @@ func GetUser(username string) (models.ReturnUser, error) { return user, err } +// GetUserInternal - gets an internal user func GetUserInternal(username string) (models.User, error) { var user models.User @@ -244,6 +249,7 @@ func GetUserInternal(username string) (models.User, error) { return user, err } +// GetUsers - gets users func GetUsers() ([]models.ReturnUser, error) { var users []models.ReturnUser @@ -267,7 +273,7 @@ func GetUsers() ([]models.ReturnUser, error) { return users, err } -//Get an individual node. Nothin fancy here folks. +// Get an individual node. Nothin fancy here folks. func getUser(w http.ResponseWriter, r *http.Request) { // set header. w.Header().Set("Content-Type", "application/json") @@ -284,7 +290,7 @@ func getUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } -//Get an individual node. Nothin fancy here folks. +// Get an individual node. Nothin fancy here folks. func getUsers(w http.ResponseWriter, r *http.Request) { // set header. w.Header().Set("Content-Type", "application/json") @@ -300,8 +306,9 @@ func getUsers(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(users) } +// CreateUser - creates a user func CreateUser(user models.User) (models.User, error) { - //check if user exists + // check if user exists if _, err := GetUser(user.UserName); err == nil { return models.User{}, errors.New("user exists") } @@ -310,18 +317,18 @@ func CreateUser(user models.User) (models.User, error) { return models.User{}, err } - //encrypt that password so we never see it again + // encrypt that password so we never see it again hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5) if err != nil { return user, err } - //set password to encrypted password + // set password to encrypted password user.Password = string(hash) tokenString, _ := functions.CreateUserJWT(user.UserName, user.Networks, user.IsAdmin) if tokenString == "" { - //returnErrorResponse(w, r, errorResponse) + // returnErrorResponse(w, r, errorResponse) return user, err } @@ -339,7 +346,7 @@ func createAdmin(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var admin models.User - //get node from body of request + // get node from body of request _ = json.NewDecoder(r.Body).Decode(&admin) admin, err := CreateAdmin(admin) @@ -368,7 +375,7 @@ func createUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var user models.User - //get node from body of request + // get node from body of request _ = json.NewDecoder(r.Body).Decode(&user) user, err := CreateUser(user) @@ -381,6 +388,7 @@ func createUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } +// UpdateUser - updates a given user func UpdateUser(userchange models.User, user models.User) (models.User, error) { //check if user exists if _, err := GetUser(user.UserName); err != nil { @@ -401,13 +409,13 @@ func UpdateUser(userchange models.User, user models.User) (models.User, error) { user.Networks = userchange.Networks } if userchange.Password != "" { - //encrypt that password so we never see it again + // encrypt that password so we never see it again hash, err := bcrypt.GenerateFromPassword([]byte(userchange.Password), 5) if err != nil { return userchange, err } - //set password to encrypted password + // set password to encrypted password userchange.Password = string(hash) user.Password = userchange.Password @@ -430,7 +438,7 @@ func updateUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) var user models.User - //start here + // start here username := params["username"] user, err := GetUserInternal(username) if err != nil { @@ -458,7 +466,7 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var params = mux.Vars(r) var user models.User - //start here + // start here username := params["username"] user, err := GetUserInternal(username) if err != nil { @@ -481,6 +489,7 @@ func updateUserAdm(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(user) } +// DeleteUser - deletes a given user func DeleteUser(user string) (bool, error) { if userRecord, err := database.FetchRecord(database.USERS_TABLE_NAME, user); err != nil || len(userRecord) == 0 { @@ -516,6 +525,7 @@ func deleteUser(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(params["username"] + " deleted.") } +// ValidateUser - validates a user model func ValidateUser(operation string, user models.User) error { v := validator.New()