get_token.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package registry
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/aws/aws-sdk-go/service/ecr"
  9. "github.com/bufbuild/connect-go"
  10. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  11. "github.com/porter-dev/porter/api/server/handlers"
  12. "github.com/porter-dev/porter/api/server/shared"
  13. "github.com/porter-dev/porter/api/server/shared/apierrors"
  14. "github.com/porter-dev/porter/api/server/shared/config"
  15. "github.com/porter-dev/porter/api/types"
  16. "github.com/porter-dev/porter/internal/models"
  17. "github.com/porter-dev/porter/internal/oauth"
  18. "github.com/porter-dev/porter/internal/registry"
  19. "github.com/aws/aws-sdk-go/aws/arn"
  20. )
  21. type RegistryGetECRTokenHandler struct {
  22. handlers.PorterHandlerReadWriter
  23. }
  24. func NewRegistryGetECRTokenHandler(
  25. config *config.Config,
  26. decoderValidator shared.RequestDecoderValidator,
  27. writer shared.ResultWriter,
  28. ) *RegistryGetECRTokenHandler {
  29. return &RegistryGetECRTokenHandler{
  30. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  31. }
  32. }
  33. func (c *RegistryGetECRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  34. ctx := r.Context()
  35. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  36. request := &types.GetRegistryECRTokenRequest{}
  37. if ok := c.DecodeAndValidate(w, r, request); !ok {
  38. return
  39. }
  40. if proj.CapiProvisionerEnabled {
  41. ecrRequest := porterv1.ECRTokenForRegistryRequest{
  42. ProjectId: int64(proj.ID),
  43. Region: request.Region,
  44. AwsAccountId: request.AccountID,
  45. }
  46. ecrResponse, err := c.Config().ClusterControlPlaneClient.ECRTokenForRegistry(ctx, connect.NewRequest(&ecrRequest))
  47. if err != nil {
  48. e := fmt.Errorf("error getting ecr token for capi cluster: %v", err)
  49. c.HandleAPIError(w, r, apierrors.NewErrInternal(e))
  50. return
  51. }
  52. if ecrResponse.Msg == nil {
  53. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("nil message received for ecr token")))
  54. return
  55. }
  56. expiry := ecrResponse.Msg.Expiry.AsTime()
  57. resp := &types.GetRegistryTokenResponse{
  58. Token: ecrResponse.Msg.Token,
  59. ExpiresAt: &expiry,
  60. }
  61. c.WriteResult(w, r, resp)
  62. return
  63. }
  64. // list registries and find one that matches the region
  65. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  66. if err != nil {
  67. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  68. return
  69. }
  70. var token string
  71. var expiresAt *time.Time
  72. for _, reg := range regs {
  73. if reg.AWSIntegrationID != 0 {
  74. awsInt, err := c.Repo().AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  75. if err != nil {
  76. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  77. return
  78. }
  79. // if the aws integration doesn't have an ARN populated, populate it
  80. if awsInt.AWSArn == "" {
  81. err = awsInt.PopulateAWSArn()
  82. if err != nil {
  83. continue
  84. }
  85. }
  86. parsedARN, err := arn.Parse(awsInt.AWSArn)
  87. if err != nil {
  88. continue
  89. }
  90. // if the account id is passed as part of the request, verify the account id matches the account id in the ARN
  91. if awsInt.AWSRegion == request.Region && (request.AccountID == "" || request.AccountID == parsedARN.AccountID) {
  92. // get the aws integration and session
  93. sess, err := awsInt.GetSession()
  94. if err != nil {
  95. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  96. return
  97. }
  98. ecrSvc := ecr.New(sess)
  99. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  100. if err != nil {
  101. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  102. return
  103. }
  104. token = *output.AuthorizationData[0].AuthorizationToken
  105. expiresAt = output.AuthorizationData[0].ExpiresAt
  106. }
  107. }
  108. }
  109. resp := &types.GetRegistryTokenResponse{
  110. Token: token,
  111. ExpiresAt: expiresAt,
  112. }
  113. c.WriteResult(w, r, resp)
  114. }
  115. type RegistryGetGCRTokenHandler struct {
  116. handlers.PorterHandlerReadWriter
  117. }
  118. func NewRegistryGetGCRTokenHandler(
  119. config *config.Config,
  120. decoderValidator shared.RequestDecoderValidator,
  121. writer shared.ResultWriter,
  122. ) *RegistryGetGCRTokenHandler {
  123. return &RegistryGetGCRTokenHandler{
  124. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  125. }
  126. }
  127. func (c *RegistryGetGCRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  128. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  129. request := &types.GetRegistryGCRTokenRequest{}
  130. if ok := c.DecodeAndValidate(w, r, request); !ok {
  131. return
  132. }
  133. // list registries and find one that matches the region
  134. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  135. if err != nil {
  136. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  137. return
  138. }
  139. var token string
  140. var expiresAt *time.Time
  141. for _, reg := range regs {
  142. if reg.GCPIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  143. _reg := registry.Registry(*reg)
  144. oauthTok, err := _reg.GetGCRToken(c.Repo())
  145. // if the oauth token is not nil, but the error is not nil, we still return the token
  146. // but log an error
  147. if oauthTok != nil && err != nil {
  148. c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
  149. } else if err != nil {
  150. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  151. return
  152. }
  153. token = oauthTok.AccessToken
  154. expiresAt = &oauthTok.Expiry
  155. break
  156. }
  157. }
  158. resp := &types.GetRegistryTokenResponse{
  159. Token: token,
  160. ExpiresAt: expiresAt,
  161. }
  162. c.WriteResult(w, r, resp)
  163. }
  164. type RegistryGetGARTokenHandler struct {
  165. handlers.PorterHandlerReadWriter
  166. }
  167. func NewRegistryGetGARTokenHandler(
  168. config *config.Config,
  169. decoderValidator shared.RequestDecoderValidator,
  170. writer shared.ResultWriter,
  171. ) *RegistryGetGARTokenHandler {
  172. return &RegistryGetGARTokenHandler{
  173. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  174. }
  175. }
  176. func (c *RegistryGetGARTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  177. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  178. request := &types.GetRegistryGCRTokenRequest{}
  179. if ok := c.DecodeAndValidate(w, r, request); !ok {
  180. return
  181. }
  182. // list registries and find one that matches the region
  183. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  184. if err != nil {
  185. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  186. return
  187. }
  188. var token string
  189. var expiresAt *time.Time
  190. for _, reg := range regs {
  191. if reg.GCPIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  192. _reg := registry.Registry(*reg)
  193. oauthTok, err := _reg.GetGARToken(c.Repo())
  194. // if the oauth token is not nil, but the error is not nil, we still return the token
  195. // but log an error
  196. if oauthTok != nil && err != nil {
  197. c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(err))
  198. } else if err != nil {
  199. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  200. return
  201. }
  202. token = oauthTok.AccessToken
  203. expiresAt = &oauthTok.Expiry
  204. break
  205. }
  206. }
  207. resp := &types.GetRegistryTokenResponse{
  208. Token: token,
  209. ExpiresAt: expiresAt,
  210. }
  211. c.WriteResult(w, r, resp)
  212. }
  213. type RegistryGetDOCRTokenHandler struct {
  214. handlers.PorterHandlerReadWriter
  215. }
  216. func NewRegistryGetDOCRTokenHandler(
  217. config *config.Config,
  218. decoderValidator shared.RequestDecoderValidator,
  219. writer shared.ResultWriter,
  220. ) *RegistryGetDOCRTokenHandler {
  221. return &RegistryGetDOCRTokenHandler{
  222. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  223. }
  224. }
  225. func (c *RegistryGetDOCRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  226. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  227. request := &types.GetRegistryDOCRTokenRequest{}
  228. if ok := c.DecodeAndValidate(w, r, request); !ok {
  229. return
  230. }
  231. // list registries and find one that matches the region
  232. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  233. if err != nil {
  234. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  235. return
  236. }
  237. var token string
  238. var expiresAt *time.Time
  239. for _, reg := range regs {
  240. if reg.DOIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  241. oauthInt, err := c.Repo().OAuthIntegration().ReadOAuthIntegration(reg.ProjectID, reg.DOIntegrationID)
  242. if err != nil {
  243. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  244. return
  245. }
  246. tok, expiry, err := oauth.GetAccessToken(
  247. oauthInt.SharedOAuthModel,
  248. c.Config().DOConf,
  249. oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, c.Repo()),
  250. )
  251. if err != nil {
  252. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  253. return
  254. }
  255. token = tok
  256. expiresAt = expiry
  257. break
  258. }
  259. }
  260. resp := &types.GetRegistryTokenResponse{
  261. Token: token,
  262. ExpiresAt: expiresAt,
  263. }
  264. c.WriteResult(w, r, resp)
  265. }
  266. type RegistryGetDockerhubTokenHandler struct {
  267. handlers.PorterHandlerReadWriter
  268. }
  269. func NewRegistryGetDockerhubTokenHandler(
  270. config *config.Config,
  271. decoderValidator shared.RequestDecoderValidator,
  272. writer shared.ResultWriter,
  273. ) *RegistryGetDockerhubTokenHandler {
  274. return &RegistryGetDockerhubTokenHandler{
  275. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  276. }
  277. }
  278. func (c *RegistryGetDockerhubTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  279. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  280. // list registries and find one that matches the region
  281. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  282. if err != nil {
  283. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  284. return
  285. }
  286. var token string
  287. var expiresAt *time.Time
  288. for _, reg := range regs {
  289. if reg.BasicIntegrationID != 0 && strings.Contains(reg.URL, "index.docker.io") {
  290. basic, err := c.Repo().BasicIntegration().ReadBasicIntegration(reg.ProjectID, reg.BasicIntegrationID)
  291. if err != nil {
  292. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  293. return
  294. }
  295. token = base64.StdEncoding.EncodeToString([]byte(string(basic.Username) + ":" + string(basic.Password)))
  296. // we'll just set an arbitrary 30-day expiry time (this is not enforced)
  297. timeExpires := time.Now().Add(30 * 24 * 3600 * time.Second)
  298. expiresAt = &timeExpires
  299. }
  300. }
  301. resp := &types.GetRegistryTokenResponse{
  302. Token: token,
  303. ExpiresAt: expiresAt,
  304. }
  305. c.WriteResult(w, r, resp)
  306. }
  307. type RegistryGetACRTokenHandler struct {
  308. handlers.PorterHandlerReadWriter
  309. }
  310. func NewRegistryGetACRTokenHandler(
  311. config *config.Config,
  312. decoderValidator shared.RequestDecoderValidator,
  313. writer shared.ResultWriter,
  314. ) *RegistryGetACRTokenHandler {
  315. return &RegistryGetACRTokenHandler{
  316. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  317. }
  318. }
  319. func (c *RegistryGetACRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  320. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  321. // list registries and find one that matches the region
  322. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  323. if err != nil {
  324. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  325. return
  326. }
  327. var token string
  328. var expiresAt *time.Time
  329. for _, reg := range regs {
  330. if reg.AzureIntegrationID != 0 && strings.Contains(reg.URL, "azurecr.io") {
  331. _reg := registry.Registry(*reg)
  332. username, pw, err := _reg.GetACRCredentials(c.Repo())
  333. if err != nil {
  334. continue
  335. }
  336. token = base64.StdEncoding.EncodeToString([]byte(string(username) + ":" + string(pw)))
  337. // we'll just set an arbitrary 30-day expiry time (this is not enforced)
  338. timeExpires := time.Now().Add(30 * 24 * 3600 * time.Second)
  339. expiresAt = &timeExpires
  340. }
  341. }
  342. resp := &types.GetRegistryTokenResponse{
  343. Token: token,
  344. ExpiresAt: expiresAt,
  345. }
  346. c.WriteResult(w, r, resp)
  347. }