2
0

handler.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package authn
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  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. 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. // special logic for GET /api/projects/{project_id}/invites/{token}
  98. if r.Method == "GET" && strings.Contains(r.URL.Path, "/invites/") &&
  99. !strings.HasSuffix(r.URL.Path, "/invites/") {
  100. pathSegments := strings.Split(r.URL.Path, "/")
  101. inviteToken := pathSegments[len(pathSegments)-1]
  102. invite, err := authn.config.Repo.Invite().ReadInviteByToken(inviteToken)
  103. if err != nil || invite.ProjectID == 0 || invite.Email == "" {
  104. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  105. apierrors.NewErrPassThroughToClient(fmt.Errorf("invalid invite token"), http.StatusBadRequest), true)
  106. return
  107. }
  108. if invite.IsExpired() || invite.IsAccepted() {
  109. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  110. apierrors.NewErrPassThroughToClient(fmt.Errorf("invite has expired"), http.StatusBadRequest), true)
  111. return
  112. }
  113. http.Redirect(w, r, "/register?email="+url.QueryEscape(invite.Email), http.StatusTemporaryRedirect)
  114. return
  115. }
  116. http.Redirect(w, r, "/dashboard", http.StatusFound)
  117. } else {
  118. authn.sendForbiddenError(err, w, r)
  119. }
  120. }
  121. func (authn *AuthN) verifyTokenWithNext(w http.ResponseWriter, r *http.Request, tok *token.Token) {
  122. // if the token has a stored token id we check that the token is valid in the database
  123. if tok.TokenID != "" {
  124. apiToken, err := authn.config.Repo.APIToken().ReadAPIToken(tok.ProjectID, tok.TokenID)
  125. if err != nil {
  126. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  127. return
  128. }
  129. // first ensure that the token hasn't been revoked, and the token has not expired
  130. if apiToken.Revoked || apiToken.IsExpired() {
  131. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  132. return
  133. }
  134. authn.nextWithAPIToken(w, r, apiToken)
  135. } else {
  136. // otherwise we just use nextWithUser using the `iby` field for the token
  137. authn.nextWithUserID(w, r, tok.IBy)
  138. }
  139. }
  140. // nextWithAPIToken sets the token in context
  141. func (authn *AuthN) nextWithAPIToken(w http.ResponseWriter, r *http.Request, tok *models.APIToken) {
  142. ctx := r.Context()
  143. ctx = context.WithValue(ctx, "api_token", tok)
  144. // add a service account user to the project: note that any calls depending on a DB lookup for the
  145. // user will fail
  146. ctx = context.WithValue(ctx, types.UserScope, &models.User{
  147. Email: fmt.Sprintf("%s-%d", tok.Name, tok.ProjectID),
  148. EmailVerified: true,
  149. })
  150. r = r.Clone(ctx)
  151. authn.next.ServeHTTP(w, r)
  152. }
  153. // nextWithUserID calls the next handler with the user set in the context with key
  154. // `types.UserScope`.
  155. func (authn *AuthN) nextWithUserID(w http.ResponseWriter, r *http.Request, userID uint) {
  156. // search for the user
  157. user, err := authn.config.Repo.User().ReadUser(userID)
  158. if err != nil {
  159. authn.sendForbiddenError(fmt.Errorf("user with id %d not found in database", userID), w, r)
  160. return
  161. }
  162. // add the user to the context
  163. ctx := r.Context()
  164. ctx = context.WithValue(ctx, types.UserScope, user)
  165. r = r.Clone(ctx)
  166. authn.next.ServeHTTP(w, r)
  167. }
  168. // sendForbiddenError sends a 403 Forbidden error to the end user while logging a
  169. // specific error
  170. func (authn *AuthN) sendForbiddenError(err error, w http.ResponseWriter, r *http.Request) {
  171. reqErr := apierrors.NewErrForbidden(err)
  172. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r, reqErr, true)
  173. }
  174. var (
  175. errInvalidToken = fmt.Errorf("authorization header exists, but token is not valid")
  176. errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
  177. )
  178. // getTokenFromRequest finds an `Authorization` header of the form `Bearer <token>`,
  179. // and returns a valid token if it exists.
  180. func (authn *AuthN) getTokenFromRequest(r *http.Request) (*token.Token, error) {
  181. reqToken := r.Header.Get("Authorization")
  182. splitToken := strings.Split(reqToken, "Bearer")
  183. if len(splitToken) != 2 {
  184. return nil, errInvalidAuthHeader
  185. }
  186. reqToken = strings.TrimSpace(splitToken[1])
  187. tok, err := token.GetTokenFromEncoded(reqToken, authn.config.TokenConf)
  188. if err != nil {
  189. return nil, fmt.Errorf("%s: %w", errInvalidToken.Error(), err)
  190. }
  191. return tok, nil
  192. }