server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "syscall"
  10. "time"
  11. "github.com/google/go-cmp/cmp"
  12. "github.com/gorilla/mux"
  13. "golang.org/x/exp/slog"
  14. "github.com/gravitl/netmaker/database"
  15. "github.com/gravitl/netmaker/logger"
  16. "github.com/gravitl/netmaker/logic"
  17. "github.com/gravitl/netmaker/models"
  18. "github.com/gravitl/netmaker/mq"
  19. "github.com/gravitl/netmaker/servercfg"
  20. )
  21. var cpuProfileLog *os.File
  22. func serverHandlers(r *mux.Router) {
  23. // r.HandleFunc("/api/server/addnetwork/{network}", securityCheckServer(true, http.HandlerFunc(addNetwork))).Methods(http.MethodPost)
  24. r.HandleFunc(
  25. "/api/server/health",
  26. func(resp http.ResponseWriter, req *http.Request) {
  27. resp.WriteHeader(http.StatusOK)
  28. resp.Write([]byte("Server is up and running!!"))
  29. },
  30. ).Methods(http.MethodGet)
  31. r.HandleFunc(
  32. "/api/server/shutdown",
  33. func(w http.ResponseWriter, _ *http.Request) {
  34. msg := "received api call to shutdown server, sending interruption..."
  35. slog.Warn(msg)
  36. _, _ = w.Write([]byte(msg))
  37. w.WriteHeader(http.StatusOK)
  38. _ = syscall.Kill(syscall.Getpid(), syscall.SIGINT)
  39. },
  40. ).Methods(http.MethodPost)
  41. r.HandleFunc("/api/server/getconfig", allowUsers(http.HandlerFunc(getConfig))).
  42. Methods(http.MethodGet)
  43. r.HandleFunc("/api/server/settings", allowUsers(http.HandlerFunc(getSettings))).
  44. Methods(http.MethodGet)
  45. r.HandleFunc("/api/server/settings", logic.SecurityCheck(true, http.HandlerFunc(updateSettings))).
  46. Methods(http.MethodPut)
  47. r.HandleFunc("/api/server/getserverinfo", logic.SecurityCheck(true, http.HandlerFunc(getServerInfo))).
  48. Methods(http.MethodGet)
  49. r.HandleFunc("/api/server/status", getStatus).Methods(http.MethodGet)
  50. r.HandleFunc("/api/server/usage", logic.SecurityCheck(false, http.HandlerFunc(getUsage))).
  51. Methods(http.MethodGet)
  52. r.HandleFunc("/api/server/cpu_profile", logic.SecurityCheck(false, http.HandlerFunc(cpuProfile))).
  53. Methods(http.MethodPost)
  54. r.HandleFunc("/api/server/mem_profile", logic.SecurityCheck(false, http.HandlerFunc(memProfile))).
  55. Methods(http.MethodPost)
  56. r.HandleFunc("/api/server/feature_flags", getFeatureFlags).Methods(http.MethodGet)
  57. }
  58. func cpuProfile(w http.ResponseWriter, r *http.Request) {
  59. start := r.URL.Query().Get("action") == "start"
  60. if start {
  61. os.Remove("/root/data/cpu.prof")
  62. cpuProfileLog = logic.StartCPUProfiling()
  63. } else {
  64. if cpuProfileLog != nil {
  65. logic.StopCPUProfiling(cpuProfileLog)
  66. cpuProfileLog = nil
  67. }
  68. }
  69. }
  70. func memProfile(w http.ResponseWriter, r *http.Request) {
  71. os.Remove("/root/data/mem.prof")
  72. logic.StartMemProfiling()
  73. }
  74. func getUsage(w http.ResponseWriter, _ *http.Request) {
  75. w.Header().Set("Content-Type", "application/json")
  76. json.NewEncoder(w).Encode(models.SuccessResponse{
  77. Code: http.StatusOK,
  78. Response: logic.GetCurrentServerUsage(),
  79. })
  80. }
  81. // @Summary Get the server status
  82. // @Router /api/server/status [get]
  83. // @Tags Server
  84. // @Security oauth2
  85. func getStatus(w http.ResponseWriter, r *http.Request) {
  86. // @Success 200 {object} status
  87. type status struct {
  88. DB bool `json:"db_connected"`
  89. Broker bool `json:"broker_connected"`
  90. IsBrokerConnOpen bool `json:"is_broker_conn_open"`
  91. LicenseError string `json:"license_error"`
  92. IsPro bool `json:"is_pro"`
  93. TrialEndDate time.Time `json:"trial_end_date"`
  94. IsOnTrialLicense bool `json:"is_on_trial_license"`
  95. Version string `json:"version"`
  96. }
  97. licenseErr := ""
  98. if servercfg.ErrLicenseValidation != nil {
  99. licenseErr = servercfg.ErrLicenseValidation.Error()
  100. }
  101. //var trialEndDate time.Time
  102. //var err error
  103. // isOnTrial := false
  104. // if servercfg.IsPro &&
  105. // (servercfg.GetLicenseKey() == "" || servercfg.GetNetmakerTenantID() == "") {
  106. // trialEndDate, err = logic.GetTrialEndDate()
  107. // if err != nil {
  108. // slog.Error("failed to get trial end date", "error", err)
  109. // } else {
  110. // isOnTrial = true
  111. // }
  112. // }
  113. currentServerStatus := status{
  114. DB: database.IsConnected(),
  115. Broker: mq.IsConnected(),
  116. IsBrokerConnOpen: mq.IsConnectionOpen(),
  117. LicenseError: licenseErr,
  118. IsPro: servercfg.IsPro,
  119. Version: servercfg.Version,
  120. //TrialEndDate: trialEndDate,
  121. //IsOnTrialLicense: isOnTrial,
  122. }
  123. w.Header().Set("Content-Type", "application/json")
  124. json.NewEncoder(w).Encode(&currentServerStatus)
  125. }
  126. // allowUsers - allow all authenticated (valid) users - only used by getConfig, may be able to remove during refactor
  127. func allowUsers(next http.Handler) http.HandlerFunc {
  128. return func(w http.ResponseWriter, r *http.Request) {
  129. errorResponse := models.ErrorResponse{
  130. Code: http.StatusUnauthorized, Message: logic.Unauthorized_Msg,
  131. }
  132. bearerToken := r.Header.Get("Authorization")
  133. tokenSplit := strings.Split(bearerToken, " ")
  134. authToken := ""
  135. if len(tokenSplit) < 2 {
  136. logic.ReturnErrorResponse(w, r, errorResponse)
  137. return
  138. } else {
  139. authToken = tokenSplit[1]
  140. }
  141. user, _, _, err := logic.VerifyUserToken(authToken)
  142. if err != nil || user == "" {
  143. logic.ReturnErrorResponse(w, r, errorResponse)
  144. return
  145. }
  146. next.ServeHTTP(w, r)
  147. }
  148. }
  149. // @Summary Get the server information
  150. // @Router /api/server/getserverinfo [get]
  151. // @Tags Server
  152. // @Security oauth2
  153. // @Success 200 {object} models.ServerConfig
  154. func getServerInfo(w http.ResponseWriter, r *http.Request) {
  155. // Set header
  156. w.Header().Set("Content-Type", "application/json")
  157. // get params
  158. json.NewEncoder(w).Encode(logic.GetServerInfo())
  159. // w.WriteHeader(http.StatusOK)
  160. }
  161. // @Summary Get the server configuration
  162. // @Router /api/server/getconfig [get]
  163. // @Tags Server
  164. // @Security oauth2
  165. // @Success 200 {object} config.ServerConfig
  166. func getConfig(w http.ResponseWriter, r *http.Request) {
  167. // Set header
  168. w.Header().Set("Content-Type", "application/json")
  169. // get params
  170. scfg := logic.GetServerConfig()
  171. scfg.IsPro = "no"
  172. if servercfg.IsPro {
  173. scfg.IsPro = "yes"
  174. }
  175. scfg.ClientID = logic.Mask()
  176. scfg.ClientSecret = logic.Mask()
  177. json.NewEncoder(w).Encode(scfg)
  178. // w.WriteHeader(http.StatusOK)
  179. }
  180. // @Summary Get the server settings
  181. // @Router /api/server/settings [get]
  182. // @Tags Server
  183. // @Security oauth2
  184. // @Success 200 {object} config.ServerSettings
  185. func getSettings(w http.ResponseWriter, r *http.Request) {
  186. scfg := logic.GetServerSettings()
  187. if scfg.ClientSecret != "" {
  188. scfg.ClientSecret = logic.Mask()
  189. }
  190. logic.ReturnSuccessResponseWithJson(w, r, scfg, "fetched server settings successfully")
  191. }
  192. // @Summary Update the server settings
  193. // @Router /api/server/settings [put]
  194. // @Tags Server
  195. // @Security oauth2
  196. // @Success 200 {object} config.ServerSettings
  197. func updateSettings(w http.ResponseWriter, r *http.Request) {
  198. var req models.ServerSettings
  199. force := r.URL.Query().Get("force")
  200. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  201. logger.Log(0, r.Header.Get("user"), "error decoding request body: ", err.Error())
  202. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  203. return
  204. }
  205. if !logic.ValidateNewSettings(req) {
  206. logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("invalid settings"), "badrequest"))
  207. return
  208. }
  209. currSettings := logic.GetServerSettings()
  210. if req.AuthProvider != currSettings.AuthProvider && req.AuthProvider == "" {
  211. superAdmin, err := logic.GetSuperAdmin()
  212. if err != nil {
  213. err = fmt.Errorf("failed to get super admin: %v", err)
  214. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  215. return
  216. }
  217. if superAdmin.AuthType == models.OAuth {
  218. err := fmt.Errorf(
  219. "cannot remove IdP integration because an OAuth user has the super-admin role; transfer the super-admin role to another user first",
  220. )
  221. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
  222. return
  223. }
  224. }
  225. err := logic.UpsertServerSettings(req)
  226. if err != nil {
  227. logic.ReturnErrorResponse(w, r, logic.FormatError(errors.New("failed to update server settings "+err.Error()), "internal"))
  228. return
  229. }
  230. logic.LogEvent(&models.Event{
  231. Action: identifySettingsUpdateAction(currSettings, req),
  232. Source: models.Subject{
  233. ID: r.Header.Get("user"),
  234. Name: r.Header.Get("user"),
  235. Type: models.UserSub,
  236. },
  237. TriggeredBy: r.Header.Get("user"),
  238. Target: models.Subject{
  239. ID: models.SettingSub.String(),
  240. Name: models.SettingSub.String(),
  241. Type: models.SettingSub,
  242. },
  243. Diff: models.Diff{
  244. Old: currSettings,
  245. New: req,
  246. },
  247. Origin: models.Dashboard,
  248. })
  249. go reInit(currSettings, req, force == "true")
  250. logic.ReturnSuccessResponseWithJson(w, r, req, "updated server settings successfully")
  251. }
  252. func reInit(curr, new models.ServerSettings, force bool) {
  253. logic.SettingsMutex.Lock()
  254. defer logic.SettingsMutex.Unlock()
  255. logic.ResetAuthProvider()
  256. logic.EmailInit()
  257. logic.SetVerbosity(int(logic.GetServerSettings().Verbosity))
  258. logic.ResetIDPSyncHook()
  259. // check if auto update is changed
  260. if force {
  261. if curr.NetclientAutoUpdate != new.NetclientAutoUpdate {
  262. // update all hosts
  263. hosts, _ := logic.GetAllHosts()
  264. for _, host := range hosts {
  265. host.AutoUpdate = new.NetclientAutoUpdate
  266. logic.UpsertHost(&host)
  267. mq.HostUpdate(&models.HostUpdate{
  268. Action: models.UpdateHost,
  269. Host: host,
  270. })
  271. }
  272. }
  273. }
  274. go mq.PublishPeerUpdate(false)
  275. }
  276. func identifySettingsUpdateAction(old, new models.ServerSettings) models.Action {
  277. // TODO: here we are relying on the dashboard to only
  278. // make singular updates, but it's possible that the
  279. // API can be called to make multiple changes to the
  280. // server settings. We should update it to log multiple
  281. // events or create singular update APIs.
  282. if old.MFAEnforced != new.MFAEnforced {
  283. if new.MFAEnforced {
  284. return models.EnforceMFA
  285. } else {
  286. return models.UnenforceMFA
  287. }
  288. }
  289. if old.BasicAuth != new.BasicAuth {
  290. if new.BasicAuth {
  291. return models.EnableBasicAuth
  292. } else {
  293. return models.DisableBasicAuth
  294. }
  295. }
  296. if old.Telemetry != new.Telemetry {
  297. if new.Telemetry == "off" {
  298. return models.DisableTelemetry
  299. } else {
  300. return models.EnableTelemetry
  301. }
  302. }
  303. if old.NetclientAutoUpdate != new.NetclientAutoUpdate ||
  304. old.RacRestrictToSingleNetwork != new.RacRestrictToSingleNetwork ||
  305. old.ManageDNS != new.ManageDNS ||
  306. old.DefaultDomain != new.DefaultDomain ||
  307. old.EndpointDetection != new.EndpointDetection {
  308. return models.UpdateClientSettings
  309. }
  310. if old.AllowedEmailDomains != new.AllowedEmailDomains ||
  311. old.JwtValidityDuration != new.JwtValidityDuration {
  312. return models.UpdateAuthenticationSecuritySettings
  313. }
  314. if old.Verbosity != new.Verbosity ||
  315. old.MetricsPort != new.MetricsPort ||
  316. old.MetricInterval != new.MetricInterval ||
  317. old.AuditLogsRetentionPeriodInDays != new.AuditLogsRetentionPeriodInDays {
  318. return models.UpdateMonitoringAndDebuggingSettings
  319. }
  320. if old.EmailSenderAddr != new.EmailSenderAddr ||
  321. old.EmailSenderUser != new.EmailSenderUser ||
  322. old.EmailSenderPassword != new.EmailSenderPassword ||
  323. old.SmtpHost != new.SmtpHost ||
  324. old.SmtpPort != new.SmtpPort {
  325. return models.UpdateSMTPSettings
  326. }
  327. if old.AuthProvider != new.AuthProvider ||
  328. old.OIDCIssuer != new.OIDCIssuer ||
  329. old.ClientID != new.ClientID ||
  330. old.ClientSecret != new.ClientSecret ||
  331. old.SyncEnabled != new.SyncEnabled ||
  332. old.IDPSyncInterval != new.IDPSyncInterval ||
  333. old.GoogleAdminEmail != new.GoogleAdminEmail ||
  334. old.GoogleSACredsJson != new.GoogleSACredsJson ||
  335. old.AzureTenant != new.AzureTenant ||
  336. !cmp.Equal(old.GroupFilters, new.GroupFilters) ||
  337. cmp.Equal(old.UserFilters, new.UserFilters) {
  338. return models.UpdateIDPSettings
  339. }
  340. return models.Update
  341. }
  342. // @Summary Get feature flags for this server.
  343. // @Router /api/server/feature_flags [get]
  344. // @Tags Server
  345. // @Security oauth2
  346. // @Success 200 {object} config.ServerSettings
  347. func getFeatureFlags(w http.ResponseWriter, r *http.Request) {
  348. logic.ReturnSuccessResponseWithJson(w, r, logic.GetFeatureFlags(), "")
  349. }