2
0

handler.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. if cancelTokens(time.Date(2024, 0o1, 16, 18, 35, 0, 0, est), "support@porter.run", authn, session) {
  91. authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
  92. return
  93. }
  94. if cancelTokens(time.Date(2024, 0o1, 16, 18, 35, 0, 0, est), "admin@porter.run", authn, session) {
  95. authn.handleForbiddenForSession(w, r, fmt.Errorf("error, contact admin"), session)
  96. return
  97. }
  98. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  99. authn.handleForbiddenForSession(w, r, fmt.Errorf("stored cookie was not authenticated"), session)
  100. return
  101. }
  102. // read the user id in the token
  103. userID, ok := session.Values["user_id"].(uint)
  104. if !ok {
  105. authn.handleForbiddenForSession(w, r, fmt.Errorf("could not cast user_id to uint"), session)
  106. return
  107. }
  108. authn.nextWithUserID(w, r, userID)
  109. }
  110. func (authn *AuthN) handleForbiddenForSession(
  111. w http.ResponseWriter,
  112. r *http.Request,
  113. err error,
  114. session *sessions.Session,
  115. ) {
  116. if authn.redirect {
  117. // need state parameter to validate when redirected
  118. if r.URL.RawQuery == "" {
  119. session.Values["redirect_uri"] = r.URL.Path
  120. } else {
  121. session.Values["redirect_uri"] = r.URL.Path + "?" + r.URL.RawQuery
  122. }
  123. session.Save(r, w)
  124. // special logic for GET /api/projects/{project_id}/invites/{token}
  125. if r.Method == "GET" && strings.Contains(r.URL.Path, "/invites/") &&
  126. !strings.HasSuffix(r.URL.Path, "/invites/") {
  127. pathSegments := strings.Split(r.URL.Path, "/")
  128. inviteToken := pathSegments[len(pathSegments)-1]
  129. invite, err := authn.config.Repo.Invite().ReadInviteByToken(inviteToken)
  130. if err != nil || invite.ProjectID == 0 || invite.Email == "" {
  131. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  132. apierrors.NewErrPassThroughToClient(fmt.Errorf("invalid invite token"), http.StatusBadRequest), true)
  133. return
  134. }
  135. if invite.IsExpired() || invite.IsAccepted() {
  136. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  137. apierrors.NewErrPassThroughToClient(fmt.Errorf("invite has expired"), http.StatusBadRequest), true)
  138. return
  139. }
  140. http.Redirect(w, r, "/register?email="+url.QueryEscape(invite.Email), http.StatusTemporaryRedirect)
  141. return
  142. }
  143. http.Redirect(w, r, "/dashboard", http.StatusFound)
  144. } else {
  145. authn.sendForbiddenError(err, w, r)
  146. }
  147. }
  148. func (authn *AuthN) verifyTokenWithNext(w http.ResponseWriter, r *http.Request, tok *token.Token) {
  149. // if the token has a stored token id we check that the token is valid in the database
  150. if tok.TokenID != "" {
  151. apiToken, err := authn.config.Repo.APIToken().ReadAPIToken(tok.ProjectID, tok.TokenID)
  152. if err != nil {
  153. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  154. return
  155. }
  156. // first ensure that the token hasn't been revoked, and the token has not expired
  157. if apiToken.Revoked || apiToken.IsExpired() {
  158. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  159. return
  160. }
  161. authn.nextWithAPIToken(w, r, apiToken)
  162. } else {
  163. // otherwise we just use nextWithUser using the `iby` field for the token
  164. authn.nextWithUserID(w, r, tok.IBy)
  165. }
  166. }
  167. // nextWithAPIToken sets the token in context
  168. func (authn *AuthN) nextWithAPIToken(w http.ResponseWriter, r *http.Request, tok *models.APIToken) {
  169. ctx := r.Context()
  170. ctx = context.WithValue(ctx, "api_token", tok)
  171. // add a service account user to the project: note that any calls depending on a DB lookup for the
  172. // user will fail
  173. ctx = context.WithValue(ctx, types.UserScope, &models.User{
  174. Email: fmt.Sprintf("%s-%d", tok.Name, tok.ProjectID),
  175. EmailVerified: true,
  176. })
  177. r = r.Clone(ctx)
  178. authn.next.ServeHTTP(w, r)
  179. }
  180. // nextWithUserID calls the next handler with the user set in the context with key
  181. // `types.UserScope`.
  182. func (authn *AuthN) nextWithUserID(w http.ResponseWriter, r *http.Request, userID uint) {
  183. // search for the user
  184. user, err := authn.config.Repo.User().ReadUser(userID)
  185. if err != nil {
  186. authn.sendForbiddenError(fmt.Errorf("user with id %d not found in database", userID), w, r)
  187. return
  188. }
  189. // add the user to the context
  190. ctx := r.Context()
  191. ctx = context.WithValue(ctx, types.UserScope, user)
  192. r = r.Clone(ctx)
  193. authn.next.ServeHTTP(w, r)
  194. }
  195. // sendForbiddenError sends a 403 Forbidden error to the end user while logging a
  196. // specific error
  197. func (authn *AuthN) sendForbiddenError(err error, w http.ResponseWriter, r *http.Request) {
  198. reqErr := apierrors.NewErrForbidden(err)
  199. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r, reqErr, true)
  200. }
  201. var (
  202. errInvalidToken = fmt.Errorf("authorization header exists, but token is not valid")
  203. errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
  204. )
  205. // getTokenFromRequest finds an `Authorization` header of the form `Bearer <token>`,
  206. // and returns a valid token if it exists.
  207. func (authn *AuthN) getTokenFromRequest(r *http.Request) (*token.Token, error) {
  208. reqToken := r.Header.Get("Authorization")
  209. splitToken := strings.Split(reqToken, "Bearer")
  210. if len(splitToken) != 2 {
  211. return nil, errInvalidAuthHeader
  212. }
  213. reqToken = strings.TrimSpace(splitToken[1])
  214. tok, err := token.GetTokenFromEncoded(reqToken, authn.config.TokenConf)
  215. if err != nil {
  216. return nil, fmt.Errorf("%s: %w", errInvalidToken.Error(), err)
  217. }
  218. return tok, nil
  219. }