nodeHttpController.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package controller
  2. import (
  3. "github.com/gravitl/netmaker/models"
  4. "github.com/gravitl/netmaker/functions"
  5. "github.com/gravitl/netmaker/mongoconn"
  6. "golang.org/x/crypto/bcrypt"
  7. "time"
  8. "strings"
  9. "fmt"
  10. "context"
  11. "encoding/json"
  12. "log"
  13. "net/http"
  14. "github.com/gorilla/mux"
  15. "go.mongodb.org/mongo-driver/bson"
  16. "go.mongodb.org/mongo-driver/mongo/options"
  17. )
  18. func nodeHandlers(r *mux.Router) {
  19. r.HandleFunc("/api/{group}/nodes", authorize(true, "group", http.HandlerFunc(getGroupNodes))).Methods("GET")
  20. r.HandleFunc("/api/nodes", authorize(false, "master", http.HandlerFunc(getAllNodes))).Methods("GET")
  21. r.HandleFunc("/api/{group}/peerlist", authorize(true, "group", http.HandlerFunc(getPeerList))).Methods("GET")
  22. r.HandleFunc("/api/{group}/lastmodified", authorize(true, "group", http.HandlerFunc(getLastModified))).Methods("GET")
  23. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(getNode))).Methods("GET")
  24. r.HandleFunc("/api/{group}/nodes", createNode).Methods("POST")
  25. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(updateNode))).Methods("PUT")
  26. r.HandleFunc("/api/{group}/nodes/{macaddress}/checkin", authorize(true, "node", http.HandlerFunc(checkIn))).Methods("POST")
  27. r.HandleFunc("/api/{group}/nodes/{macaddress}/uncordon", authorize(true, "master", http.HandlerFunc(uncordonNode))).Methods("POST")
  28. r.HandleFunc("/api/{group}/nodes/{macaddress}", authorize(true, "node", http.HandlerFunc(deleteNode))).Methods("DELETE")
  29. r.HandleFunc("/api/{group}/authenticate", authenticate).Methods("POST")
  30. }
  31. //Node authenticates using its password and retrieves a JWT for authorization.
  32. func authenticate(response http.ResponseWriter, request *http.Request) {
  33. //Auth request consists of Mac Address and Password (from node that is authorizing
  34. //in case of Master, auth is ignored and mac is set to "mastermac"
  35. var authRequest models.AuthParams
  36. var result models.Node
  37. var errorResponse = models.ErrorResponse{
  38. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  39. }
  40. //Get password fnd mac rom request
  41. decoder := json.NewDecoder(request.Body)
  42. decoderErr := decoder.Decode(&authRequest)
  43. defer request.Body.Close()
  44. if decoderErr != nil {
  45. returnErrorResponse(response, request, errorResponse)
  46. } else {
  47. errorResponse.Code = http.StatusBadRequest
  48. if authRequest.MacAddress == "" {
  49. errorResponse.Message = "W1R3: MacAddress can't be empty"
  50. returnErrorResponse(response, request, errorResponse)
  51. } else if authRequest.Password == "" {
  52. errorResponse.Message = "W1R3: Password can't be empty"
  53. returnErrorResponse(response, request, errorResponse)
  54. } else {
  55. //Search DB for node with Mac Address. Ignore pending nodes (they should not be able to authenticate with API untill approved).
  56. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  57. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  58. var err = collection.FindOne(ctx, bson.M{ "macaddress": authRequest.MacAddress, "ispending": false }).Decode(&result)
  59. defer cancel()
  60. if err != nil {
  61. returnErrorResponse(response, request, errorResponse)
  62. }
  63. //compare password from request to stored password in database
  64. //might be able to have a common hash (certificates?) and compare those so that a password isn't passed in in plain text...
  65. //TODO: Consider a way of hashing the password client side before sending, or using certificates
  66. err = bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(authRequest.Password))
  67. if err != nil {
  68. returnErrorResponse(response, request, errorResponse)
  69. } else {
  70. //Create a new JWT for the node
  71. tokenString, _ := functions.CreateJWT(authRequest.MacAddress, result.Group)
  72. if tokenString == "" {
  73. returnErrorResponse(response, request, errorResponse)
  74. }
  75. var successResponse = models.SuccessResponse{
  76. Code: http.StatusOK,
  77. Message: "W1R3: Device " + authRequest.MacAddress + " Authorized",
  78. Response: models.SuccessfulLoginResponse{
  79. AuthToken: tokenString,
  80. MacAddress: authRequest.MacAddress,
  81. },
  82. }
  83. //Send back the JWT
  84. successJSONResponse, jsonError := json.Marshal(successResponse)
  85. if jsonError != nil {
  86. returnErrorResponse(response, request, errorResponse)
  87. }
  88. response.Header().Set("Content-Type", "application/json")
  89. response.Write(successJSONResponse)
  90. }
  91. }
  92. }
  93. }
  94. //The middleware for most requests to the API
  95. //They all pass through here first
  96. //This will validate the JWT (or check for master token)
  97. //This will also check against the authGroup and make sure the node should be accessing that endpoint,
  98. //even if it's technically ok
  99. //This is kind of a poor man's RBAC. There's probably a better/smarter way.
  100. //TODO: Consider better RBAC implementations
  101. func authorize(groupCheck bool, authGroup string, next http.Handler) http.HandlerFunc {
  102. return func(w http.ResponseWriter, r *http.Request) {
  103. var errorResponse = models.ErrorResponse{
  104. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  105. }
  106. var params = mux.Vars(r)
  107. groupexists, _ := functions.GroupExists(params["group"])
  108. //check that the request is for a valid group
  109. //if (groupCheck && !groupexists) || err != nil {
  110. if (groupCheck && !groupexists) {
  111. errorResponse = models.ErrorResponse{
  112. Code: http.StatusNotFound, Message: "W1R3: This group does not exist. ",
  113. }
  114. returnErrorResponse(w, r, errorResponse)
  115. } else {
  116. w.Header().Set("Content-Type", "application/json")
  117. //get the auth token
  118. bearerToken := r.Header.Get("Authorization")
  119. var tokenSplit = strings.Split(bearerToken, " ")
  120. //I put this in in case the user doesn't put in a token at all (in which case it's empty)
  121. //There's probably a smarter way of handling this.
  122. var authToken = "928rt238tghgwe@TY@$Y@#WQAEGB2FC#@HG#@$Hddd"
  123. if len(tokenSplit) > 1 {
  124. authToken = tokenSplit[1]
  125. }
  126. //This checks if
  127. //A: the token is the master password
  128. //B: the token corresponds to a mac address, and if so, which one
  129. //TODO: There's probably a better way of dealing with the "master token"/master password. Plz Halp.
  130. macaddress, _, err := functions.VerifyToken(authToken)
  131. if err != nil {
  132. return
  133. }
  134. var isAuthorized = false
  135. //The mastermac (login with masterkey from config) can do everything!! May be dangerous.
  136. if macaddress == "mastermac" {
  137. isAuthorized = true
  138. //for everyone else, there's poor man's RBAC. The "cases" are defined in the routes in the handlers
  139. //So each route defines which access group should be allowed to access it
  140. } else {
  141. switch authGroup {
  142. case "all":
  143. isAuthorized = true
  144. case "nodes":
  145. isAuthorized = (macaddress != "")
  146. case "group":
  147. node, err := functions.GetNodeByMacAddress(params["group"], macaddress)
  148. if err != nil {
  149. return
  150. }
  151. isAuthorized = (node.Group == params["group"])
  152. case "node":
  153. isAuthorized = (macaddress == params["macaddress"])
  154. case "master":
  155. isAuthorized = (macaddress == "mastermac")
  156. default:
  157. isAuthorized = false
  158. }
  159. }
  160. if !isAuthorized {
  161. errorResponse = models.ErrorResponse{
  162. Code: http.StatusUnauthorized, Message: "W1R3: You are unauthorized to access this endpoint.",
  163. }
  164. returnErrorResponse(w, r, errorResponse)
  165. } else {
  166. //If authorized, this function passes along it's request and output to the appropriate route function.
  167. next.ServeHTTP(w, r)
  168. }
  169. }
  170. }
  171. }
  172. //Returns a list of peers in "plaintext" format, which can be piped straight to a file (peers.conf) on a local machine
  173. //Not sure if it would be better to do that here or to let the client handle the formatting.
  174. //TODO: May want to consider a different approach
  175. func getPeerList(w http.ResponseWriter, r *http.Request) {
  176. w.Header().Set("Content-Type", "application/json")
  177. var nodes []models.Node
  178. var params = mux.Vars(r)
  179. //Connection mongoDB with mongoconn class
  180. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  181. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  182. //Get all nodes in the relevant group which are NOT in pending state
  183. filter := bson.M{"group": params["group"], "ispending": false}
  184. cur, err := collection.Find(ctx, filter)
  185. if err != nil {
  186. mongoconn.GetError(err, w)
  187. return
  188. }
  189. // Close the cursor once finished and cancel if it takes too long
  190. defer cancel()
  191. for cur.Next(context.TODO()) {
  192. var node models.Node
  193. err := cur.Decode(&node)
  194. if err != nil {
  195. log.Fatal(err)
  196. }
  197. // add the node to our node array
  198. //maybe better to just return this? But then that's just GetNodes...
  199. nodes = append(nodes, node)
  200. }
  201. //Uh oh, fatal error! This needs some better error handling
  202. //TODO: needs appropriate error handling so the server doesnt shut down.
  203. if err := cur.Err(); err != nil {
  204. log.Fatal(err)
  205. }
  206. //Writes output in the style familiar to WireGuard
  207. //Get's piped to peers.conf locally after client request
  208. for _, n := range nodes {
  209. w.Write([]byte("[Peer] \n"))
  210. w.Write([]byte("PublicKey = " + n.PublicKey + "\n"))
  211. w.Write([]byte("AllowedIPs = " + n.Address + "/32" + "\n"))
  212. w.Write([]byte("PersistentKeepalive = " + fmt.Sprint(n.PersistentKeepalive) + "\n"))
  213. w.Write([]byte("Endpoint = " + n.Endpoint + ":" + fmt.Sprint(n.ListenPort) + "\n\n"))
  214. }
  215. }
  216. //Gets all nodes associated with group, including pending nodes
  217. func getGroupNodes(w http.ResponseWriter, r *http.Request) {
  218. w.Header().Set("Content-Type", "application/json")
  219. var nodes []models.ReturnNode
  220. var params = mux.Vars(r)
  221. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  222. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  223. filter := bson.M{"group": params["group"]}
  224. //Filtering out the ID field cuz Dillon doesn't like it. May want to filter out other fields in the future
  225. cur, err := collection.Find(ctx, filter, options.Find().SetProjection(bson.M{"_id": 0}))
  226. if err != nil {
  227. mongoconn.GetError(err, w)
  228. return
  229. }
  230. defer cancel()
  231. for cur.Next(context.TODO()) {
  232. //Using a different model for the ReturnNode (other than regular node).
  233. //Either we should do this for ALL structs (so Groups and Keys)
  234. //OR we should just use the original struct
  235. //My preference is to make some new return structs
  236. //TODO: Think about this. Not an immediate concern. Just need to get some consistency eventually
  237. var node models.ReturnNode
  238. err := cur.Decode(&node)
  239. if err != nil {
  240. log.Fatal(err)
  241. }
  242. // add item our array of nodes
  243. nodes = append(nodes, node)
  244. }
  245. //TODO: Another fatal error we should take care of.
  246. if err := cur.Err(); err != nil {
  247. log.Fatal(err)
  248. }
  249. //Returns all the nodes in JSON format
  250. json.NewEncoder(w).Encode(nodes)
  251. }
  252. //A separate function to get all nodes, not just nodes for a particular group.
  253. //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
  254. func getAllNodes(w http.ResponseWriter, r *http.Request) {
  255. w.Header().Set("Content-Type", "application/json")
  256. var nodes []models.ReturnNode
  257. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  258. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  259. // Filter out them ID's again
  260. cur, err := collection.Find(ctx, bson.M{}, options.Find().SetProjection(bson.M{"_id": 0}))
  261. if err != nil {
  262. mongoconn.GetError(err, w)
  263. return
  264. }
  265. defer cancel()
  266. for cur.Next(context.TODO()) {
  267. var node models.ReturnNode
  268. err := cur.Decode(&node)
  269. //TODO: Fatal error
  270. if err != nil {
  271. log.Fatal(err)
  272. }
  273. // add node to our array
  274. nodes = append(nodes, node)
  275. }
  276. //TODO: Fatal error
  277. if err := cur.Err(); err != nil {
  278. log.Fatal(err)
  279. }
  280. //Return all the nodes in JSON format
  281. json.NewEncoder(w).Encode(nodes)
  282. }
  283. //This function get's called when a node "checks in" at check in interval
  284. //Honestly I'm not sure what all it should be doing
  285. //TODO: Implement the necessary stuff, including the below
  286. //Check the last modified of the group
  287. //Check the last modified of the nodes
  288. //Write functions for responding to these two thingies
  289. func checkIn(w http.ResponseWriter, r *http.Request) {
  290. //TODO: Current thoughts:
  291. //Dont bother with a grouplastmodified
  292. //Instead, implement a "configupdate" boolean on nodes
  293. //when there is a group update that requrires a config update, then the node will pull its new config
  294. // set header.
  295. w.Header().Set("Content-Type", "application/json")
  296. var params = mux.Vars(r)
  297. var node models.Node
  298. //Retrieves node with DB Call which is inefficient. Let's just get the time and set it.
  299. //node = functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  300. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  301. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  302. filter := bson.M{"macaddress": params["macaddress"]}
  303. //old code was inefficient, this is all we need.
  304. time := time.Now().String()
  305. //node.SetLastCheckIn()
  306. // prepare update model with new time
  307. update := bson.D{
  308. {"$set", bson.D{
  309. {"lastcheckin", time},
  310. }},
  311. }
  312. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  313. defer cancel()
  314. if errN != nil {
  315. mongoconn.GetError(errN, w)
  316. return
  317. }
  318. //TODO: check node last modified vs group last modified
  319. json.NewEncoder(w).Encode(node)
  320. }
  321. //Get an individual node. Nothin fancy here folks.
  322. func getNode(w http.ResponseWriter, r *http.Request) {
  323. // set header.
  324. w.Header().Set("Content-Type", "application/json")
  325. var params = mux.Vars(r)
  326. node, err := GetNode(params["macaddress"], params["group"])
  327. if err != nil {
  328. mongoconn.GetError(err, w)
  329. return
  330. }
  331. json.NewEncoder(w).Encode(node)
  332. }
  333. //Get the time that a group of nodes was last modified.
  334. //TODO: This needs to be refactored
  335. //Potential way to do this: On UpdateNode, set a new field for "LastModified"
  336. //If we go with the existing way, we need to at least set group.NodesLastModified on UpdateNode
  337. func getLastModified(w http.ResponseWriter, r *http.Request) {
  338. // set header.
  339. w.Header().Set("Content-Type", "application/json")
  340. var group models.Group
  341. var params = mux.Vars(r)
  342. collection := mongoconn.Client.Database("wirecat").Collection("groups")
  343. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  344. filter := bson.M{"nameid": params["group"]}
  345. err := collection.FindOne(ctx, filter).Decode(&group)
  346. defer cancel()
  347. if err != nil {
  348. fmt.Println(err)
  349. //log.Fatal(err)
  350. }
  351. w.Write([]byte(string(group.NodesLastModified)))
  352. }
  353. //This one's a doozy
  354. //To create a node
  355. //Must have valid key and be unique
  356. func createNode(w http.ResponseWriter, r *http.Request) {
  357. w.Header().Set("Content-Type", "application/json")
  358. var params = mux.Vars(r)
  359. var errorResponse = models.ErrorResponse{
  360. Code: http.StatusInternalServerError, Message: "W1R3: It's not you it's me.",
  361. }
  362. groupName := params["group"]
  363. //Check if group exists first
  364. //TODO: This is inefficient. Let's find a better way.
  365. //Just a few rows down we grab the group anyway
  366. groupexists, errgroup := functions.GroupExists(groupName)
  367. if !groupexists || errgroup != nil {
  368. errorResponse = models.ErrorResponse{
  369. Code: http.StatusNotFound, Message: "W1R3: Group does not exist! ",
  370. }
  371. returnErrorResponse(w, r, errorResponse)
  372. return
  373. }
  374. var node models.Node
  375. //get node from body of request
  376. _ = json.NewDecoder(r.Body).Decode(&node)
  377. node.Group = groupName
  378. group, _ := node.GetGroup()
  379. //Check to see if key is valid
  380. //TODO: Triple inefficient!!! This is the third call to the DB we make for groups
  381. validKey := functions.IsKeyValid(groupName, node.AccessKey)
  382. if !validKey {
  383. //Check to see if group will allow manual sign up
  384. //may want to switch this up with the valid key check and avoid a DB call that way.
  385. if *group.AllowManualSignUp {
  386. node.IsPending = true
  387. } else {
  388. errorResponse = models.ErrorResponse{
  389. Code: http.StatusUnauthorized, Message: "W1R3: Key invalid, or none provided.",
  390. }
  391. returnErrorResponse(w, r, errorResponse)
  392. return
  393. }
  394. }
  395. err := ValidateNode("create", groupName, node)
  396. if err != nil {
  397. return
  398. }
  399. node, err = CreateNode(node, groupName)
  400. if err != nil {
  401. return
  402. }
  403. json.NewEncoder(w).Encode(node)
  404. }
  405. //Takes node out of pending state
  406. //TODO: May want to use cordon/uncordon terminology instead of "ispending".
  407. func uncordonNode(w http.ResponseWriter, r *http.Request) {
  408. w.Header().Set("Content-Type", "application/json")
  409. var params = mux.Vars(r)
  410. var node models.Node
  411. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  412. if err != nil {
  413. mongoconn.GetError(err, w)
  414. return
  415. }
  416. collection := mongoconn.Client.Database("wirecat").Collection("nodes")
  417. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  418. // Create filter
  419. filter := bson.M{"macaddress": params["macaddress"]}
  420. node.SetLastModified()
  421. fmt.Println("Uncordoning node " + node.Name)
  422. // prepare update model.
  423. update := bson.D{
  424. {"$set", bson.D{
  425. {"ispending", false},
  426. }},
  427. }
  428. errN := collection.FindOneAndUpdate(ctx, filter, update).Decode(&node)
  429. defer cancel()
  430. if errN != nil {
  431. mongoconn.GetError(errN, w)
  432. return
  433. }
  434. json.NewEncoder(w).Encode("SUCCESS")
  435. }
  436. func updateNode(w http.ResponseWriter, r *http.Request) {
  437. w.Header().Set("Content-Type", "application/json")
  438. var params = mux.Vars(r)
  439. //Get id from parameters
  440. //id, _ := primitive.ObjectIDFromHex(params["id"])
  441. var node models.Node
  442. //start here
  443. node, err := functions.GetNodeByMacAddress(params["group"], params["macaddress"])
  444. if err != nil {
  445. json.NewEncoder(w).Encode(err)
  446. return
  447. }
  448. var nodechange models.Node
  449. // we decode our body request params
  450. _ = json.NewDecoder(r.Body).Decode(&nodechange)
  451. if nodechange.Group == "" {
  452. nodechange.Group = node.Group
  453. }
  454. if nodechange.MacAddress == "" {
  455. nodechange.MacAddress = node.MacAddress
  456. }
  457. err = ValidateNode("update", params["group"], nodechange)
  458. if err != nil {
  459. json.NewEncoder(w).Encode(err)
  460. return
  461. }
  462. node, err = UpdateNode(nodechange, node)
  463. if err != nil {
  464. json.NewEncoder(w).Encode(err)
  465. return
  466. }
  467. json.NewEncoder(w).Encode(node)
  468. }
  469. //Delete a node
  470. //Pretty straightforward
  471. func deleteNode(w http.ResponseWriter, r *http.Request) {
  472. // Set header
  473. w.Header().Set("Content-Type", "application/json")
  474. // get params
  475. var params = mux.Vars(r)
  476. success, err := DeleteNode(params["macaddress"], params["group"])
  477. if err != nil || !success {
  478. json.NewEncoder(w).Encode("Could not delete node " + params["macaddress"])
  479. return
  480. }
  481. json.NewEncoder(w).Encode(params["macaddress"] + " deleted.")
  482. }
  483. //A fun lil method for handling errors with http
  484. //Used in some cases but not others
  485. //1. This should probably be an application-wide function
  486. //2. All the API calls should probably be using this
  487. //3. The mongoconn should probably use this.
  488. //4. Need a consistent approach to error handling generally. Very haphazard at the moment
  489. //TODO: This is important. All Handlers should be replying with appropriate error code.
  490. func returnErrorResponse(response http.ResponseWriter, request *http.Request, errorMesage models.ErrorResponse) {
  491. httpResponse := &models.ErrorResponse{Code: errorMesage.Code, Message: errorMesage.Message}
  492. jsonResponse, err := json.Marshal(httpResponse)
  493. if err != nil {
  494. panic(err)
  495. }
  496. response.Header().Set("Content-Type", "application/json")
  497. response.WriteHeader(errorMesage.Code)
  498. response.Write(jsonResponse)
  499. }