serverconf.go 23 KB

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