auth.go 28 KB

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