handler.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. package authn
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/gorilla/sessions"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/config"
  10. "github.com/porter-dev/porter/api/types"
  11. "github.com/porter-dev/porter/internal/auth/token"
  12. "github.com/porter-dev/porter/internal/models"
  13. "golang.org/x/crypto/bcrypt"
  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. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  72. authn.handleForbiddenForSession(w, r, fmt.Errorf("stored cookie was not authenticated"), session)
  73. return
  74. }
  75. // read the user id in the token
  76. userID, ok := session.Values["user_id"].(uint)
  77. if !ok {
  78. authn.handleForbiddenForSession(w, r, fmt.Errorf("could not cast user_id to uint"), session)
  79. return
  80. }
  81. authn.nextWithUserID(w, r, userID)
  82. }
  83. func (authn *AuthN) handleForbiddenForSession(
  84. w http.ResponseWriter,
  85. r *http.Request,
  86. err error,
  87. session *sessions.Session,
  88. ) {
  89. if authn.redirect {
  90. // need state parameter to validate when redirected
  91. if r.URL.RawQuery == "" {
  92. session.Values["redirect_uri"] = r.URL.Path
  93. } else {
  94. session.Values["redirect_uri"] = r.URL.Path + "?" + r.URL.RawQuery
  95. }
  96. session.Save(r, w)
  97. http.Redirect(w, r, "/dashboard", 302)
  98. } else {
  99. authn.sendForbiddenError(err, w, r)
  100. }
  101. return
  102. }
  103. func (authn *AuthN) verifyTokenWithNext(w http.ResponseWriter, r *http.Request, tok *token.Token) {
  104. // if the token has a stored token id and secret we check that the token is valid in the database
  105. if tok.Secret != "" && tok.TokenID != "" {
  106. apiToken, err := authn.config.Repo.APIToken().ReadAPIToken(tok.ProjectID, tok.TokenID)
  107. if err != nil {
  108. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  109. return
  110. }
  111. // first ensure that the token hasn't been revoked, and the token has not expired
  112. if apiToken.Revoked || apiToken.IsExpired() {
  113. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  114. return
  115. }
  116. // next, compare the secret against the hashed version
  117. if err := bcrypt.CompareHashAndPassword([]byte(apiToken.SecretKey), []byte(tok.Secret)); err != nil {
  118. authn.sendForbiddenError(fmt.Errorf("incorrect secret key for token %s", tok.TokenID), w, r)
  119. return
  120. }
  121. authn.nextWithAPIToken(w, r, apiToken)
  122. } else {
  123. // otherwise we just use nextWithUser using the `iby` field for the token
  124. authn.nextWithUserID(w, r, tok.IBy)
  125. }
  126. }
  127. // nextWithAPIToken sets the token in context
  128. func (authn *AuthN) nextWithAPIToken(w http.ResponseWriter, r *http.Request, tok *models.APIToken) {
  129. ctx := r.Context()
  130. ctx = context.WithValue(ctx, "api_token", tok)
  131. r = r.Clone(ctx)
  132. authn.next.ServeHTTP(w, r)
  133. }
  134. // nextWithUserID calls the next handler with the user set in the context with key
  135. // `types.UserScope`.
  136. func (authn *AuthN) nextWithUserID(w http.ResponseWriter, r *http.Request, userID uint) {
  137. // search for the user
  138. user, err := authn.config.Repo.User().ReadUser(userID)
  139. if err != nil {
  140. authn.sendForbiddenError(fmt.Errorf("user with id %d not found in database", userID), w, r)
  141. return
  142. }
  143. // add the user to the context
  144. ctx := r.Context()
  145. ctx = context.WithValue(ctx, types.UserScope, user)
  146. r = r.Clone(ctx)
  147. authn.next.ServeHTTP(w, r)
  148. }
  149. // sendForbiddenError sends a 403 Forbidden error to the end user while logging a
  150. // specific error
  151. func (authn *AuthN) sendForbiddenError(err error, w http.ResponseWriter, r *http.Request) {
  152. reqErr := apierrors.NewErrForbidden(err)
  153. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r, reqErr, true)
  154. }
  155. var errInvalidToken = fmt.Errorf("authorization header exists, but token is not valid")
  156. var errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
  157. // getTokenFromRequest finds an `Authorization` header of the form `Bearer <token>`,
  158. // and returns a valid token if it exists.
  159. func (authn *AuthN) getTokenFromRequest(r *http.Request) (*token.Token, error) {
  160. reqToken := r.Header.Get("Authorization")
  161. splitToken := strings.Split(reqToken, "Bearer")
  162. if len(splitToken) != 2 {
  163. return nil, errInvalidAuthHeader
  164. }
  165. reqToken = strings.TrimSpace(splitToken[1])
  166. tok, err := token.GetTokenFromEncoded(reqToken, authn.config.TokenConf)
  167. if err != nil {
  168. return nil, errInvalidToken
  169. }
  170. return tok, nil
  171. }