handler.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package authn
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/gorilla/sessions"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/auth/token"
  13. "github.com/porter-dev/porter/internal/models"
  14. )
  15. // AuthNFactory generates a middleware handler `AuthN`
  16. type AuthNFactory struct {
  17. config *config.Config
  18. }
  19. // NewAuthNFactory returns an `AuthNFactory` that uses the passed-in server
  20. // config
  21. func NewAuthNFactory(
  22. config *config.Config,
  23. ) *AuthNFactory {
  24. return &AuthNFactory{config}
  25. }
  26. // NewAuthenticated creates a new instance of `AuthN` that implements the http.Handler
  27. // interface.
  28. func (f *AuthNFactory) NewAuthenticated(next http.Handler) http.Handler {
  29. return &AuthN{next, f.config, false}
  30. }
  31. // NewAuthenticatedWithRedirect creates a new instance of `AuthN` that implements the http.Handler
  32. // interface. This handler redirects the user to login if the user is not attached, and stores a
  33. // redirect URI in the session, if the session exists.
  34. func (f *AuthNFactory) NewAuthenticatedWithRedirect(next http.Handler) http.Handler {
  35. return &AuthN{next, f.config, true}
  36. }
  37. // AuthN implements the authentication middleware
  38. type AuthN struct {
  39. next http.Handler
  40. config *config.Config
  41. redirect bool
  42. }
  43. // ServeHTTP attaches an authenticated subject to the request context,
  44. // or serves a forbidden error. If authenticated, it calls the next handler.
  45. //
  46. // A token can either be issued for a specific project id or for a user. In the case
  47. // of a project id, we attach a service account to the context. In the case of a
  48. // user, we attach that user to the context.
  49. func (authn *AuthN) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  50. // first check for a bearer token
  51. tok, err := authn.getTokenFromRequest(r)
  52. // if the error is not an invalid auth error, the token was invalid, and we throw error
  53. // forbidden. If the error was an invalid auth error, we look for a cookie.
  54. if err != nil && err != errInvalidAuthHeader {
  55. authn.sendForbiddenError(err, w, r)
  56. return
  57. } else if err == nil && tok != nil {
  58. authn.verifyTokenWithNext(w, r, tok)
  59. return
  60. }
  61. // if the bearer token is not found, look for a request cookie
  62. session, err := authn.config.Store.Get(r, authn.config.ServerConf.CookieName)
  63. if err != nil {
  64. session.Values["authenticated"] = false
  65. // we attempt to save the session, but do not catch the error since we send the
  66. // forbidden error regardless
  67. session.Save(r, w)
  68. authn.sendForbiddenError(err, w, r)
  69. return
  70. }
  71. supportEmail := "support@porter.run"
  72. cancelTime := time.Date(2023, 0o1, 31, 14, 30, 0, 0, time.Now().Local().Location())
  73. if email, ok := session.Values["email"]; ok {
  74. if email.(string) == supportEmail {
  75. sess, _ := authn.config.Repo.Session().SelectSession(&models.Session{Key: session.ID})
  76. if sess.CreatedAt.Before(cancelTime) {
  77. _, _ = authn.config.Repo.Session().DeleteSession(sess)
  78. authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
  79. return
  80. }
  81. }
  82. }
  83. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  84. authn.handleForbiddenForSession(w, r, fmt.Errorf("stored cookie was not authenticated"), session)
  85. return
  86. }
  87. // read the user id in the token
  88. userID, ok := session.Values["user_id"].(uint)
  89. if !ok {
  90. authn.handleForbiddenForSession(w, r, fmt.Errorf("could not cast user_id to uint"), session)
  91. return
  92. }
  93. authn.nextWithUserID(w, r, userID)
  94. }
  95. func (authn *AuthN) handleForbiddenForSession(
  96. w http.ResponseWriter,
  97. r *http.Request,
  98. err error,
  99. session *sessions.Session,
  100. ) {
  101. if authn.redirect {
  102. // need state parameter to validate when redirected
  103. if r.URL.RawQuery == "" {
  104. session.Values["redirect_uri"] = r.URL.Path
  105. } else {
  106. session.Values["redirect_uri"] = r.URL.Path + "?" + r.URL.RawQuery
  107. }
  108. session.Save(r, w)
  109. http.Redirect(w, r, "/dashboard", 302)
  110. } else {
  111. authn.sendForbiddenError(err, w, r)
  112. }
  113. return
  114. }
  115. func (authn *AuthN) verifyTokenWithNext(w http.ResponseWriter, r *http.Request, tok *token.Token) {
  116. // if the token has a stored token id and secret we check that the token is valid in the database
  117. if tok.Secret != "" && tok.TokenID != "" {
  118. apiToken, err := authn.config.Repo.APIToken().ReadAPIToken(tok.ProjectID, tok.TokenID)
  119. if err != nil {
  120. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  121. return
  122. }
  123. // first ensure that the token hasn't been revoked, and the token has not expired
  124. if apiToken.Revoked || apiToken.IsExpired() {
  125. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  126. return
  127. }
  128. authn.nextWithAPIToken(w, r, apiToken)
  129. } else {
  130. // otherwise we just use nextWithUser using the `iby` field for the token
  131. authn.nextWithUserID(w, r, tok.IBy)
  132. }
  133. }
  134. // nextWithAPIToken sets the token in context
  135. func (authn *AuthN) nextWithAPIToken(w http.ResponseWriter, r *http.Request, tok *models.APIToken) {
  136. ctx := r.Context()
  137. ctx = context.WithValue(ctx, "api_token", tok)
  138. // add a service account user to the project: note that any calls depending on a DB lookup for the
  139. // user will fail
  140. ctx = context.WithValue(ctx, types.UserScope, &models.User{
  141. Email: fmt.Sprintf("%s-%d", tok.Name, tok.ProjectID),
  142. EmailVerified: true,
  143. })
  144. r = r.Clone(ctx)
  145. authn.next.ServeHTTP(w, r)
  146. }
  147. // nextWithUserID calls the next handler with the user set in the context with key
  148. // `types.UserScope`.
  149. func (authn *AuthN) nextWithUserID(w http.ResponseWriter, r *http.Request, userID uint) {
  150. // search for the user
  151. user, err := authn.config.Repo.User().ReadUser(userID)
  152. if err != nil {
  153. authn.sendForbiddenError(fmt.Errorf("user with id %d not found in database", userID), w, r)
  154. return
  155. }
  156. // add the user to the context
  157. ctx := r.Context()
  158. ctx = context.WithValue(ctx, types.UserScope, user)
  159. r = r.Clone(ctx)
  160. authn.next.ServeHTTP(w, r)
  161. }
  162. // sendForbiddenError sends a 403 Forbidden error to the end user while logging a
  163. // specific error
  164. func (authn *AuthN) sendForbiddenError(err error, w http.ResponseWriter, r *http.Request) {
  165. reqErr := apierrors.NewErrForbidden(err)
  166. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r, reqErr, true)
  167. }
  168. var (
  169. errInvalidToken = fmt.Errorf("authorization header exists, but token is not valid")
  170. errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
  171. )
  172. // getTokenFromRequest finds an `Authorization` header of the form `Bearer <token>`,
  173. // and returns a valid token if it exists.
  174. func (authn *AuthN) getTokenFromRequest(r *http.Request) (*token.Token, error) {
  175. reqToken := r.Header.Get("Authorization")
  176. splitToken := strings.Split(reqToken, "Bearer")
  177. if len(splitToken) != 2 {
  178. return nil, errInvalidAuthHeader
  179. }
  180. reqToken = strings.TrimSpace(splitToken[1])
  181. tok, err := token.GetTokenFromEncoded(reqToken, authn.config.TokenConf)
  182. if err != nil {
  183. return nil, errInvalidToken
  184. }
  185. return tok, nil
  186. }