network.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/gorilla/mux"
  9. "github.com/gravitl/netmaker/database"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/logic"
  12. "github.com/gravitl/netmaker/logic/acls"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/mq"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "github.com/gravitl/netmaker/serverctl"
  17. )
  18. // ALL_NETWORK_ACCESS - represents all networks
  19. const ALL_NETWORK_ACCESS = "THIS_USER_HAS_ALL"
  20. // NO_NETWORKS_PRESENT - represents no networks
  21. const NO_NETWORKS_PRESENT = "THIS_USER_HAS_NONE"
  22. func networkHandlers(r *mux.Router) {
  23. r.HandleFunc("/api/networks", securityCheck(false, http.HandlerFunc(getNetworks))).Methods("GET")
  24. r.HandleFunc("/api/networks", securityCheck(true, http.HandlerFunc(createNetwork))).Methods("POST")
  25. r.HandleFunc("/api/networks/{networkname}", securityCheck(false, http.HandlerFunc(getNetwork))).Methods("GET")
  26. r.HandleFunc("/api/networks/{networkname}", securityCheck(false, http.HandlerFunc(updateNetwork))).Methods("PUT")
  27. r.HandleFunc("/api/networks/{networkname}/nodelimit", securityCheck(true, http.HandlerFunc(updateNetworkNodeLimit))).Methods("PUT")
  28. r.HandleFunc("/api/networks/{networkname}", securityCheck(true, http.HandlerFunc(deleteNetwork))).Methods("DELETE")
  29. r.HandleFunc("/api/networks/{networkname}/keyupdate", securityCheck(true, http.HandlerFunc(keyUpdate))).Methods("POST")
  30. r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(false, http.HandlerFunc(createAccessKey))).Methods("POST")
  31. r.HandleFunc("/api/networks/{networkname}/keys", securityCheck(false, http.HandlerFunc(getAccessKeys))).Methods("GET")
  32. r.HandleFunc("/api/networks/{networkname}/keys/{name}", securityCheck(false, http.HandlerFunc(deleteAccessKey))).Methods("DELETE")
  33. r.HandleFunc("/api/networks/{networkname}/acls", securityCheck(true, http.HandlerFunc(updateNetworkACL))).Methods("PUT")
  34. r.HandleFunc("/api/networks/{networkname}/acls", securityCheck(true, http.HandlerFunc(getNetworkACL))).Methods("GET")
  35. }
  36. //simple get all networks function
  37. func getNetworks(w http.ResponseWriter, r *http.Request) {
  38. headerNetworks := r.Header.Get("networks")
  39. networksSlice := []string{}
  40. marshalErr := json.Unmarshal([]byte(headerNetworks), &networksSlice)
  41. if marshalErr != nil {
  42. returnErrorResponse(w, r, formatError(marshalErr, "internal"))
  43. return
  44. }
  45. allnetworks := []models.Network{}
  46. var err error
  47. if networksSlice[0] == ALL_NETWORK_ACCESS {
  48. allnetworks, err = logic.GetNetworks()
  49. if err != nil && !database.IsEmptyRecord(err) {
  50. returnErrorResponse(w, r, formatError(err, "internal"))
  51. return
  52. }
  53. } else {
  54. for _, network := range networksSlice {
  55. netObject, parentErr := logic.GetParentNetwork(network)
  56. if parentErr == nil {
  57. allnetworks = append(allnetworks, netObject)
  58. }
  59. }
  60. }
  61. if !servercfg.IsDisplayKeys() {
  62. for i, net := range allnetworks {
  63. net.AccessKeys = logic.RemoveKeySensitiveInfo(net.AccessKeys)
  64. allnetworks[i] = net
  65. }
  66. }
  67. logger.Log(2, r.Header.Get("user"), "fetched networks.")
  68. w.WriteHeader(http.StatusOK)
  69. json.NewEncoder(w).Encode(allnetworks)
  70. }
  71. // Simple get network function
  72. func getNetwork(w http.ResponseWriter, r *http.Request) {
  73. // set header.
  74. w.Header().Set("Content-Type", "application/json")
  75. var params = mux.Vars(r)
  76. netname := params["networkname"]
  77. if isCommsEdit(w, r, netname) {
  78. return
  79. }
  80. network, err := logic.GetNetwork(netname)
  81. if err != nil {
  82. returnErrorResponse(w, r, formatError(err, "internal"))
  83. return
  84. }
  85. if !servercfg.IsDisplayKeys() {
  86. network.AccessKeys = logic.RemoveKeySensitiveInfo(network.AccessKeys)
  87. }
  88. logger.Log(2, r.Header.Get("user"), "fetched network", netname)
  89. w.WriteHeader(http.StatusOK)
  90. json.NewEncoder(w).Encode(network)
  91. }
  92. func keyUpdate(w http.ResponseWriter, r *http.Request) {
  93. w.Header().Set("Content-Type", "application/json")
  94. var params = mux.Vars(r)
  95. netname := params["networkname"]
  96. if isCommsEdit(w, r, netname) {
  97. return
  98. }
  99. network, err := logic.KeyUpdate(netname)
  100. if err != nil {
  101. returnErrorResponse(w, r, formatError(err, "internal"))
  102. return
  103. }
  104. logger.Log(2, r.Header.Get("user"), "updated key on network", netname)
  105. w.WriteHeader(http.StatusOK)
  106. json.NewEncoder(w).Encode(network)
  107. nodes, err := logic.GetNetworkNodes(netname)
  108. if err != nil {
  109. logger.Log(2, "failed to retrieve network nodes for network", netname, err.Error())
  110. return
  111. }
  112. for _, node := range nodes {
  113. logger.Log(2, "updating node ", node.Name, " for a key update")
  114. if node.IsServer != "yes" {
  115. if err = mq.NodeUpdate(&node); err != nil {
  116. logger.Log(1, "failed to send update to node during a network wide key update", node.Name, node.ID, err.Error())
  117. }
  118. }
  119. }
  120. }
  121. // Update a network
  122. func updateNetwork(w http.ResponseWriter, r *http.Request) {
  123. w.Header().Set("Content-Type", "application/json")
  124. var params = mux.Vars(r)
  125. var network models.Network
  126. netname := params["networkname"]
  127. network, err := logic.GetParentNetwork(netname)
  128. if err != nil {
  129. returnErrorResponse(w, r, formatError(err, "internal"))
  130. return
  131. }
  132. var newNetwork models.Network
  133. err = json.NewDecoder(r.Body).Decode(&newNetwork)
  134. if err != nil {
  135. returnErrorResponse(w, r, formatError(err, "badrequest"))
  136. return
  137. }
  138. if !servercfg.GetRce() {
  139. newNetwork.DefaultPostDown = network.DefaultPostDown
  140. newNetwork.DefaultPostUp = network.DefaultPostUp
  141. }
  142. rangeupdate, localrangeupdate, holepunchupdate, err := logic.UpdateNetwork(&network, &newNetwork)
  143. if err != nil {
  144. returnErrorResponse(w, r, formatError(err, "badrequest"))
  145. return
  146. }
  147. // if newNetwork.IsDualStack != currentNetwork.IsDualStack && newNetwork.IsDualStack == "no" {
  148. // // Remove IPv6 address from network nodes
  149. // RemoveNetworkNodeIPv6Addresses(currentNetwork.NetID)
  150. // }
  151. if rangeupdate {
  152. err = logic.UpdateNetworkNodeAddresses(network.NetID)
  153. if err != nil {
  154. returnErrorResponse(w, r, formatError(err, "internal"))
  155. return
  156. }
  157. }
  158. if localrangeupdate {
  159. err = logic.UpdateNetworkLocalAddresses(network.NetID)
  160. if err != nil {
  161. returnErrorResponse(w, r, formatError(err, "internal"))
  162. return
  163. }
  164. }
  165. if holepunchupdate {
  166. err = logic.UpdateNetworkHolePunching(network.NetID, newNetwork.DefaultUDPHolePunch)
  167. if err != nil {
  168. returnErrorResponse(w, r, formatError(err, "internal"))
  169. return
  170. }
  171. }
  172. if rangeupdate || localrangeupdate || holepunchupdate {
  173. nodes, err := logic.GetNetworkNodes(network.NetID)
  174. if err != nil {
  175. returnErrorResponse(w, r, formatError(err, "internal"))
  176. return
  177. }
  178. for _, node := range nodes {
  179. if err = mq.NodeUpdate(&node); err != nil {
  180. logger.Log(1, "failed to send update to node during a network wide update", node.Name, node.ID, err.Error())
  181. }
  182. }
  183. }
  184. logger.Log(1, r.Header.Get("user"), "updated network", netname)
  185. w.WriteHeader(http.StatusOK)
  186. json.NewEncoder(w).Encode(newNetwork)
  187. }
  188. func updateNetworkNodeLimit(w http.ResponseWriter, r *http.Request) {
  189. w.Header().Set("Content-Type", "application/json")
  190. var params = mux.Vars(r)
  191. var network models.Network
  192. netname := params["networkname"]
  193. network, err := logic.GetParentNetwork(netname)
  194. if err != nil {
  195. returnErrorResponse(w, r, formatError(err, "internal"))
  196. return
  197. }
  198. var networkChange models.Network
  199. _ = json.NewDecoder(r.Body).Decode(&networkChange)
  200. if networkChange.NodeLimit != 0 {
  201. network.NodeLimit = networkChange.NodeLimit
  202. data, err := json.Marshal(&network)
  203. if err != nil {
  204. returnErrorResponse(w, r, formatError(err, "badrequest"))
  205. return
  206. }
  207. database.Insert(network.NetID, string(data), database.NETWORKS_TABLE_NAME)
  208. logger.Log(1, r.Header.Get("user"), "updated network node limit on", netname)
  209. }
  210. w.WriteHeader(http.StatusOK)
  211. json.NewEncoder(w).Encode(network)
  212. }
  213. func updateNetworkACL(w http.ResponseWriter, r *http.Request) {
  214. w.Header().Set("Content-Type", "application/json")
  215. var params = mux.Vars(r)
  216. netname := params["networkname"]
  217. var networkACLChange acls.ACLContainer
  218. networkACLChange, err := networkACLChange.Get(acls.ContainerID(netname))
  219. if err != nil {
  220. returnErrorResponse(w, r, formatError(err, "internal"))
  221. return
  222. }
  223. _ = json.NewDecoder(r.Body).Decode(&networkACLChange)
  224. newNetACL, err := networkACLChange.Save(acls.ContainerID(netname))
  225. if err != nil {
  226. returnErrorResponse(w, r, formatError(err, "badrequest"))
  227. return
  228. }
  229. w.WriteHeader(http.StatusOK)
  230. json.NewEncoder(w).Encode(newNetACL)
  231. }
  232. func getNetworkACL(w http.ResponseWriter, r *http.Request) {
  233. w.Header().Set("Content-Type", "application/json")
  234. var params = mux.Vars(r)
  235. netname := params["networkname"]
  236. var networkACL acls.ACLContainer
  237. networkACL, err := networkACL.Get(acls.ContainerID(netname))
  238. if err != nil {
  239. returnErrorResponse(w, r, formatError(err, "internal"))
  240. return
  241. }
  242. w.WriteHeader(http.StatusOK)
  243. json.NewEncoder(w).Encode(networkACL)
  244. }
  245. // Delete a network
  246. // Will stop you if there's any nodes associated
  247. func deleteNetwork(w http.ResponseWriter, r *http.Request) {
  248. // Set header
  249. w.Header().Set("Content-Type", "application/json")
  250. var params = mux.Vars(r)
  251. network := params["networkname"]
  252. if isCommsEdit(w, r, network) {
  253. return
  254. }
  255. err := logic.DeleteNetwork(network)
  256. if err != nil {
  257. errtype := "badrequest"
  258. if strings.Contains(err.Error(), "Node check failed") {
  259. errtype = "forbidden"
  260. }
  261. returnErrorResponse(w, r, formatError(err, errtype))
  262. return
  263. }
  264. logger.Log(1, r.Header.Get("user"), "deleted network", network)
  265. w.WriteHeader(http.StatusOK)
  266. json.NewEncoder(w).Encode("success")
  267. }
  268. func createNetwork(w http.ResponseWriter, r *http.Request) {
  269. w.Header().Set("Content-Type", "application/json")
  270. var network models.Network
  271. // we decode our body request params
  272. err := json.NewDecoder(r.Body).Decode(&network)
  273. if err != nil {
  274. returnErrorResponse(w, r, formatError(err, "internal"))
  275. return
  276. }
  277. err = logic.CreateNetwork(network)
  278. if err != nil {
  279. returnErrorResponse(w, r, formatError(err, "badrequest"))
  280. return
  281. }
  282. if servercfg.IsClientMode() != "off" {
  283. var node models.Node
  284. node, err = logic.ServerJoin(&network)
  285. if err != nil {
  286. logic.DeleteNetwork(network.NetID)
  287. if err == nil {
  288. err = errors.New("Failed to add server to network " + network.NetID)
  289. }
  290. returnErrorResponse(w, r, formatError(err, "internal"))
  291. return
  292. }
  293. getServerAddrs(&node)
  294. }
  295. logger.Log(1, r.Header.Get("user"), "created network", network.NetID)
  296. w.WriteHeader(http.StatusOK)
  297. }
  298. // BEGIN KEY MANAGEMENT SECTION
  299. func createAccessKey(w http.ResponseWriter, r *http.Request) {
  300. w.Header().Set("Content-Type", "application/json")
  301. var params = mux.Vars(r)
  302. var accesskey models.AccessKey
  303. //start here
  304. netname := params["networkname"]
  305. if isCommsEdit(w, r, netname) {
  306. return
  307. }
  308. network, err := logic.GetParentNetwork(netname)
  309. if err != nil {
  310. returnErrorResponse(w, r, formatError(err, "internal"))
  311. return
  312. }
  313. err = json.NewDecoder(r.Body).Decode(&accesskey)
  314. if err != nil {
  315. returnErrorResponse(w, r, formatError(err, "internal"))
  316. return
  317. }
  318. key, err := logic.CreateAccessKey(accesskey, network)
  319. if err != nil {
  320. returnErrorResponse(w, r, formatError(err, "badrequest"))
  321. return
  322. }
  323. logger.Log(1, r.Header.Get("user"), "created access key", accesskey.Name, "on", netname)
  324. w.WriteHeader(http.StatusOK)
  325. json.NewEncoder(w).Encode(key)
  326. }
  327. // pretty simple get
  328. func getAccessKeys(w http.ResponseWriter, r *http.Request) {
  329. w.Header().Set("Content-Type", "application/json")
  330. var params = mux.Vars(r)
  331. network := params["networkname"]
  332. keys, err := logic.GetKeys(network)
  333. if err != nil {
  334. returnErrorResponse(w, r, formatError(err, "internal"))
  335. return
  336. }
  337. if !servercfg.IsDisplayKeys() {
  338. keys = logic.RemoveKeySensitiveInfo(keys)
  339. }
  340. logger.Log(2, r.Header.Get("user"), "fetched access keys on network", network)
  341. w.WriteHeader(http.StatusOK)
  342. json.NewEncoder(w).Encode(keys)
  343. }
  344. // delete key. Has to do a little funky logic since it's not a collection item
  345. func deleteAccessKey(w http.ResponseWriter, r *http.Request) {
  346. w.Header().Set("Content-Type", "application/json")
  347. var params = mux.Vars(r)
  348. keyname := params["name"]
  349. netname := params["networkname"]
  350. err := logic.DeleteKey(keyname, netname)
  351. if err != nil {
  352. returnErrorResponse(w, r, formatError(err, "badrequest"))
  353. return
  354. }
  355. logger.Log(1, r.Header.Get("user"), "deleted access key", keyname, "on network,", netname)
  356. w.WriteHeader(http.StatusOK)
  357. }
  358. func isCommsEdit(w http.ResponseWriter, r *http.Request, netname string) bool {
  359. if netname == serverctl.COMMS_NETID {
  360. returnErrorResponse(w, r, formatError(fmt.Errorf("cannot access comms network"), "internal"))
  361. return true
  362. }
  363. return false
  364. }
  365. func filterCommsNetwork(networks []models.Network) []models.Network {
  366. var filterdNets []models.Network
  367. for i := range networks {
  368. if networks[i].IsComms != "yes" && networks[i].NetID != servercfg.GetCommsID() {
  369. filterdNets = append(filterdNets, networks[i])
  370. }
  371. }
  372. return filterdNets
  373. }