serverconf.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. package servercfg
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "os"
  7. "regexp"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gravitl/netmaker/config"
  12. "github.com/gravitl/netmaker/models"
  13. )
  14. var ServerInfo = GetServerInfo()
  15. // EmqxBrokerType denotes the broker type for EMQX MQTT
  16. const EmqxBrokerType = "emqx"
  17. // Emqxdeploy - emqx deploy type
  18. type Emqxdeploy string
  19. var (
  20. Version = "dev"
  21. IsPro = false
  22. ErrLicenseValidation error
  23. EmqxCloudDeploy Emqxdeploy = "cloud"
  24. EmqxOnPremDeploy Emqxdeploy = "on-prem"
  25. )
  26. // SetHost - sets the host ip
  27. func SetHost() error {
  28. remoteip, err := GetPublicIP()
  29. if err != nil {
  30. return err
  31. }
  32. os.Setenv("SERVER_HOST", remoteip)
  33. return nil
  34. }
  35. // GetServerConfig - gets the server config into memory from file or env
  36. func GetServerConfig() config.ServerConfig {
  37. var cfg config.ServerConfig
  38. cfg.APIConnString = GetAPIConnString()
  39. cfg.CoreDNSAddr = GetCoreDNSAddr()
  40. cfg.APIHost = GetAPIHost()
  41. cfg.APIPort = GetAPIPort()
  42. cfg.MasterKey = "(hidden)"
  43. cfg.DNSKey = "(hidden)"
  44. cfg.AllowedOrigin = GetAllowedOrigin()
  45. cfg.RestBackend = "off"
  46. cfg.NodeID = GetNodeID()
  47. cfg.BrokerType = GetBrokerType()
  48. cfg.EmqxRestEndpoint = GetEmqxRestEndpoint()
  49. if AutoUpdateEnabled() {
  50. cfg.NetclientAutoUpdate = "enabled"
  51. } else {
  52. cfg.NetclientAutoUpdate = "disabled"
  53. }
  54. if IsRestBackend() {
  55. cfg.RestBackend = "on"
  56. }
  57. cfg.DNSMode = "off"
  58. if IsDNSMode() {
  59. cfg.DNSMode = "on"
  60. }
  61. cfg.DisplayKeys = "off"
  62. if IsDisplayKeys() {
  63. cfg.DisplayKeys = "on"
  64. }
  65. cfg.DisableRemoteIPCheck = "off"
  66. if DisableRemoteIPCheck() {
  67. cfg.DisableRemoteIPCheck = "on"
  68. }
  69. cfg.Database = GetDB()
  70. cfg.Platform = GetPlatform()
  71. cfg.Version = GetVersion()
  72. cfg.PublicIp = GetServerHostIP()
  73. // == auth config ==
  74. var authInfo = GetAuthProviderInfo()
  75. cfg.AuthProvider = authInfo[0]
  76. cfg.ClientID = authInfo[1]
  77. cfg.ClientSecret = authInfo[2]
  78. cfg.FrontendURL = GetFrontendURL()
  79. cfg.Telemetry = Telemetry()
  80. cfg.Server = GetServer()
  81. cfg.Verbosity = GetVerbosity()
  82. cfg.IsPro = "no"
  83. if IsPro {
  84. cfg.IsPro = "yes"
  85. }
  86. cfg.JwtValidityDuration = GetJwtValidityDuration()
  87. cfg.RacAutoDisable = GetRacAutoDisable()
  88. cfg.RacRestrictToSingleNetwork = GetRacRestrictToSingleNetwork()
  89. cfg.MetricInterval = GetMetricInterval()
  90. cfg.ManageDNS = GetManageDNS()
  91. cfg.Stun = IsStunEnabled()
  92. cfg.StunServers = GetStunServers()
  93. cfg.DefaultDomain = GetDefaultDomain()
  94. return cfg
  95. }
  96. // GetJwtValidityDuration - returns the JWT validity duration in seconds
  97. func GetJwtValidityDuration() time.Duration {
  98. var defaultDuration = time.Duration(24) * time.Hour
  99. if os.Getenv("JWT_VALIDITY_DURATION") != "" {
  100. t, err := strconv.Atoi(os.Getenv("JWT_VALIDITY_DURATION"))
  101. if err != nil {
  102. return defaultDuration
  103. }
  104. return time.Duration(t) * time.Second
  105. }
  106. return defaultDuration
  107. }
  108. // GetRacAutoDisable - returns whether the feature to autodisable RAC is enabled
  109. func GetRacAutoDisable() bool {
  110. return os.Getenv("RAC_AUTO_DISABLE") == "true"
  111. }
  112. // GetRacRestrictToSingleNetwork - returns whether the feature to allow simultaneous network connections via RAC is enabled
  113. func GetRacRestrictToSingleNetwork() bool {
  114. return os.Getenv("RAC_RESTRICT_TO_SINGLE_NETWORK") == "true"
  115. }
  116. // GetServerInfo - gets the server config into memory from file or env
  117. func GetServerInfo() models.ServerConfig {
  118. var cfg models.ServerConfig
  119. cfg.Server = GetServer()
  120. if GetBrokerType() == EmqxBrokerType {
  121. cfg.MQUserName = "HOST_ID"
  122. cfg.MQPassword = "HOST_PASS"
  123. } else {
  124. cfg.MQUserName = GetMqUserName()
  125. cfg.MQPassword = GetMqPassword()
  126. }
  127. cfg.API = GetAPIConnString()
  128. cfg.CoreDNSAddr = GetCoreDNSAddr()
  129. cfg.APIPort = GetAPIPort()
  130. cfg.DNSMode = "off"
  131. cfg.Broker = GetPublicBrokerEndpoint()
  132. cfg.BrokerType = GetBrokerType()
  133. if IsDNSMode() {
  134. cfg.DNSMode = "on"
  135. }
  136. cfg.Version = GetVersion()
  137. cfg.IsPro = IsPro
  138. cfg.MetricInterval = GetMetricInterval()
  139. cfg.MetricsPort = GetMetricsPort()
  140. cfg.ManageDNS = GetManageDNS()
  141. cfg.Stun = IsStunEnabled()
  142. cfg.StunServers = GetStunServers()
  143. cfg.DefaultDomain = GetDefaultDomain()
  144. cfg.EndpointDetection = IsEndpointDetectionEnabled()
  145. return cfg
  146. }
  147. // GetFrontendURL - gets the frontend url
  148. func GetFrontendURL() string {
  149. var frontend = ""
  150. if os.Getenv("FRONTEND_URL") != "" {
  151. frontend = os.Getenv("FRONTEND_URL")
  152. } else if config.Config.Server.FrontendURL != "" {
  153. frontend = config.Config.Server.FrontendURL
  154. }
  155. return frontend
  156. }
  157. // GetAPIConnString - gets the api connections string
  158. func GetAPIConnString() string {
  159. conn := ""
  160. if os.Getenv("SERVER_API_CONN_STRING") != "" {
  161. conn = os.Getenv("SERVER_API_CONN_STRING")
  162. } else if config.Config.Server.APIConnString != "" {
  163. conn = config.Config.Server.APIConnString
  164. }
  165. return conn
  166. }
  167. // SetVersion - set version of netmaker
  168. func SetVersion(v string) {
  169. Version = v
  170. }
  171. // GetVersion - version of netmaker
  172. func GetVersion() string {
  173. return Version
  174. }
  175. // GetServerHostIP - fetches server IP
  176. func GetServerHostIP() string {
  177. return os.Getenv("SERVER_HOST")
  178. }
  179. // GetDB - gets the database type
  180. func GetDB() string {
  181. database := "sqlite"
  182. if os.Getenv("DATABASE") != "" {
  183. database = os.Getenv("DATABASE")
  184. } else if config.Config.Server.Database != "" {
  185. database = config.Config.Server.Database
  186. }
  187. return database
  188. }
  189. // CacheEnabled - checks if cache is enabled
  190. func CacheEnabled() bool {
  191. caching := true
  192. if os.Getenv("CACHING_ENABLED") == "false" {
  193. caching = false
  194. } else if config.Config.Server.CacheEnabled == "false" {
  195. caching = false
  196. }
  197. return caching
  198. }
  199. // GetAPIHost - gets the api host
  200. func GetAPIHost() string {
  201. serverhost := "127.0.0.1"
  202. remoteip, _ := GetPublicIP()
  203. if os.Getenv("SERVER_HTTP_HOST") != "" {
  204. serverhost = os.Getenv("SERVER_HTTP_HOST")
  205. } else if config.Config.Server.APIHost != "" {
  206. serverhost = config.Config.Server.APIHost
  207. } else if os.Getenv("SERVER_HOST") != "" {
  208. serverhost = os.Getenv("SERVER_HOST")
  209. } else {
  210. if remoteip != "" {
  211. serverhost = remoteip
  212. }
  213. }
  214. return serverhost
  215. }
  216. // GetAPIPort - gets the api port
  217. func GetAPIPort() string {
  218. apiport := "8081"
  219. if os.Getenv("API_PORT") != "" {
  220. apiport = os.Getenv("API_PORT")
  221. } else if config.Config.Server.APIPort != "" {
  222. apiport = config.Config.Server.APIPort
  223. }
  224. return apiport
  225. }
  226. // GetCoreDNSAddr - gets the core dns address
  227. func GetCoreDNSAddr() string {
  228. addr, _ := GetPublicIP()
  229. if os.Getenv("COREDNS_ADDR") != "" {
  230. addr = os.Getenv("COREDNS_ADDR")
  231. } else if config.Config.Server.CoreDNSAddr != "" {
  232. addr = config.Config.Server.CoreDNSAddr
  233. }
  234. return addr
  235. }
  236. // GetPublicBrokerEndpoint - returns the public broker endpoint which shall be used by netclient
  237. func GetPublicBrokerEndpoint() string {
  238. if os.Getenv("BROKER_ENDPOINT") != "" {
  239. return os.Getenv("BROKER_ENDPOINT")
  240. } else {
  241. return config.Config.Server.Broker
  242. }
  243. }
  244. func GetSmtpHost() string {
  245. v := ""
  246. if fromEnv := os.Getenv("SMTP_HOST"); fromEnv != "" {
  247. v = fromEnv
  248. } else if fromCfg := config.Config.Server.SmtpHost; fromCfg != "" {
  249. v = fromCfg
  250. }
  251. return v
  252. }
  253. func GetSmtpPort() int {
  254. v := 587
  255. if fromEnv := os.Getenv("SMTP_PORT"); fromEnv != "" {
  256. port, err := strconv.Atoi(fromEnv)
  257. if err == nil {
  258. v = port
  259. }
  260. } else if fromCfg := config.Config.Server.SmtpPort; fromCfg != 0 {
  261. v = fromCfg
  262. }
  263. return v
  264. }
  265. func GetSenderEmail() string {
  266. v := ""
  267. if fromEnv := os.Getenv("EMAIL_SENDER_ADDR"); fromEnv != "" {
  268. v = fromEnv
  269. } else if fromCfg := config.Config.Server.EmailSenderAddr; fromCfg != "" {
  270. v = fromCfg
  271. }
  272. return v
  273. }
  274. func GetSenderUser() string {
  275. v := ""
  276. if fromEnv := os.Getenv("EMAIL_SENDER_USER"); fromEnv != "" {
  277. v = fromEnv
  278. } else if fromCfg := config.Config.Server.EmailSenderUser; fromCfg != "" {
  279. v = fromCfg
  280. }
  281. return v
  282. }
  283. func GetEmaiSenderPassword() string {
  284. v := ""
  285. if fromEnv := os.Getenv("EMAIL_SENDER_PASSWORD"); fromEnv != "" {
  286. v = fromEnv
  287. } else if fromCfg := config.Config.Server.EmailSenderPassword; fromCfg != "" {
  288. v = fromCfg
  289. }
  290. return v
  291. }
  292. // GetOwnerEmail - gets the owner email (saas)
  293. func GetOwnerEmail() string {
  294. return os.Getenv("SAAS_OWNER_EMAIL")
  295. }
  296. // GetMessageQueueEndpoint - gets the message queue endpoint
  297. func GetMessageQueueEndpoint() (string, bool) {
  298. host, _ := GetPublicIP()
  299. if os.Getenv("SERVER_BROKER_ENDPOINT") != "" {
  300. host = os.Getenv("SERVER_BROKER_ENDPOINT")
  301. } else if config.Config.Server.ServerBrokerEndpoint != "" {
  302. host = config.Config.Server.ServerBrokerEndpoint
  303. } else if os.Getenv("BROKER_ENDPOINT") != "" {
  304. host = os.Getenv("BROKER_ENDPOINT")
  305. } else if config.Config.Server.Broker != "" {
  306. host = config.Config.Server.Broker
  307. } else {
  308. host += ":1883" // default
  309. }
  310. return host, strings.Contains(host, "wss") || strings.Contains(host, "ssl") || strings.Contains(host, "mqtts")
  311. }
  312. // GetBrokerType - returns the type of MQ broker
  313. func GetBrokerType() string {
  314. if os.Getenv("BROKER_TYPE") != "" {
  315. return os.Getenv("BROKER_TYPE")
  316. } else {
  317. return "mosquitto"
  318. }
  319. }
  320. // GetMasterKey - gets the configured master key of server
  321. func GetMasterKey() string {
  322. key := ""
  323. if os.Getenv("MASTER_KEY") != "" {
  324. key = os.Getenv("MASTER_KEY")
  325. } else if config.Config.Server.MasterKey != "" {
  326. key = config.Config.Server.MasterKey
  327. }
  328. return key
  329. }
  330. // GetAllowedOrigin - get the allowed origin
  331. func GetAllowedOrigin() string {
  332. allowedorigin := "*"
  333. if os.Getenv("CORS_ALLOWED_ORIGIN") != "" {
  334. allowedorigin = os.Getenv("CORS_ALLOWED_ORIGIN")
  335. } else if config.Config.Server.AllowedOrigin != "" {
  336. allowedorigin = config.Config.Server.AllowedOrigin
  337. }
  338. return allowedorigin
  339. }
  340. // IsRestBackend - checks if rest is on or off
  341. func IsRestBackend() bool {
  342. isrest := true
  343. if os.Getenv("REST_BACKEND") != "" {
  344. if os.Getenv("REST_BACKEND") == "off" {
  345. isrest = false
  346. }
  347. } else if config.Config.Server.RestBackend != "" {
  348. if config.Config.Server.RestBackend == "off" {
  349. isrest = false
  350. }
  351. }
  352. return isrest
  353. }
  354. // IsMetricsExporter - checks if metrics exporter is on or off
  355. func IsMetricsExporter() bool {
  356. export := false
  357. if os.Getenv("METRICS_EXPORTER") != "" {
  358. if os.Getenv("METRICS_EXPORTER") == "on" {
  359. export = true
  360. }
  361. } else if config.Config.Server.MetricsExporter != "" {
  362. if config.Config.Server.MetricsExporter == "on" {
  363. export = true
  364. }
  365. }
  366. return export
  367. }
  368. // IsMessageQueueBackend - checks if message queue is on or off
  369. func IsMessageQueueBackend() bool {
  370. ismessagequeue := true
  371. if os.Getenv("MESSAGEQUEUE_BACKEND") != "" {
  372. if os.Getenv("MESSAGEQUEUE_BACKEND") == "off" {
  373. ismessagequeue = false
  374. }
  375. } else if config.Config.Server.MessageQueueBackend != "" {
  376. if config.Config.Server.MessageQueueBackend == "off" {
  377. ismessagequeue = false
  378. }
  379. }
  380. return ismessagequeue
  381. }
  382. // Telemetry - checks if telemetry data should be sent
  383. func Telemetry() string {
  384. telemetry := "on"
  385. if os.Getenv("TELEMETRY") == "off" {
  386. telemetry = "off"
  387. }
  388. if config.Config.Server.Telemetry == "off" {
  389. telemetry = "off"
  390. }
  391. return telemetry
  392. }
  393. // GetServer - gets the server name
  394. func GetServer() string {
  395. server := ""
  396. if os.Getenv("SERVER_NAME") != "" {
  397. server = os.Getenv("SERVER_NAME")
  398. } else if config.Config.Server.Server != "" {
  399. server = config.Config.Server.Server
  400. }
  401. return server
  402. }
  403. func GetVerbosity() int32 {
  404. var verbosity = 0
  405. var err error
  406. if os.Getenv("VERBOSITY") != "" {
  407. verbosity, err = strconv.Atoi(os.Getenv("VERBOSITY"))
  408. if err != nil {
  409. verbosity = 0
  410. }
  411. } else if config.Config.Server.Verbosity != 0 {
  412. verbosity = int(config.Config.Server.Verbosity)
  413. }
  414. if verbosity < 0 || verbosity > 4 {
  415. verbosity = 0
  416. }
  417. return int32(verbosity)
  418. }
  419. // AutoUpdateEnabled returns a boolean indicating whether netclient auto update is enabled or disabled
  420. // default is enabled
  421. func AutoUpdateEnabled() bool {
  422. if os.Getenv("NETCLIENT_AUTO_UPDATE") == "disabled" {
  423. return false
  424. } else if config.Config.Server.NetclientAutoUpdate == "disabled" {
  425. return false
  426. }
  427. return true
  428. }
  429. // IsDNSMode - should it run with DNS
  430. func IsDNSMode() bool {
  431. isdns := true
  432. if os.Getenv("DNS_MODE") != "" {
  433. if os.Getenv("DNS_MODE") == "off" {
  434. isdns = false
  435. }
  436. } else if config.Config.Server.DNSMode != "" {
  437. if config.Config.Server.DNSMode == "off" {
  438. isdns = false
  439. }
  440. }
  441. return isdns
  442. }
  443. // IsDisplayKeys - should server be able to display keys?
  444. func IsDisplayKeys() bool {
  445. isdisplay := true
  446. if os.Getenv("DISPLAY_KEYS") != "" {
  447. if os.Getenv("DISPLAY_KEYS") == "off" {
  448. isdisplay = false
  449. }
  450. } else if config.Config.Server.DisplayKeys != "" {
  451. if config.Config.Server.DisplayKeys == "off" {
  452. isdisplay = false
  453. }
  454. }
  455. return isdisplay
  456. }
  457. // DisableRemoteIPCheck - disable the remote ip check
  458. func DisableRemoteIPCheck() bool {
  459. disabled := false
  460. if os.Getenv("DISABLE_REMOTE_IP_CHECK") != "" {
  461. if os.Getenv("DISABLE_REMOTE_IP_CHECK") == "on" {
  462. disabled = true
  463. }
  464. } else if config.Config.Server.DisableRemoteIPCheck != "" {
  465. if config.Config.Server.DisableRemoteIPCheck == "on" {
  466. disabled = true
  467. }
  468. }
  469. return disabled
  470. }
  471. // GetPublicIP - gets public ip
  472. func GetPublicIP() (string, error) {
  473. endpoint := ""
  474. var err error
  475. iplist := []string{"https://ifconfig.me/ip", "https://api.ipify.org", "https://ipinfo.io/ip"}
  476. publicIpService := os.Getenv("PUBLIC_IP_SERVICE")
  477. if publicIpService != "" {
  478. // prepend the user-specified service so it's checked first
  479. iplist = append([]string{publicIpService}, iplist...)
  480. } else if config.Config.Server.PublicIPService != "" {
  481. publicIpService = config.Config.Server.PublicIPService
  482. // prepend the user-specified service so it's checked first
  483. iplist = append([]string{publicIpService}, iplist...)
  484. }
  485. for _, ipserver := range iplist {
  486. client := &http.Client{
  487. Timeout: time.Second * 10,
  488. }
  489. resp, err := client.Get(ipserver)
  490. if err != nil {
  491. continue
  492. }
  493. defer resp.Body.Close()
  494. if resp.StatusCode == http.StatusOK {
  495. bodyBytes, err := io.ReadAll(resp.Body)
  496. if err != nil {
  497. continue
  498. }
  499. endpoint = string(bodyBytes)
  500. break
  501. }
  502. }
  503. if endpoint == "" {
  504. err = errors.New("public address not found")
  505. }
  506. return endpoint, err
  507. }
  508. // GetPlatform - get the system type of server
  509. func GetPlatform() string {
  510. platform := "linux"
  511. if os.Getenv("PLATFORM") != "" {
  512. platform = os.Getenv("PLATFORM")
  513. } else if config.Config.Server.Platform != "" {
  514. platform = config.Config.Server.Platform
  515. }
  516. return platform
  517. }
  518. // GetSQLConn - get the sql connection string
  519. func GetSQLConn() string {
  520. sqlconn := "http://"
  521. if os.Getenv("SQL_CONN") != "" {
  522. sqlconn = os.Getenv("SQL_CONN")
  523. } else if config.Config.Server.SQLConn != "" {
  524. sqlconn = config.Config.Server.SQLConn
  525. }
  526. return sqlconn
  527. }
  528. // GetNodeID - gets the node id
  529. func GetNodeID() string {
  530. var id string
  531. var err error
  532. // id = getMacAddr()
  533. if os.Getenv("NODE_ID") != "" {
  534. id = os.Getenv("NODE_ID")
  535. } else if config.Config.Server.NodeID != "" {
  536. id = config.Config.Server.NodeID
  537. } else {
  538. id, err = os.Hostname()
  539. if err != nil {
  540. return ""
  541. }
  542. }
  543. return id
  544. }
  545. func SetNodeID(id string) {
  546. config.Config.Server.NodeID = id
  547. }
  548. // GetAuthProviderInfo = gets the oauth provider info
  549. func GetAuthProviderInfo() (pi []string) {
  550. var authProvider = ""
  551. defer func() {
  552. if authProvider == "oidc" {
  553. if os.Getenv("OIDC_ISSUER") != "" {
  554. pi = append(pi, os.Getenv("OIDC_ISSUER"))
  555. } else if config.Config.Server.OIDCIssuer != "" {
  556. pi = append(pi, config.Config.Server.OIDCIssuer)
  557. } else {
  558. pi = []string{"", "", ""}
  559. }
  560. }
  561. }()
  562. if os.Getenv("AUTH_PROVIDER") != "" && os.Getenv("CLIENT_ID") != "" && os.Getenv("CLIENT_SECRET") != "" {
  563. authProvider = strings.ToLower(os.Getenv("AUTH_PROVIDER"))
  564. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  565. return []string{authProvider, os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")}
  566. } else {
  567. authProvider = ""
  568. }
  569. } else if config.Config.Server.AuthProvider != "" && config.Config.Server.ClientID != "" && config.Config.Server.ClientSecret != "" {
  570. authProvider = strings.ToLower(config.Config.Server.AuthProvider)
  571. if authProvider == "google" || authProvider == "azure-ad" || authProvider == "github" || authProvider == "oidc" {
  572. return []string{authProvider, config.Config.Server.ClientID, config.Config.Server.ClientSecret}
  573. }
  574. }
  575. return []string{"", "", ""}
  576. }
  577. // GetAzureTenant - retrieve the azure tenant ID from env variable or config file
  578. func GetAzureTenant() string {
  579. var azureTenant = ""
  580. if os.Getenv("AZURE_TENANT") != "" {
  581. azureTenant = os.Getenv("AZURE_TENANT")
  582. } else if config.Config.Server.AzureTenant != "" {
  583. azureTenant = config.Config.Server.AzureTenant
  584. }
  585. return azureTenant
  586. }
  587. // GetMqPassword - fetches the MQ password
  588. func GetMqPassword() string {
  589. password := ""
  590. if os.Getenv("MQ_PASSWORD") != "" {
  591. password = os.Getenv("MQ_PASSWORD")
  592. } else if config.Config.Server.MQPassword != "" {
  593. password = config.Config.Server.MQPassword
  594. }
  595. return password
  596. }
  597. // GetMqUserName - fetches the MQ username
  598. func GetMqUserName() string {
  599. password := ""
  600. if os.Getenv("MQ_USERNAME") != "" {
  601. password = os.Getenv("MQ_USERNAME")
  602. } else if config.Config.Server.MQUserName != "" {
  603. password = config.Config.Server.MQUserName
  604. }
  605. return password
  606. }
  607. // GetMetricsPort - get metrics port
  608. func GetMetricsPort() int {
  609. p := 51821
  610. if os.Getenv("METRICS_PORT") != "" {
  611. pStr := os.Getenv("METRICS_PORT")
  612. pInt, err := strconv.Atoi(pStr)
  613. if err == nil && pInt != 0 {
  614. p = pInt
  615. }
  616. }
  617. return p
  618. }
  619. // GetMetricInterval - get the publish metric interval
  620. func GetMetricIntervalInMinutes() time.Duration {
  621. //default 15 minutes
  622. mi := "15"
  623. if os.Getenv("PUBLISH_METRIC_INTERVAL") != "" {
  624. mi = os.Getenv("PUBLISH_METRIC_INTERVAL")
  625. }
  626. interval, err := strconv.Atoi(mi)
  627. if err != nil {
  628. interval = 15
  629. }
  630. return time.Duration(interval) * time.Minute
  631. }
  632. // GetMetricInterval - get the publish metric interval
  633. func GetMetricInterval() string {
  634. //default 15 minutes
  635. mi := "15"
  636. if os.Getenv("PUBLISH_METRIC_INTERVAL") != "" {
  637. mi = os.Getenv("PUBLISH_METRIC_INTERVAL")
  638. }
  639. return mi
  640. }
  641. // GetManageDNS - if manage DNS enabled or not
  642. func GetManageDNS() bool {
  643. enabled := false
  644. if os.Getenv("MANAGE_DNS") != "" {
  645. enabled = os.Getenv("MANAGE_DNS") == "true"
  646. }
  647. return enabled
  648. }
  649. func IsOldAclEnabled() bool {
  650. enabled := true
  651. if os.Getenv("OLD_ACL_SUPPORT") != "" {
  652. enabled = os.Getenv("OLD_ACL_SUPPORT") == "true"
  653. }
  654. return enabled
  655. }
  656. // GetDefaultDomain - get the default domain
  657. func GetDefaultDomain() string {
  658. //default hosted.nm
  659. var domain string
  660. if os.Getenv("DEFAULT_DOMAIN") != "" {
  661. if validateDomain(os.Getenv("DEFAULT_DOMAIN")) {
  662. domain = os.Getenv("DEFAULT_DOMAIN")
  663. }
  664. }
  665. return domain
  666. }
  667. func validateDomain(domain string) bool {
  668. domainPattern := `[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}(\.[a-zA-Z0-9][a-zA-Z0-9_-]{0,62})*(\.[a-zA-Z][a-zA-Z0-9]{0,10}){1}`
  669. exp := regexp.MustCompile("^" + domainPattern + "$")
  670. return exp.MatchString(domain)
  671. }
  672. // GetEmqxRestEndpoint - returns the REST API Endpoint of EMQX
  673. func GetEmqxRestEndpoint() string {
  674. return os.Getenv("EMQX_REST_ENDPOINT")
  675. }
  676. // IsBasicAuthEnabled - checks if basic auth has been configured to be turned off
  677. func IsBasicAuthEnabled() bool {
  678. var enabled = true //default
  679. if os.Getenv("BASIC_AUTH") != "" {
  680. enabled = os.Getenv("BASIC_AUTH") == "yes"
  681. } else if config.Config.Server.BasicAuth != "" {
  682. enabled = config.Config.Server.BasicAuth == "yes"
  683. }
  684. return enabled
  685. }
  686. // GetLicenseKey - retrieves pro license value from env or conf files
  687. func GetLicenseKey() string {
  688. licenseKeyValue := os.Getenv("LICENSE_KEY")
  689. if licenseKeyValue == "" {
  690. licenseKeyValue = config.Config.Server.LicenseValue
  691. }
  692. return licenseKeyValue
  693. }
  694. // GetNetmakerTenantID - get's the associated, Netmaker, tenant ID to verify ownership
  695. func GetNetmakerTenantID() string {
  696. netmakerTenantID := os.Getenv("NETMAKER_TENANT_ID")
  697. if netmakerTenantID == "" {
  698. netmakerTenantID = config.Config.Server.NetmakerTenantID
  699. }
  700. return netmakerTenantID
  701. }
  702. // GetUserLimit - fetches free tier limits on users
  703. func GetUserLimit() int {
  704. var userslimit int
  705. if os.Getenv("USERS_LIMIT") != "" {
  706. userslimit, _ = strconv.Atoi(os.Getenv("USERS_LIMIT"))
  707. } else {
  708. userslimit = config.Config.Server.UsersLimit
  709. }
  710. return userslimit
  711. }
  712. // GetNetworkLimit - fetches free tier limits on networks
  713. func GetNetworkLimit() int {
  714. var networkslimit int
  715. if os.Getenv("NETWORKS_LIMIT") != "" {
  716. networkslimit, _ = strconv.Atoi(os.Getenv("NETWORKS_LIMIT"))
  717. } else {
  718. networkslimit = config.Config.Server.NetworksLimit
  719. }
  720. return networkslimit
  721. }
  722. // GetMachinesLimit - fetches free tier limits on machines (clients + hosts)
  723. func GetMachinesLimit() int {
  724. if l, err := strconv.Atoi(os.Getenv("MACHINES_LIMIT")); err == nil {
  725. return l
  726. }
  727. return config.Config.Server.MachinesLimit
  728. }
  729. // GetIngressLimit - fetches free tier limits on ingresses
  730. func GetIngressLimit() int {
  731. if l, err := strconv.Atoi(os.Getenv("INGRESSES_LIMIT")); err == nil {
  732. return l
  733. }
  734. return config.Config.Server.IngressesLimit
  735. }
  736. // GetEgressLimit - fetches free tier limits on egresses
  737. func GetEgressLimit() int {
  738. if l, err := strconv.Atoi(os.Getenv("EGRESSES_LIMIT")); err == nil {
  739. return l
  740. }
  741. return config.Config.Server.EgressesLimit
  742. }
  743. // DeployedByOperator - returns true if the instance is deployed by netmaker operator
  744. func DeployedByOperator() bool {
  745. if os.Getenv("DEPLOYED_BY_OPERATOR") != "" {
  746. return os.Getenv("DEPLOYED_BY_OPERATOR") == "true"
  747. }
  748. return config.Config.Server.DeployedByOperator
  749. }
  750. // IsEndpointDetectionEnabled - returns true if endpoint detection enabled
  751. func IsEndpointDetectionEnabled() bool {
  752. var enabled = true //default
  753. if os.Getenv("ENDPOINT_DETECTION") != "" {
  754. enabled = os.Getenv("ENDPOINT_DETECTION") == "true"
  755. }
  756. return enabled
  757. }
  758. // IsStunEnabled - returns true if STUN set to on
  759. func IsStunEnabled() bool {
  760. var enabled = true
  761. if os.Getenv("STUN") != "" {
  762. enabled = os.Getenv("STUN") == "true"
  763. }
  764. return enabled
  765. }
  766. func GetStunServers() string {
  767. return os.Getenv("STUN_SERVERS")
  768. }
  769. // GetEnvironment returns the environment the server is running in (e.g. dev, staging, prod...)
  770. func GetEnvironment() string {
  771. if env := os.Getenv("ENVIRONMENT"); env != "" {
  772. return env
  773. }
  774. if env := config.Config.Server.Environment; env != "" {
  775. return env
  776. }
  777. return ""
  778. }
  779. // GetEmqxDeployType - fetches emqx deploy type this server uses
  780. func GetEmqxDeployType() (deployType Emqxdeploy) {
  781. deployType = EmqxOnPremDeploy
  782. if os.Getenv("EMQX_DEPLOY_TYPE") == string(EmqxCloudDeploy) {
  783. deployType = EmqxCloudDeploy
  784. }
  785. return
  786. }
  787. // GetEmqxAppID - gets the emqx cloud app id
  788. func GetEmqxAppID() string {
  789. return os.Getenv("EMQX_APP_ID")
  790. }
  791. // GetEmqxAppSecret - gets the emqx cloud app secret
  792. func GetEmqxAppSecret() string {
  793. return os.Getenv("EMQX_APP_SECRET")
  794. }
  795. // GetAllowedEmailDomains - gets the allowed email domains for oauth signup
  796. func GetAllowedEmailDomains() string {
  797. allowedDomains := "*"
  798. if os.Getenv("ALLOWED_EMAIL_DOMAINS") != "" {
  799. allowedDomains = os.Getenv("ALLOWED_EMAIL_DOMAINS")
  800. } else if config.Config.Server.AllowedEmailDomains != "" {
  801. allowedDomains = config.Config.Server.AllowedEmailDomains
  802. }
  803. return allowedDomains
  804. }
  805. // GetNmBaseDomain - fetches nm base domain
  806. func GetNmBaseDomain() string {
  807. return os.Getenv("NM_DOMAIN")
  808. }