2
0

register_callback.go 5.1 KB

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