auth.go 28 KB

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