auth.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. package middleware
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "github.com/google/go-github/github"
  13. "github.com/porter-dev/porter/internal/oauth"
  14. "golang.org/x/oauth2"
  15. "github.com/go-chi/chi"
  16. "github.com/gorilla/sessions"
  17. "github.com/porter-dev/porter/internal/auth/token"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/repository"
  20. )
  21. // Auth implements the authorization functions
  22. type Auth struct {
  23. store sessions.Store
  24. cookieName string
  25. tokenConf *token.TokenGeneratorConf
  26. repo *repository.Repository
  27. GithubAppConf *oauth2.Config
  28. }
  29. // NewAuth returns a new Auth instance
  30. func NewAuth(
  31. store sessions.Store,
  32. cookieName string,
  33. tokenConf *token.TokenGeneratorConf,
  34. repo *repository.Repository,
  35. GithubAppConf *oauth2.Config,
  36. ) *Auth {
  37. return &Auth{store, cookieName, tokenConf, repo, GithubAppConf}
  38. }
  39. // BasicAuthenticate just checks that a user is logged in
  40. func (auth *Auth) BasicAuthenticate(next http.Handler) http.Handler {
  41. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  42. if auth.isLoggedIn(w, r) {
  43. next.ServeHTTP(w, r)
  44. } else {
  45. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  46. return
  47. }
  48. return
  49. })
  50. }
  51. // BasicAuthenticateWithRedirect checks that a user is logged in, and if they're not, the
  52. // user is redirected to the login page with the redirect path stored in the session
  53. func (auth *Auth) BasicAuthenticateWithRedirect(next http.Handler) http.Handler {
  54. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  55. if auth.isLoggedIn(w, r) {
  56. next.ServeHTTP(w, r)
  57. } else {
  58. session, err := auth.store.Get(r, auth.cookieName)
  59. if err != nil {
  60. http.Redirect(w, r, "/dashboard", 302)
  61. }
  62. // need state parameter to validate when redirected
  63. if r.URL.RawQuery == "" {
  64. session.Values["redirect"] = r.URL.Path
  65. } else {
  66. session.Values["redirect"] = r.URL.Path + "?" + r.URL.RawQuery
  67. }
  68. session.Save(r, w)
  69. http.Redirect(w, r, "/dashboard", 302)
  70. return
  71. }
  72. return
  73. })
  74. }
  75. // IDLocation represents the location of the ID to use for authentication
  76. type IDLocation uint
  77. const (
  78. // URLParam location looks for a parameter in the URL endpoint
  79. URLParam IDLocation = iota
  80. // BodyParam location looks for a parameter in the body
  81. BodyParam
  82. // QueryParam location looks for a parameter in the query string
  83. QueryParam
  84. )
  85. type bodyUserID struct {
  86. UserID uint64 `json:"user_id"`
  87. }
  88. type bodyProjectID struct {
  89. ProjectID uint64 `json:"project_id"`
  90. }
  91. type bodyClusterID struct {
  92. ClusterID uint64 `json:"cluster_id"`
  93. }
  94. type bodyRegistryID struct {
  95. RegistryID uint64 `json:"registry_id"`
  96. }
  97. type bodyGitRepoID struct {
  98. GitRepoID uint64 `json:"git_repo_id"`
  99. }
  100. type bodyInfraID struct {
  101. InfraID uint64 `json:"infra_id"`
  102. }
  103. type bodyInviteID struct {
  104. InviteID uint64 `json:"invite_id"`
  105. }
  106. type bodyAWSIntegrationID struct {
  107. AWSIntegrationID uint64 `json:"aws_integration_id"`
  108. }
  109. type bodyGCPIntegrationID struct {
  110. GCPIntegrationID uint64 `json:"gcp_integration_id"`
  111. }
  112. type bodyDOIntegrationID struct {
  113. DOIntegrationID uint64 `json:"do_integration_id"`
  114. }
  115. // DoesUserIDMatch checks the id URL parameter and verifies that it matches
  116. // the one stored in the session
  117. func (auth *Auth) DoesUserIDMatch(next http.Handler, loc IDLocation) http.Handler {
  118. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  119. var err error
  120. id, err := findUserIDInRequest(r, loc)
  121. // first check for token
  122. tok := auth.getTokenFromRequest(r)
  123. if err != nil {
  124. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  125. return
  126. } else if tok != nil && tok.IBy == uint(id) {
  127. next.ServeHTTP(w, r)
  128. return
  129. } else if auth.doesSessionMatchID(r, uint(id)) {
  130. next.ServeHTTP(w, r)
  131. } else {
  132. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  133. return
  134. }
  135. return
  136. })
  137. }
  138. // AccessType represents the various access types for a project
  139. type AccessType string
  140. // The various access types
  141. const (
  142. AdminAccess AccessType = "admin"
  143. ReadAccess AccessType = "read"
  144. WriteAccess AccessType = "write"
  145. )
  146. // DoesUserHaveProjectAccess looks for a project_id parameter and checks that the
  147. // user has access via the specified accessType
  148. func (auth *Auth) DoesUserHaveProjectAccess(
  149. next http.Handler,
  150. projLoc IDLocation,
  151. accessType AccessType,
  152. ) http.Handler {
  153. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  154. var err error
  155. projID, err := findProjIDInRequest(r, projLoc)
  156. if err != nil {
  157. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  158. return
  159. }
  160. // first check for token
  161. tok := auth.getTokenFromRequest(r)
  162. var userID uint
  163. if tok != nil && tok.ProjectID != 0 && tok.ProjectID == uint(projID) {
  164. next.ServeHTTP(w, r)
  165. return
  166. } else if tok != nil {
  167. userID = tok.IBy
  168. } else {
  169. session, err := auth.store.Get(r, auth.cookieName)
  170. if err != nil {
  171. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  172. return
  173. }
  174. sessionUserID, ok := session.Values["user_id"]
  175. userID = sessionUserID.(uint)
  176. if !ok {
  177. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  178. return
  179. }
  180. }
  181. // read the user and make sure the email is verified
  182. user, err := auth.repo.User.ReadUser(userID)
  183. if err != nil || !user.EmailVerified {
  184. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  185. return
  186. }
  187. // get the project
  188. proj, err := auth.repo.Project.ReadProject(uint(projID))
  189. if err != nil {
  190. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  191. return
  192. }
  193. // look for the user role in the project
  194. for _, role := range proj.Roles {
  195. if role.UserID == userID {
  196. if accessType == AdminAccess {
  197. if role.Kind == models.RoleAdmin {
  198. next.ServeHTTP(w, r)
  199. return
  200. }
  201. } else if accessType == WriteAccess {
  202. if role.Kind == models.RoleAdmin || role.Kind == models.RoleDeveloper {
  203. next.ServeHTTP(w, r)
  204. return
  205. }
  206. } else if accessType == ReadAccess {
  207. next.ServeHTTP(w, r)
  208. return
  209. }
  210. }
  211. }
  212. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  213. return
  214. })
  215. }
  216. // DoesUserHaveClusterAccess looks for a project_id parameter and a
  217. // cluster_id parameter, and verifies that the cluster belongs
  218. // to the project
  219. func (auth *Auth) DoesUserHaveClusterAccess(
  220. next http.Handler,
  221. projLoc IDLocation,
  222. clusterLoc IDLocation,
  223. ) http.Handler {
  224. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  225. clusterID, err := findClusterIDInRequest(r, clusterLoc)
  226. if err != nil {
  227. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  228. return
  229. }
  230. projID, err := findProjIDInRequest(r, projLoc)
  231. if err != nil {
  232. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  233. return
  234. }
  235. // get the service accounts belonging to the project
  236. clusters, err := auth.repo.Cluster.ListClustersByProjectID(uint(projID))
  237. if err != nil {
  238. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  239. return
  240. }
  241. doesExist := false
  242. for _, cluster := range clusters {
  243. if cluster.ID == uint(clusterID) {
  244. doesExist = true
  245. break
  246. }
  247. }
  248. if doesExist {
  249. next.ServeHTTP(w, r)
  250. return
  251. }
  252. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  253. return
  254. })
  255. }
  256. // DoesUserHaveInviteAccess looks for a project_id parameter and a
  257. // invite_id parameter, and verifies that the invite belongs
  258. // to the project
  259. func (auth *Auth) DoesUserHaveInviteAccess(
  260. next http.Handler,
  261. projLoc IDLocation,
  262. inviteLoc IDLocation,
  263. ) http.Handler {
  264. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  265. inviteID, err := findInviteIDInRequest(r, inviteLoc)
  266. if err != nil {
  267. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  268. return
  269. }
  270. projID, err := findProjIDInRequest(r, projLoc)
  271. if err != nil {
  272. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  273. return
  274. }
  275. // get the service accounts belonging to the project
  276. invites, err := auth.repo.Invite.ListInvitesByProjectID(uint(projID))
  277. if err != nil {
  278. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  279. return
  280. }
  281. doesExist := false
  282. for _, invite := range invites {
  283. if invite.ID == uint(inviteID) {
  284. doesExist = true
  285. break
  286. }
  287. }
  288. if doesExist {
  289. next.ServeHTTP(w, r)
  290. return
  291. }
  292. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  293. return
  294. })
  295. }
  296. // DoesUserHaveRegistryAccess looks for a project_id parameter and a
  297. // registry_id parameter, and verifies that the registry belongs
  298. // to the project
  299. func (auth *Auth) DoesUserHaveRegistryAccess(
  300. next http.Handler,
  301. projLoc IDLocation,
  302. registryLoc IDLocation,
  303. ) http.Handler {
  304. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  305. regID, err := findRegistryIDInRequest(r, registryLoc)
  306. if err != nil {
  307. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  308. return
  309. }
  310. projID, err := findProjIDInRequest(r, projLoc)
  311. if err != nil {
  312. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  313. return
  314. }
  315. // get the service accounts belonging to the project
  316. regs, err := auth.repo.Registry.ListRegistriesByProjectID(uint(projID))
  317. if err != nil {
  318. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  319. return
  320. }
  321. doesExist := false
  322. for _, reg := range regs {
  323. if reg.ID == uint(regID) {
  324. doesExist = true
  325. break
  326. }
  327. }
  328. if doesExist {
  329. next.ServeHTTP(w, r)
  330. return
  331. }
  332. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  333. return
  334. })
  335. }
  336. // DoesUserHaveGitInstallationAccess checks that a user has access to an installation id
  337. // by ensuring the installation id exists for one org or account they have access to
  338. // note that this makes a github API request, but the endpoint is fast so this doesn't add
  339. // much overhead
  340. func (auth *Auth) DoesUserHaveGitInstallationAccess(
  341. next http.Handler,
  342. gitRepoLoc IDLocation,
  343. ) http.Handler {
  344. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  345. grID, err := findGitInstallationIDInRequest(r, gitRepoLoc)
  346. if err != nil {
  347. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  348. return
  349. }
  350. tok := auth.getTokenFromRequest(r)
  351. var userID uint
  352. if tok != nil {
  353. userID = tok.IBy
  354. } else {
  355. session, err := auth.store.Get(r, auth.cookieName)
  356. if err != nil {
  357. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  358. return
  359. }
  360. sessionUserID, ok := session.Values["user_id"]
  361. userID = sessionUserID.(uint)
  362. if !ok {
  363. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  364. return
  365. }
  366. }
  367. user, err := auth.repo.User.ReadUser(userID)
  368. if err != nil {
  369. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  370. return
  371. }
  372. oauthInt, err := auth.repo.GithubAppOAuthIntegration.ReadGithubAppOauthIntegration(user.GithubAppIntegrationID)
  373. if err != nil {
  374. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  375. return
  376. }
  377. _, _, err = oauth.GetAccessToken(oauthInt.SharedOAuthModel,
  378. auth.GithubAppConf,
  379. oauth.MakeUpdateGithubAppOauthIntegrationFunction(oauthInt, *auth.repo))
  380. if err != nil {
  381. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  382. return
  383. }
  384. client := github.NewClient(auth.GithubAppConf.Client(oauth2.NoContext, &oauth2.Token{
  385. AccessToken: string(oauthInt.AccessToken),
  386. RefreshToken: string(oauthInt.RefreshToken),
  387. TokenType: "Bearer",
  388. }))
  389. accountIDs := make([]int64, 0)
  390. AuthUser, _, err := client.Users.Get(context.Background(), "")
  391. if err != nil {
  392. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  393. return
  394. }
  395. accountIDs = append(accountIDs, *AuthUser.ID)
  396. opts := &github.ListOptions{
  397. PerPage: 100,
  398. Page: 1,
  399. }
  400. for {
  401. orgs, pages, err := client.Organizations.List(context.Background(), "", opts)
  402. if err != nil {
  403. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  404. return
  405. }
  406. for _, org := range orgs {
  407. accountIDs = append(accountIDs, *org.ID)
  408. }
  409. if pages.NextPage == 0 {
  410. break
  411. }
  412. }
  413. installations, err := auth.repo.GithubAppInstallation.ReadGithubAppInstallationByAccountIDs(accountIDs)
  414. for _, installation := range installations {
  415. if uint64(installation.InstallationID) == grID {
  416. next.ServeHTTP(w, r)
  417. return
  418. }
  419. }
  420. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  421. })
  422. }
  423. // DoesUserHaveInfraAccess looks for a project_id parameter and an
  424. // infra_id parameter, and verifies that the infra belongs
  425. // to the project
  426. func (auth *Auth) DoesUserHaveInfraAccess(
  427. next http.Handler,
  428. projLoc IDLocation,
  429. infraLoc IDLocation,
  430. ) http.Handler {
  431. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  432. infraID, err := findInfraIDInRequest(r, infraLoc)
  433. if err != nil {
  434. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  435. return
  436. }
  437. projID, err := findProjIDInRequest(r, projLoc)
  438. if err != nil {
  439. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  440. return
  441. }
  442. infras, err := auth.repo.Infra.ListInfrasByProjectID(uint(projID))
  443. if err != nil {
  444. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  445. return
  446. }
  447. doesExist := false
  448. for _, infra := range infras {
  449. if infra.ID == uint(infraID) {
  450. doesExist = true
  451. break
  452. }
  453. }
  454. if doesExist {
  455. next.ServeHTTP(w, r)
  456. return
  457. }
  458. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  459. return
  460. })
  461. }
  462. // DoesUserHaveAWSIntegrationAccess looks for a project_id parameter and an
  463. // aws_integration_id parameter, and verifies that the infra belongs
  464. // to the project
  465. func (auth *Auth) DoesUserHaveAWSIntegrationAccess(
  466. next http.Handler,
  467. projLoc IDLocation,
  468. awsLoc IDLocation,
  469. optional bool,
  470. ) http.Handler {
  471. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  472. awsID, err := findAWSIntegrationIDInRequest(r, awsLoc)
  473. if awsID == 0 && optional {
  474. next.ServeHTTP(w, r)
  475. return
  476. }
  477. if awsID == 0 || err != nil {
  478. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  479. return
  480. }
  481. projID, err := findProjIDInRequest(r, projLoc)
  482. if err != nil {
  483. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  484. return
  485. }
  486. awsInts, err := auth.repo.AWSIntegration.ListAWSIntegrationsByProjectID(uint(projID))
  487. if err != nil {
  488. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  489. return
  490. }
  491. doesExist := false
  492. for _, awsInt := range awsInts {
  493. if awsInt.ID == uint(awsID) {
  494. doesExist = true
  495. break
  496. }
  497. }
  498. if doesExist {
  499. next.ServeHTTP(w, r)
  500. return
  501. }
  502. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  503. return
  504. })
  505. }
  506. // DoesUserHaveGCPIntegrationAccess looks for a project_id parameter and an
  507. // gcp_integration_id parameter, and verifies that the infra belongs
  508. // to the project
  509. func (auth *Auth) DoesUserHaveGCPIntegrationAccess(
  510. next http.Handler,
  511. projLoc IDLocation,
  512. gcpLoc IDLocation,
  513. optional bool,
  514. ) http.Handler {
  515. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  516. gcpID, err := findGCPIntegrationIDInRequest(r, gcpLoc)
  517. if gcpID == 0 && optional {
  518. next.ServeHTTP(w, r)
  519. return
  520. }
  521. if gcpID == 0 || err != nil {
  522. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  523. return
  524. }
  525. projID, err := findProjIDInRequest(r, projLoc)
  526. if err != nil {
  527. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  528. return
  529. }
  530. gcpInts, err := auth.repo.GCPIntegration.ListGCPIntegrationsByProjectID(uint(projID))
  531. if err != nil {
  532. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  533. return
  534. }
  535. doesExist := false
  536. for _, awsInt := range gcpInts {
  537. if awsInt.ID == uint(gcpID) {
  538. doesExist = true
  539. break
  540. }
  541. }
  542. if doesExist {
  543. next.ServeHTTP(w, r)
  544. return
  545. }
  546. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  547. return
  548. })
  549. }
  550. // DoesUserHaveDOIntegrationAccess looks for a project_id parameter and an
  551. // do_integration_id parameter, and verifies that the infra belongs
  552. // to the project
  553. func (auth *Auth) DoesUserHaveDOIntegrationAccess(
  554. next http.Handler,
  555. projLoc IDLocation,
  556. doLoc IDLocation,
  557. optional bool,
  558. ) http.Handler {
  559. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  560. doID, err := findDOIntegrationIDInRequest(r, doLoc)
  561. if doID == 0 && optional {
  562. next.ServeHTTP(w, r)
  563. return
  564. }
  565. if doID == 0 || err != nil {
  566. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  567. return
  568. }
  569. projID, err := findProjIDInRequest(r, projLoc)
  570. if err != nil {
  571. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  572. return
  573. }
  574. oauthInts, err := auth.repo.OAuthIntegration.ListOAuthIntegrationsByProjectID(uint(projID))
  575. if err != nil {
  576. http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
  577. return
  578. }
  579. doesExist := false
  580. for _, oauthInt := range oauthInts {
  581. if oauthInt.ID == uint(doID) {
  582. doesExist = true
  583. break
  584. }
  585. }
  586. if doesExist {
  587. next.ServeHTTP(w, r)
  588. return
  589. }
  590. http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
  591. return
  592. })
  593. }
  594. // Helpers
  595. func (auth *Auth) doesSessionMatchID(r *http.Request, id uint) bool {
  596. session, _ := auth.store.Get(r, auth.cookieName)
  597. if sessID, ok := session.Values["user_id"].(uint); !ok || sessID != id {
  598. return false
  599. }
  600. return true
  601. }
  602. func (auth *Auth) isLoggedIn(w http.ResponseWriter, r *http.Request) bool {
  603. // first check for Bearer token
  604. tok := auth.getTokenFromRequest(r)
  605. if tok != nil {
  606. return true
  607. }
  608. session, err := auth.store.Get(r, auth.cookieName)
  609. if err != nil {
  610. session.Values["authenticated"] = false
  611. if err := session.Save(r, w); err != nil {
  612. return false
  613. }
  614. return false
  615. }
  616. if auth, ok := session.Values["authenticated"].(bool); !auth || !ok {
  617. return false
  618. }
  619. return true
  620. }
  621. func (auth *Auth) getTokenFromRequest(r *http.Request) *token.Token {
  622. reqToken := r.Header.Get("Authorization")
  623. splitToken := strings.Split(reqToken, "Bearer")
  624. if len(splitToken) != 2 {
  625. return nil
  626. }
  627. reqToken = strings.TrimSpace(splitToken[1])
  628. tok, err := token.GetTokenFromEncoded(reqToken, auth.tokenConf)
  629. if err != nil {
  630. return nil
  631. }
  632. return tok
  633. }
  634. func findUserIDInRequest(r *http.Request, userLoc IDLocation) (uint64, error) {
  635. var userID uint64
  636. var err error
  637. if userLoc == URLParam {
  638. userID, err = strconv.ParseUint(chi.URLParam(r, "user_id"), 0, 64)
  639. if err != nil {
  640. return 0, err
  641. }
  642. } else if userLoc == BodyParam {
  643. form := &bodyUserID{}
  644. body, err := ioutil.ReadAll(r.Body)
  645. if err != nil {
  646. return 0, err
  647. }
  648. err = json.Unmarshal(body, form)
  649. if err != nil {
  650. return 0, err
  651. }
  652. userID = form.UserID
  653. // need to create a new stream for the body
  654. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  655. } else {
  656. vals, err := url.ParseQuery(r.URL.RawQuery)
  657. if err != nil {
  658. return 0, err
  659. }
  660. if userStrArr, ok := vals["user_id"]; ok && len(userStrArr) == 1 {
  661. userID, err = strconv.ParseUint(userStrArr[0], 10, 64)
  662. } else {
  663. return 0, errors.New("user id not found")
  664. }
  665. }
  666. return userID, nil
  667. }
  668. func findProjIDInRequest(r *http.Request, projLoc IDLocation) (uint64, error) {
  669. var projID uint64
  670. var err error
  671. if projLoc == URLParam {
  672. projID, err = strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  673. if err != nil {
  674. return 0, err
  675. }
  676. } else if projLoc == BodyParam {
  677. form := &bodyProjectID{}
  678. body, err := ioutil.ReadAll(r.Body)
  679. if err != nil {
  680. return 0, err
  681. }
  682. err = json.Unmarshal(body, form)
  683. if err != nil {
  684. return 0, err
  685. }
  686. projID = form.ProjectID
  687. // need to create a new stream for the body
  688. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  689. } else {
  690. vals, err := url.ParseQuery(r.URL.RawQuery)
  691. if err != nil {
  692. return 0, err
  693. }
  694. if projStrArr, ok := vals["project_id"]; ok && len(projStrArr) == 1 {
  695. projID, err = strconv.ParseUint(projStrArr[0], 10, 64)
  696. } else {
  697. return 0, errors.New("project id not found")
  698. }
  699. }
  700. return projID, nil
  701. }
  702. func findClusterIDInRequest(r *http.Request, clusterLoc IDLocation) (uint64, error) {
  703. var clusterID uint64
  704. var err error
  705. if clusterLoc == URLParam {
  706. clusterID, err = strconv.ParseUint(chi.URLParam(r, "cluster_id"), 0, 64)
  707. if err != nil {
  708. return 0, err
  709. }
  710. } else if clusterLoc == BodyParam {
  711. form := &bodyClusterID{}
  712. body, err := ioutil.ReadAll(r.Body)
  713. if err != nil {
  714. return 0, err
  715. }
  716. err = json.Unmarshal(body, form)
  717. if err != nil {
  718. return 0, err
  719. }
  720. clusterID = form.ClusterID
  721. // need to create a new stream for the body
  722. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  723. } else {
  724. vals, err := url.ParseQuery(r.URL.RawQuery)
  725. if err != nil {
  726. return 0, err
  727. }
  728. if clStrArr, ok := vals["cluster_id"]; ok && len(clStrArr) == 1 {
  729. clusterID, err = strconv.ParseUint(clStrArr[0], 10, 64)
  730. } else {
  731. return 0, errors.New("cluster id not found")
  732. }
  733. }
  734. return clusterID, nil
  735. }
  736. func findInviteIDInRequest(r *http.Request, inviteLoc IDLocation) (uint64, error) {
  737. var inviteID uint64
  738. var err error
  739. if inviteLoc == URLParam {
  740. inviteID, err = strconv.ParseUint(chi.URLParam(r, "invite_id"), 0, 64)
  741. if err != nil {
  742. return 0, err
  743. }
  744. } else if inviteLoc == BodyParam {
  745. form := &bodyInviteID{}
  746. body, err := ioutil.ReadAll(r.Body)
  747. if err != nil {
  748. return 0, err
  749. }
  750. err = json.Unmarshal(body, form)
  751. if err != nil {
  752. return 0, err
  753. }
  754. inviteID = form.InviteID
  755. // need to create a new stream for the body
  756. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  757. } else {
  758. vals, err := url.ParseQuery(r.URL.RawQuery)
  759. if err != nil {
  760. return 0, err
  761. }
  762. if invStrArr, ok := vals["invite_id"]; ok && len(invStrArr) == 1 {
  763. inviteID, err = strconv.ParseUint(invStrArr[0], 10, 64)
  764. } else {
  765. return 0, errors.New("invite id not found")
  766. }
  767. }
  768. return inviteID, nil
  769. }
  770. func findRegistryIDInRequest(r *http.Request, registryLoc IDLocation) (uint64, error) {
  771. var regID uint64
  772. var err error
  773. if registryLoc == URLParam {
  774. regID, err = strconv.ParseUint(chi.URLParam(r, "registry_id"), 0, 64)
  775. if err != nil {
  776. return 0, err
  777. }
  778. } else if registryLoc == BodyParam {
  779. form := &bodyRegistryID{}
  780. body, err := ioutil.ReadAll(r.Body)
  781. if err != nil {
  782. return 0, err
  783. }
  784. err = json.Unmarshal(body, form)
  785. if err != nil {
  786. return 0, err
  787. }
  788. regID = form.RegistryID
  789. // need to create a new stream for the body
  790. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  791. } else {
  792. vals, err := url.ParseQuery(r.URL.RawQuery)
  793. if err != nil {
  794. return 0, err
  795. }
  796. if regStrArr, ok := vals["registry_id"]; ok && len(regStrArr) == 1 {
  797. regID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  798. } else {
  799. return 0, errors.New("registry id not found")
  800. }
  801. }
  802. return regID, nil
  803. }
  804. // findGitInstallationIDInRequest extracts and installation ID from a request
  805. func findGitInstallationIDInRequest(r *http.Request, gitRepoLoc IDLocation) (uint64, error) {
  806. var grID uint64
  807. var err error
  808. if gitRepoLoc == URLParam {
  809. grID, err = strconv.ParseUint(chi.URLParam(r, "installation_id"), 0, 64)
  810. if err != nil {
  811. return 0, err
  812. }
  813. } else if gitRepoLoc == BodyParam {
  814. form := &bodyGitRepoID{}
  815. body, err := ioutil.ReadAll(r.Body)
  816. if err != nil {
  817. return 0, err
  818. }
  819. err = json.Unmarshal(body, form)
  820. if err != nil {
  821. return 0, err
  822. }
  823. grID = form.GitRepoID
  824. // need to create a new stream for the body
  825. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  826. } else {
  827. vals, err := url.ParseQuery(r.URL.RawQuery)
  828. if err != nil {
  829. return 0, err
  830. }
  831. if regStrArr, ok := vals["installation_id"]; ok && len(regStrArr) == 1 {
  832. grID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  833. } else {
  834. return 0, errors.New("git app installation id not found")
  835. }
  836. }
  837. return grID, nil
  838. }
  839. func findInfraIDInRequest(r *http.Request, infraLoc IDLocation) (uint64, error) {
  840. var infraID uint64
  841. var err error
  842. if infraLoc == URLParam {
  843. infraID, err = strconv.ParseUint(chi.URLParam(r, "infra_id"), 0, 64)
  844. if err != nil {
  845. return 0, err
  846. }
  847. } else if infraLoc == BodyParam {
  848. form := &bodyInfraID{}
  849. body, err := ioutil.ReadAll(r.Body)
  850. if err != nil {
  851. return 0, err
  852. }
  853. err = json.Unmarshal(body, form)
  854. if err != nil {
  855. return 0, err
  856. }
  857. infraID = form.InfraID
  858. // need to create a new stream for the body
  859. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  860. } else {
  861. vals, err := url.ParseQuery(r.URL.RawQuery)
  862. if err != nil {
  863. return 0, err
  864. }
  865. if regStrArr, ok := vals["infra_id"]; ok && len(regStrArr) == 1 {
  866. infraID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  867. } else {
  868. return 0, errors.New("infra id not found")
  869. }
  870. }
  871. return infraID, nil
  872. }
  873. func findAWSIntegrationIDInRequest(r *http.Request, awsLoc IDLocation) (uint64, error) {
  874. var awsID uint64
  875. var err error
  876. if awsLoc == URLParam {
  877. awsID, err = strconv.ParseUint(chi.URLParam(r, "aws_integration_id"), 0, 64)
  878. if err != nil {
  879. return 0, err
  880. }
  881. } else if awsLoc == BodyParam {
  882. form := &bodyAWSIntegrationID{}
  883. body, err := ioutil.ReadAll(r.Body)
  884. if err != nil {
  885. return 0, err
  886. }
  887. err = json.Unmarshal(body, form)
  888. if err != nil {
  889. return 0, err
  890. }
  891. awsID = form.AWSIntegrationID
  892. // need to create a new stream for the body
  893. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  894. } else {
  895. vals, err := url.ParseQuery(r.URL.RawQuery)
  896. if err != nil {
  897. return 0, err
  898. }
  899. if regStrArr, ok := vals["aws_integration_id"]; ok && len(regStrArr) == 1 {
  900. awsID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  901. } else {
  902. return 0, errors.New("aws integration id not found")
  903. }
  904. }
  905. return awsID, nil
  906. }
  907. func findGCPIntegrationIDInRequest(r *http.Request, gcpLoc IDLocation) (uint64, error) {
  908. var gcpID uint64
  909. var err error
  910. if gcpLoc == URLParam {
  911. gcpID, err = strconv.ParseUint(chi.URLParam(r, "gcp_integration_id"), 0, 64)
  912. if err != nil {
  913. return 0, err
  914. }
  915. } else if gcpLoc == BodyParam {
  916. form := &bodyGCPIntegrationID{}
  917. body, err := ioutil.ReadAll(r.Body)
  918. if err != nil {
  919. return 0, err
  920. }
  921. err = json.Unmarshal(body, form)
  922. if err != nil {
  923. return 0, err
  924. }
  925. gcpID = form.GCPIntegrationID
  926. // need to create a new stream for the body
  927. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  928. } else {
  929. vals, err := url.ParseQuery(r.URL.RawQuery)
  930. if err != nil {
  931. return 0, err
  932. }
  933. if regStrArr, ok := vals["gcp_integration_id"]; ok && len(regStrArr) == 1 {
  934. gcpID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  935. } else {
  936. return 0, errors.New("gcp integration id not found")
  937. }
  938. }
  939. return gcpID, nil
  940. }
  941. func findDOIntegrationIDInRequest(r *http.Request, doLoc IDLocation) (uint64, error) {
  942. var doID uint64
  943. var err error
  944. if doLoc == URLParam {
  945. doID, err = strconv.ParseUint(chi.URLParam(r, "do_integration_id"), 0, 64)
  946. if err != nil {
  947. return 0, err
  948. }
  949. } else if doLoc == BodyParam {
  950. form := &bodyDOIntegrationID{}
  951. body, err := ioutil.ReadAll(r.Body)
  952. if err != nil {
  953. return 0, err
  954. }
  955. err = json.Unmarshal(body, form)
  956. if err != nil {
  957. return 0, err
  958. }
  959. doID = form.DOIntegrationID
  960. // need to create a new stream for the body
  961. r.Body = ioutil.NopCloser(bytes.NewReader(body))
  962. } else {
  963. vals, err := url.ParseQuery(r.URL.RawQuery)
  964. if err != nil {
  965. return 0, err
  966. }
  967. if regStrArr, ok := vals["do_integration_id"]; ok && len(regStrArr) == 1 {
  968. doID, err = strconv.ParseUint(regStrArr[0], 10, 64)
  969. } else {
  970. return 0, errors.New("do integration id not found")
  971. }
  972. }
  973. return doID, nil
  974. }