register_callback.go 4.7 KB

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