register_callback.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package auth
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/gorilla/mux"
  8. "github.com/gravitl/netmaker/logger"
  9. "github.com/gravitl/netmaker/logic"
  10. "github.com/gravitl/netmaker/logic/pro"
  11. "github.com/gravitl/netmaker/logic/pro/netcache"
  12. "github.com/gravitl/netmaker/models"
  13. "github.com/gravitl/netmaker/models/promodels"
  14. )
  15. var (
  16. redirectUrl string
  17. )
  18. // HandleHostSSOCallback handles the callback from the sso endpoint
  19. // It is the analogue of auth.handleNodeSSOCallback but takes care of the end point flow
  20. // Retrieves the mkey from the state cache and adds the machine to the users email namespace
  21. // TODO: A confirmation page for new machines should be added to avoid phishing vulnerabilities
  22. // TODO: Add groups information from OIDC tokens into machine HostInfo
  23. // Listens in /oidc/callback.
  24. func HandleHostSSOCallback(w http.ResponseWriter, r *http.Request) {
  25. var functions = getCurrentAuthFunctions()
  26. if functions == nil {
  27. w.WriteHeader(http.StatusBadRequest)
  28. w.Write([]byte("bad conf"))
  29. logger.Log(0, "Missing Oauth config in HandleNodeSSOCallback")
  30. return
  31. }
  32. state, code := getStateAndCode(r)
  33. var userClaims, err = functions[get_user_info].(func(string, string) (*OAuthUser, error))(state, code)
  34. if err != nil {
  35. logger.Log(0, "error when getting user info from callback:", err.Error())
  36. handleOauthNotConfigured(w)
  37. return
  38. }
  39. if code == "" || state == "" {
  40. w.WriteHeader(http.StatusBadRequest)
  41. w.Write([]byte("Wrong params"))
  42. logger.Log(0, "Missing params in HandleSSOCallback")
  43. return
  44. }
  45. // all responses should be in html format from here on out
  46. w.Header().Add("content-type", "text/html; charset=utf-8")
  47. // retrieve machinekey from state cache
  48. reqKeyIf, machineKeyFoundErr := netcache.Get(state)
  49. if machineKeyFoundErr != nil {
  50. logger.Log(0, "requested machine state key expired before authorisation completed -", machineKeyFoundErr.Error())
  51. reqKeyIf = &netcache.CValue{
  52. Network: "invalid",
  53. Value: state,
  54. Pass: "",
  55. User: "netmaker",
  56. Expiration: time.Now(),
  57. }
  58. response := returnErrTemplate("", "requested machine state key expired before authorisation completed", state, reqKeyIf)
  59. w.WriteHeader(http.StatusInternalServerError)
  60. w.Write(response)
  61. return
  62. }
  63. logger.Log(1, "registering host for user:", userClaims.getUserName(), reqKeyIf.Host.Name, reqKeyIf.Host.ID.String())
  64. // Send OK to user in the browser
  65. var response bytes.Buffer
  66. if err := ssoCallbackTemplate.Execute(&response, ssoCallbackTemplateConfig{
  67. User: userClaims.getUserName(),
  68. Verb: "Authenticated",
  69. }); err != nil {
  70. logger.Log(0, "Could not render SSO callback template ", err.Error())
  71. response := returnErrTemplate(reqKeyIf.User, "Could not render SSO callback template", state, reqKeyIf)
  72. w.WriteHeader(http.StatusInternalServerError)
  73. w.Write(response)
  74. } else {
  75. w.WriteHeader(http.StatusOK)
  76. w.Write(response.Bytes())
  77. }
  78. reqKeyIf.User = userClaims.getUserName() // set the cached registering hosts' user
  79. if err = netcache.Set(state, reqKeyIf); err != nil {
  80. logger.Log(0, "machine failed to complete join on network,", reqKeyIf.Network, "-", err.Error())
  81. return
  82. }
  83. }
  84. func setNetcache(ncache *netcache.CValue, state string) error {
  85. if ncache == nil {
  86. return fmt.Errorf("cache miss")
  87. }
  88. var err error
  89. if err = netcache.Set(state, ncache); err != nil {
  90. logger.Log(0, "machine failed to complete join on network,", ncache.Network, "-", err.Error())
  91. }
  92. return err
  93. }
  94. func returnErrTemplate(uname, message, state string, ncache *netcache.CValue) []byte {
  95. var response bytes.Buffer
  96. if ncache != nil {
  97. ncache.Pass = message
  98. }
  99. err := ssoErrCallbackTemplate.Execute(&response, ssoCallbackTemplateConfig{
  100. User: uname,
  101. Verb: message,
  102. })
  103. if err != nil {
  104. return []byte(err.Error())
  105. }
  106. err = setNetcache(ncache, state)
  107. if err != nil {
  108. return []byte(err.Error())
  109. }
  110. return response.Bytes()
  111. }
  112. // RegisterHostSSO redirects to the IDP for authentication
  113. // Puts machine key in cache so the callback can retrieve it using the oidc state param
  114. // Listens in /oidc/register/:regKey.
  115. func RegisterHostSSO(w http.ResponseWriter, r *http.Request) {
  116. if auth_provider == nil {
  117. w.WriteHeader(http.StatusBadRequest)
  118. w.Write([]byte("invalid login attempt"))
  119. return
  120. }
  121. vars := mux.Vars(r)
  122. // machineKeyStr this is not key but state
  123. machineKeyStr := vars["regKey"]
  124. if machineKeyStr == "" {
  125. w.WriteHeader(http.StatusBadRequest)
  126. w.Write([]byte("invalid login attempt"))
  127. return
  128. }
  129. http.Redirect(w, r, auth_provider.AuthCodeURL(machineKeyStr), http.StatusSeeOther)
  130. }
  131. // == private ==
  132. func isUserIsAllowed(username, network string, shouldAddUser bool) (*models.User, error) {
  133. user, err := logic.GetUser(username)
  134. if err != nil && shouldAddUser { // user must not exist, so try to make one
  135. if err = addUser(username); err != nil {
  136. logger.Log(0, "failed to add user", username, "during a node SSO network join on network", network)
  137. // response := returnErrTemplate(user.UserName, "failed to add user", state, reqKeyIf)
  138. // w.WriteHeader(http.StatusInternalServerError)
  139. // w.Write(response)
  140. return nil, fmt.Errorf("failed to add user to system")
  141. }
  142. logger.Log(0, "user", username, "was added during a node SSO network join on network", network)
  143. user, _ = logic.GetUser(username)
  144. }
  145. if !user.IsAdmin { // perform check to see if user is allowed to join a node to network
  146. netUser, err := pro.GetNetworkUser(network, promodels.NetworkUserID(user.UserName))
  147. if err != nil {
  148. logger.Log(0, "failed to get net user details for user", user.UserName, "during node SSO")
  149. return nil, fmt.Errorf("failed to verify network user")
  150. }
  151. if netUser.AccessLevel != pro.NET_ADMIN { // if user is a net admin on network, good to go
  152. // otherwise, check if they have node access + haven't reached node limit on network
  153. if netUser.AccessLevel == pro.NODE_ACCESS {
  154. if len(netUser.Nodes) >= netUser.NodeLimit {
  155. logger.Log(0, "user", user.UserName, "has reached their node limit on network", network)
  156. return nil, fmt.Errorf("user node limit exceeded")
  157. }
  158. } else {
  159. logger.Log(0, "user", user.UserName, "attempted to access network", network, "via node SSO")
  160. return nil, fmt.Errorf("network user not allowed")
  161. }
  162. }
  163. }
  164. return user, nil
  165. }