handler.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package authn
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "strings"
  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. // first look for new ory cookie
  64. // set the cookies on the ory client
  65. var cookies string
  66. // this example passes all request.Cookies
  67. // to `ToSession` function
  68. //
  69. // However, you can pass only the value of
  70. // ory_session_projectid cookie to the endpoint
  71. cookies = r.Header.Get("Cookie")
  72. fmt.Println("Cookies: ", cookies)
  73. // check if we have a session
  74. orySession, _, err := authn.config.Ory.FrontendAPI.ToSession(r.Context()).Cookie(cookies).Execute()
  75. if err != nil {
  76. authn.sendForbiddenError(err, w, r)
  77. return
  78. }
  79. if orySession == nil {
  80. err = errors.New("ory session is nil")
  81. authn.sendForbiddenError(err, w, r)
  82. return
  83. }
  84. if !*orySession.Active {
  85. err = errors.New("ory session is not active")
  86. authn.sendForbiddenError(err, w, r)
  87. return
  88. }
  89. if orySession.Identity == nil {
  90. err = errors.New("ory session identity is nil")
  91. authn.sendForbiddenError(err, w, r)
  92. return
  93. }
  94. fmt.Println("now in here")
  95. // get user id from Ory
  96. externalId := orySession.Identity.Id
  97. user, err := authn.config.Repo.User().ReadUserByAuthProvider("ory", externalId)
  98. if err != nil || user == nil {
  99. err := fmt.Errorf("ory user not found in database", externalId)
  100. authn.sendForbiddenError(err, w, r)
  101. return
  102. }
  103. fmt.Println("going next")
  104. authn.nextWithUserID(w, r, user.ID)
  105. return
  106. }
  107. func (authn *AuthN) handleForbiddenForSession(
  108. w http.ResponseWriter,
  109. r *http.Request,
  110. err error,
  111. session *sessions.Session,
  112. ) {
  113. if authn.redirect {
  114. // need state parameter to validate when redirected
  115. if r.URL.RawQuery == "" {
  116. session.Values["redirect_uri"] = r.URL.Path
  117. } else {
  118. session.Values["redirect_uri"] = r.URL.Path + "?" + r.URL.RawQuery
  119. }
  120. session.Save(r, w)
  121. // special logic for GET /api/projects/{project_id}/invites/{token}
  122. if r.Method == "GET" && strings.Contains(r.URL.Path, "/invites/") &&
  123. !strings.HasSuffix(r.URL.Path, "/invites/") {
  124. pathSegments := strings.Split(r.URL.Path, "/")
  125. inviteToken := pathSegments[len(pathSegments)-1]
  126. invite, err := authn.config.Repo.Invite().ReadInviteByToken(inviteToken)
  127. if err != nil || invite.ProjectID == 0 || invite.Email == "" {
  128. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  129. apierrors.NewErrPassThroughToClient(fmt.Errorf("invalid invite token"), http.StatusBadRequest), true)
  130. return
  131. }
  132. if invite.IsExpired() || invite.IsAccepted() {
  133. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r,
  134. apierrors.NewErrPassThroughToClient(fmt.Errorf("invite has expired"), http.StatusBadRequest), true)
  135. return
  136. }
  137. http.Redirect(w, r, "/register?email="+url.QueryEscape(invite.Email), http.StatusTemporaryRedirect)
  138. return
  139. }
  140. http.Redirect(w, r, "/dashboard", http.StatusFound)
  141. } else {
  142. authn.sendForbiddenError(err, w, r)
  143. }
  144. }
  145. func (authn *AuthN) verifyTokenWithNext(w http.ResponseWriter, r *http.Request, tok *token.Token) {
  146. // if the token has a stored token id we check that the token is valid in the database
  147. if tok.TokenID != "" {
  148. apiToken, err := authn.config.Repo.APIToken().ReadAPIToken(tok.ProjectID, tok.TokenID)
  149. if err != nil {
  150. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  151. return
  152. }
  153. // first ensure that the token hasn't been revoked, and the token has not expired
  154. if apiToken.Revoked || apiToken.IsExpired() {
  155. authn.sendForbiddenError(fmt.Errorf("token with id %s not valid", tok.TokenID), w, r)
  156. return
  157. }
  158. authn.nextWithAPIToken(w, r, apiToken)
  159. } else {
  160. // otherwise we just use nextWithUser using the `iby` field for the token
  161. authn.nextWithUserID(w, r, tok.IBy)
  162. }
  163. }
  164. // nextWithAPIToken sets the token in context
  165. func (authn *AuthN) nextWithAPIToken(w http.ResponseWriter, r *http.Request, tok *models.APIToken) {
  166. ctx := r.Context()
  167. ctx = context.WithValue(ctx, "api_token", tok)
  168. // add a service account user to the project: note that any calls depending on a DB lookup for the
  169. // user will fail
  170. ctx = context.WithValue(ctx, types.UserScope, &models.User{
  171. Email: fmt.Sprintf("%s-%d", tok.Name, tok.ProjectID),
  172. EmailVerified: true,
  173. })
  174. r = r.Clone(ctx)
  175. authn.next.ServeHTTP(w, r)
  176. }
  177. // nextWithUserID calls the next handler with the user set in the context with key
  178. // `types.UserScope`.
  179. func (authn *AuthN) nextWithUserID(w http.ResponseWriter, r *http.Request, userID uint) {
  180. // search for the user
  181. user, err := authn.config.Repo.User().ReadUser(userID)
  182. if err != nil {
  183. authn.sendForbiddenError(fmt.Errorf("user with id %d not found in database", userID), w, r)
  184. return
  185. }
  186. // add the user to the context
  187. ctx := r.Context()
  188. ctx = context.WithValue(ctx, types.UserScope, user)
  189. r = r.Clone(ctx)
  190. authn.next.ServeHTTP(w, r)
  191. }
  192. // sendForbiddenError sends a 403 Forbidden error to the end user while logging a
  193. // specific error
  194. func (authn *AuthN) sendForbiddenError(err error, w http.ResponseWriter, r *http.Request) {
  195. reqErr := apierrors.NewErrForbidden(err)
  196. apierrors.HandleAPIError(authn.config.Logger, authn.config.Alerter, w, r, reqErr, true)
  197. }
  198. var (
  199. errInvalidToken = fmt.Errorf("authorization header exists, but token is not valid")
  200. errInvalidAuthHeader = fmt.Errorf("invalid authorization header in request")
  201. )
  202. // getTokenFromRequest finds an `Authorization` header of the form `Bearer <token>`,
  203. // and returns a valid token if it exists.
  204. func (authn *AuthN) getTokenFromRequest(r *http.Request) (*token.Token, error) {
  205. reqToken := r.Header.Get("Authorization")
  206. splitToken := strings.Split(reqToken, "Bearer")
  207. if len(splitToken) != 2 {
  208. return nil, errInvalidAuthHeader
  209. }
  210. reqToken = strings.TrimSpace(splitToken[1])
  211. tok, err := token.GetTokenFromEncoded(reqToken, authn.config.TokenConf)
  212. if err != nil {
  213. return nil, fmt.Errorf("%s: %w", errInvalidToken.Error(), err)
  214. }
  215. return tok, nil
  216. }