get_token.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. package registry
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/porter-dev/porter/internal/telemetry"
  9. "connectrpc.com/connect"
  10. "github.com/aws/aws-sdk-go/aws/arn"
  11. "github.com/aws/aws-sdk-go/service/ecr"
  12. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  13. "github.com/porter-dev/porter/api/server/handlers"
  14. "github.com/porter-dev/porter/api/server/shared"
  15. "github.com/porter-dev/porter/api/server/shared/apierrors"
  16. "github.com/porter-dev/porter/api/server/shared/config"
  17. "github.com/porter-dev/porter/api/types"
  18. "github.com/porter-dev/porter/internal/models"
  19. "github.com/porter-dev/porter/internal/oauth"
  20. "github.com/porter-dev/porter/internal/registry"
  21. )
  22. type RegistryGetECRTokenHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. }
  25. func NewRegistryGetECRTokenHandler(
  26. config *config.Config,
  27. decoderValidator shared.RequestDecoderValidator,
  28. writer shared.ResultWriter,
  29. ) *RegistryGetECRTokenHandler {
  30. return &RegistryGetECRTokenHandler{
  31. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  32. }
  33. }
  34. func (c *RegistryGetECRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  35. ctx := r.Context()
  36. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  37. request := &types.GetRegistryECRTokenRequest{}
  38. if ok := c.DecodeAndValidate(w, r, request); !ok {
  39. return
  40. }
  41. if proj.GetFeatureFlag(models.CapiProvisionerEnabled, c.Config().LaunchDarklyClient) {
  42. ecrRequest := porterv1.ECRTokenForRegistryRequest{
  43. ProjectId: int64(proj.ID),
  44. Region: request.Region,
  45. AwsAccountId: request.AccountID,
  46. }
  47. ecrResponse, err := c.Config().ClusterControlPlaneClient.ECRTokenForRegistry(ctx, connect.NewRequest(&ecrRequest))
  48. if err != nil {
  49. e := fmt.Errorf("error getting ecr token for capi cluster: %v", err)
  50. c.HandleAPIError(w, r, apierrors.NewErrInternal(e))
  51. return
  52. }
  53. if ecrResponse.Msg == nil {
  54. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("nil message received for ecr token")))
  55. return
  56. }
  57. expiry := ecrResponse.Msg.Expiry.AsTime()
  58. resp := &types.GetRegistryTokenResponse{
  59. Token: ecrResponse.Msg.Token,
  60. ExpiresAt: expiry,
  61. }
  62. c.WriteResult(w, r, resp)
  63. return
  64. }
  65. // list registries and find one that matches the region
  66. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  67. if err != nil {
  68. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  69. return
  70. }
  71. var token string
  72. var expiresAt time.Time
  73. for _, reg := range regs {
  74. if reg.AWSIntegrationID != 0 {
  75. awsInt, err := c.Repo().AWSIntegration().ReadAWSIntegration(reg.ProjectID, reg.AWSIntegrationID)
  76. if err != nil {
  77. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  78. return
  79. }
  80. // if the aws integration doesn't have an ARN populated, populate it
  81. if awsInt.AWSArn == "" {
  82. err = awsInt.PopulateAWSArn()
  83. if err != nil {
  84. continue
  85. }
  86. }
  87. parsedARN, err := arn.Parse(awsInt.AWSArn)
  88. if err != nil {
  89. continue
  90. }
  91. // if the account id is passed as part of the request, verify the account id matches the account id in the ARN
  92. if awsInt.AWSRegion == request.Region && (request.AccountID == "" || request.AccountID == parsedARN.AccountID) {
  93. // get the aws integration and session
  94. sess, err := awsInt.GetSession()
  95. if err != nil {
  96. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  97. return
  98. }
  99. ecrSvc := ecr.New(sess)
  100. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  101. if err != nil {
  102. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  103. return
  104. }
  105. if output == nil || output.AuthorizationData == nil || len(output.AuthorizationData) == 0 {
  106. continue
  107. }
  108. token = *output.AuthorizationData[0].AuthorizationToken
  109. expiresAt = *output.AuthorizationData[0].ExpiresAt
  110. }
  111. }
  112. }
  113. resp := &types.GetRegistryTokenResponse{
  114. Token: token,
  115. ExpiresAt: expiresAt,
  116. }
  117. c.WriteResult(w, r, resp)
  118. }
  119. type RegistryGetGCRTokenHandler struct {
  120. handlers.PorterHandlerReadWriter
  121. }
  122. func NewRegistryGetGCRTokenHandler(
  123. config *config.Config,
  124. decoderValidator shared.RequestDecoderValidator,
  125. writer shared.ResultWriter,
  126. ) *RegistryGetGCRTokenHandler {
  127. return &RegistryGetGCRTokenHandler{
  128. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  129. }
  130. }
  131. func (c *RegistryGetGCRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  132. ctx, span := telemetry.NewSpan(r.Context(), "serve-registry-get-gcr-token")
  133. defer span.End()
  134. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  135. request := &types.GetRegistryGCRTokenRequest{}
  136. if ok := c.DecodeAndValidate(w, r, request); !ok {
  137. return
  138. }
  139. // list registries and find one that matches the region
  140. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  141. if err != nil {
  142. e := telemetry.Error(ctx, span, err, "error listing registries by project id")
  143. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  144. return
  145. }
  146. var token string
  147. var expiresAt time.Time
  148. for _, reg := range regs {
  149. if reg.GCPIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  150. _reg := registry.Registry(*reg)
  151. oauthTok, err := _reg.GetGCRToken(ctx, c.Repo())
  152. if err != nil {
  153. // if the oauth token is not nil, we still return the token but log an error
  154. if oauthTok == nil {
  155. e := telemetry.Error(ctx, span, err, "error getting gcr token")
  156. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  157. return
  158. }
  159. e := telemetry.Error(ctx, span, err, "error getting gcr token, but token was returned")
  160. c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(e))
  161. }
  162. token = oauthTok.AccessToken
  163. expiresAt = oauthTok.Expiry
  164. break
  165. }
  166. }
  167. resp := &types.GetRegistryTokenResponse{
  168. Token: token,
  169. ExpiresAt: expiresAt,
  170. }
  171. c.WriteResult(w, r, resp)
  172. }
  173. type RegistryGetGARTokenHandler struct {
  174. handlers.PorterHandlerReadWriter
  175. }
  176. func NewRegistryGetGARTokenHandler(
  177. config *config.Config,
  178. decoderValidator shared.RequestDecoderValidator,
  179. writer shared.ResultWriter,
  180. ) *RegistryGetGARTokenHandler {
  181. return &RegistryGetGARTokenHandler{
  182. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  183. }
  184. }
  185. func (c *RegistryGetGARTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  186. ctx, span := telemetry.NewSpan(r.Context(), "serve-registry-get-gar-token")
  187. defer span.End()
  188. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  189. request := &types.GetRegistryGCRTokenRequest{}
  190. if ok := c.DecodeAndValidate(w, r, request); !ok {
  191. return
  192. }
  193. // list registries and find one that matches the region
  194. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  195. if err != nil {
  196. e := telemetry.Error(ctx, span, err, "error listing registries by project id")
  197. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  198. return
  199. }
  200. if len(regs) == 0 {
  201. e := telemetry.Error(ctx, span, err, "no registries found")
  202. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusNotFound))
  203. return
  204. }
  205. if proj.GetFeatureFlag(models.CapiProvisionerEnabled, c.Config().LaunchDarklyClient) {
  206. regInput := connect.NewRequest(&porterv1.TokenForRegistryRequest{
  207. ProjectId: int64(proj.ID),
  208. RegistryUri: regs[0].URL,
  209. })
  210. regOutput, err := c.Config().ClusterControlPlaneClient.TokenForRegistry(ctx, regInput)
  211. if err != nil {
  212. e := telemetry.Error(ctx, span, err, "error getting gar token")
  213. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  214. return
  215. }
  216. if regOutput == nil || regOutput.Msg == nil {
  217. e := telemetry.Error(ctx, span, err, "error reading gar token")
  218. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  219. return
  220. }
  221. if regOutput.Msg.Token == "" {
  222. e := telemetry.Error(ctx, span, err, "no token for for registry")
  223. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  224. return
  225. }
  226. resp := &types.GetRegistryTokenResponse{
  227. Token: regOutput.Msg.Token,
  228. ExpiresAt: regOutput.Msg.Expiry.AsTime(),
  229. }
  230. c.WriteResult(w, r, resp)
  231. return
  232. }
  233. var token string
  234. var expiresAt time.Time
  235. for _, reg := range regs {
  236. if reg.GCPIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  237. _reg := registry.Registry(*reg)
  238. oauthTok, err := _reg.GetGARToken(ctx, c.Repo())
  239. if err != nil {
  240. // if the oauth token is not nil, we still return the token but log an error
  241. if oauthTok == nil {
  242. e := telemetry.Error(ctx, span, err, "error getting gar token")
  243. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusInternalServerError))
  244. return
  245. }
  246. e := telemetry.Error(ctx, span, err, "error getting gar token, but token was returned")
  247. c.HandleAPIErrorNoWrite(w, r, apierrors.NewErrInternal(e))
  248. }
  249. if oauthTok == nil {
  250. continue
  251. }
  252. token = oauthTok.AccessToken
  253. expiresAt = oauthTok.Expiry
  254. break
  255. }
  256. }
  257. resp := &types.GetRegistryTokenResponse{
  258. Token: token,
  259. ExpiresAt: expiresAt,
  260. }
  261. c.WriteResult(w, r, resp)
  262. }
  263. type RegistryGetDOCRTokenHandler struct {
  264. handlers.PorterHandlerReadWriter
  265. }
  266. func NewRegistryGetDOCRTokenHandler(
  267. config *config.Config,
  268. decoderValidator shared.RequestDecoderValidator,
  269. writer shared.ResultWriter,
  270. ) *RegistryGetDOCRTokenHandler {
  271. return &RegistryGetDOCRTokenHandler{
  272. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  273. }
  274. }
  275. func (c *RegistryGetDOCRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  276. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  277. request := &types.GetRegistryDOCRTokenRequest{}
  278. if ok := c.DecodeAndValidate(w, r, request); !ok {
  279. return
  280. }
  281. // list registries and find one that matches the region
  282. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  283. if err != nil {
  284. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  285. return
  286. }
  287. var token string
  288. var expiresAt time.Time
  289. for _, reg := range regs {
  290. if reg.DOIntegrationID != 0 && strings.Contains(reg.URL, request.ServerURL) {
  291. oauthInt, err := c.Repo().OAuthIntegration().ReadOAuthIntegration(reg.ProjectID, reg.DOIntegrationID)
  292. if err != nil {
  293. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  294. return
  295. }
  296. tok, expiry, err := oauth.GetAccessToken(
  297. oauthInt.SharedOAuthModel,
  298. c.Config().DOConf,
  299. oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, c.Repo()),
  300. )
  301. if err != nil {
  302. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  303. return
  304. }
  305. token = tok
  306. expiresAt = *expiry
  307. break
  308. }
  309. }
  310. resp := &types.GetRegistryTokenResponse{
  311. Token: token,
  312. ExpiresAt: expiresAt,
  313. }
  314. c.WriteResult(w, r, resp)
  315. }
  316. type RegistryGetDockerhubTokenHandler struct {
  317. handlers.PorterHandlerReadWriter
  318. }
  319. func NewRegistryGetDockerhubTokenHandler(
  320. config *config.Config,
  321. decoderValidator shared.RequestDecoderValidator,
  322. writer shared.ResultWriter,
  323. ) *RegistryGetDockerhubTokenHandler {
  324. return &RegistryGetDockerhubTokenHandler{
  325. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  326. }
  327. }
  328. func (c *RegistryGetDockerhubTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  329. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  330. // list registries and find one that matches the region
  331. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  332. if err != nil {
  333. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  334. return
  335. }
  336. var token string
  337. var expiresAt time.Time
  338. for _, reg := range regs {
  339. if reg.BasicIntegrationID != 0 && strings.Contains(reg.URL, "index.docker.io") {
  340. basic, err := c.Repo().BasicIntegration().ReadBasicIntegration(reg.ProjectID, reg.BasicIntegrationID)
  341. if err != nil {
  342. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  343. return
  344. }
  345. token = base64.StdEncoding.EncodeToString([]byte(string(basic.Username) + ":" + string(basic.Password)))
  346. // we'll just set an arbitrary 30-day expiry time (this is not enforced)
  347. timeExpires := time.Now().Add(30 * 24 * 3600 * time.Second)
  348. expiresAt = timeExpires
  349. }
  350. }
  351. resp := &types.GetRegistryTokenResponse{
  352. Token: token,
  353. ExpiresAt: expiresAt,
  354. }
  355. c.WriteResult(w, r, resp)
  356. }
  357. type RegistryGetACRTokenHandler struct {
  358. handlers.PorterHandlerReadWriter
  359. }
  360. func NewRegistryGetACRTokenHandler(
  361. config *config.Config,
  362. decoderValidator shared.RequestDecoderValidator,
  363. writer shared.ResultWriter,
  364. ) *RegistryGetACRTokenHandler {
  365. return &RegistryGetACRTokenHandler{
  366. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  367. }
  368. }
  369. func (c *RegistryGetACRTokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  370. ctx, span := telemetry.NewSpan(r.Context(), "serve-acr-token")
  371. defer span.End()
  372. proj, _ := ctx.Value(types.ProjectScope).(*models.Project)
  373. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "project-id", Value: proj.ID})
  374. request := &types.GetRegistryACRTokenRequest{}
  375. if ok := c.DecodeAndValidate(w, r, request); !ok {
  376. err := telemetry.Error(ctx, span, nil, "error decoding request")
  377. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  378. return
  379. }
  380. if request.ServerURL == "" {
  381. err := telemetry.Error(ctx, span, nil, "missing server url")
  382. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  383. return
  384. }
  385. serverUrl := strings.TrimSuffix(request.ServerURL, "/")
  386. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "server-url", Value: serverUrl})
  387. // list registries and find one that matches the region
  388. regs, err := c.Repo().Registry().ListRegistriesByProjectID(proj.ID)
  389. if err != nil {
  390. err = telemetry.Error(ctx, span, err, "error getting registries by project id")
  391. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  392. return
  393. }
  394. var token string
  395. var expiresAt time.Time
  396. var matchingReg *models.Registry
  397. for _, reg := range regs {
  398. if strings.Contains(reg.URL, serverUrl) {
  399. matchingReg = reg
  400. }
  401. }
  402. if matchingReg == nil {
  403. err := telemetry.Error(ctx, span, err, "no matching registry")
  404. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  405. return
  406. }
  407. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "registry-name", Value: matchingReg.Name})
  408. if proj.GetFeatureFlag(models.CapiProvisionerEnabled, c.Config().LaunchDarklyClient) {
  409. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "capi-provisioned", Value: true})
  410. if c.Config().ClusterControlPlaneClient == nil {
  411. err := telemetry.Error(ctx, span, nil, "cluster control plane client cannot be nil")
  412. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  413. return
  414. }
  415. tokenReq := connect.NewRequest(&porterv1.TokenForRegistryRequest{
  416. ProjectId: int64(proj.ID),
  417. RegistryUri: matchingReg.URL,
  418. })
  419. tokenResp, err := c.Config().ClusterControlPlaneClient.TokenForRegistry(ctx, tokenReq)
  420. if err != nil {
  421. err = telemetry.Error(ctx, span, err, "error getting token response from ccp")
  422. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  423. return
  424. }
  425. if tokenResp.Msg == nil || tokenResp.Msg.Token == "" {
  426. err := telemetry.Error(ctx, span, nil, "no token found in response")
  427. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  428. return
  429. }
  430. token = tokenResp.Msg.Token
  431. // we'll just set an arbitrary 30-day expiry time (this is not enforced)
  432. timeExpires := time.Now().UTC().Add(30 * 24 * time.Hour)
  433. expiresAt = timeExpires
  434. }
  435. if matchingReg.AzureIntegrationID != 0 {
  436. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "capi-provisioned", Value: false})
  437. _reg := registry.Registry(*matchingReg)
  438. username, pw, err := _reg.GetACRCredentials(c.Repo())
  439. if err != nil {
  440. err = telemetry.Error(ctx, span, err, "error getting token response from ccp")
  441. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  442. return
  443. }
  444. token = base64.StdEncoding.EncodeToString([]byte(string(username) + ":" + string(pw)))
  445. // we'll just set an arbitrary 30-day expiry time (this is not enforced)
  446. timeExpires := time.Now().UTC().Add(30 * 24 * time.Hour)
  447. expiresAt = timeExpires
  448. }
  449. if token == "" {
  450. err := telemetry.Error(ctx, span, nil, "missing token")
  451. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  452. return
  453. }
  454. resp := &types.GetRegistryTokenResponse{
  455. Token: token,
  456. ExpiresAt: expiresAt,
  457. }
  458. c.WriteResult(w, r, resp)
  459. }