register_callback.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. // check if user exists
  62. user, err := logic.GetUser(userClaims.getUserName())
  63. if err != nil {
  64. handleOauthUserNotFound(w)
  65. return
  66. }
  67. if user.PlatformRoleID != models.AdminRole && user.PlatformRoleID != models.SuperAdminRole {
  68. response := returnErrTemplate(userClaims.getUserName(), "only admin users can register using SSO", state, reqKeyIf)
  69. w.WriteHeader(http.StatusForbidden)
  70. w.Write(response)
  71. return
  72. }
  73. logger.Log(1, "registering host for user:", userClaims.getUserName(), reqKeyIf.Host.Name, reqKeyIf.Host.ID.String())
  74. // Send OK to user in the browser
  75. var response bytes.Buffer
  76. if err := ssoCallbackTemplate.Execute(&response, ssoCallbackTemplateConfig{
  77. User: userClaims.getUserName(),
  78. Verb: "Authenticated",
  79. }); err != nil {
  80. logger.Log(0, "Could not render SSO callback template ", err.Error())
  81. response := returnErrTemplate(reqKeyIf.User, "Could not render SSO callback template", state, reqKeyIf)
  82. w.WriteHeader(http.StatusInternalServerError)
  83. w.Write(response)
  84. } else {
  85. w.WriteHeader(http.StatusOK)
  86. w.Write(response.Bytes())
  87. }
  88. reqKeyIf.User = userClaims.getUserName() // set the cached registering hosts' user
  89. if err = netcache.Set(state, reqKeyIf); err != nil {
  90. logger.Log(0, "machine failed to complete join on network,", reqKeyIf.Network, "-", err.Error())
  91. return
  92. }
  93. }
  94. func setNetcache(ncache *netcache.CValue, state string) error {
  95. if ncache == nil {
  96. return fmt.Errorf("cache miss")
  97. }
  98. var err error
  99. if err = netcache.Set(state, ncache); err != nil {
  100. logger.Log(0, "machine failed to complete join on network,", ncache.Network, "-", err.Error())
  101. }
  102. return err
  103. }
  104. func returnErrTemplate(uname, message, state string, ncache *netcache.CValue) []byte {
  105. var response bytes.Buffer
  106. if ncache != nil {
  107. ncache.Pass = message
  108. }
  109. err := ssoErrCallbackTemplate.Execute(&response, ssoCallbackTemplateConfig{
  110. User: uname,
  111. Verb: message,
  112. })
  113. if err != nil {
  114. return []byte(err.Error())
  115. }
  116. err = setNetcache(ncache, state)
  117. if err != nil {
  118. return []byte(err.Error())
  119. }
  120. return response.Bytes()
  121. }
  122. // RegisterHostSSO redirects to the IDP for authentication
  123. // Puts machine key in cache so the callback can retrieve it using the oidc state param
  124. // Listens in /oidc/register/:regKey.
  125. func RegisterHostSSO(w http.ResponseWriter, r *http.Request) {
  126. if auth_provider == nil {
  127. w.WriteHeader(http.StatusBadRequest)
  128. w.Write([]byte("invalid login attempt"))
  129. return
  130. }
  131. vars := mux.Vars(r)
  132. // machineKeyStr this is not key but state
  133. machineKeyStr := vars["regKey"]
  134. if machineKeyStr == "" {
  135. w.WriteHeader(http.StatusBadRequest)
  136. w.Write([]byte("invalid login attempt"))
  137. return
  138. }
  139. http.Redirect(w, r, auth_provider.AuthCodeURL(machineKeyStr), http.StatusSeeOther)
  140. }