handler.go 8.5 KB

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