registry.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. package registry
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "time"
  11. "github.com/aws/aws-sdk-go/aws/awserr"
  12. "github.com/aws/aws-sdk-go/service/ecr"
  13. "github.com/porter-dev/porter/internal/models"
  14. "github.com/porter-dev/porter/internal/oauth"
  15. "github.com/porter-dev/porter/internal/repository"
  16. "golang.org/x/oauth2"
  17. ints "github.com/porter-dev/porter/internal/models/integrations"
  18. "github.com/digitalocean/godo"
  19. "github.com/docker/cli/cli/config/configfile"
  20. "github.com/docker/cli/cli/config/types"
  21. )
  22. // Registry wraps the gorm Registry model
  23. type Registry models.Registry
  24. // Repository is a collection of images
  25. type Repository struct {
  26. // Name of the repository
  27. Name string `json:"name"`
  28. // When the repository was created
  29. CreatedAt time.Time `json:"created_at,omitempty"`
  30. // The URI of the repository
  31. URI string `json:"uri"`
  32. }
  33. // Image is a Docker image type
  34. type Image struct {
  35. // The sha256 digest of the image manifest.
  36. Digest string `json:"digest"`
  37. // The tag used for the image.
  38. Tag string `json:"tag"`
  39. // The image manifest associated with the image.
  40. Manifest string `json:"manifest"`
  41. // The name of the repository associated with the image.
  42. RepositoryName string `json:"repository_name"`
  43. // When the image was pushed
  44. PushedAt *time.Time `json:"pushed_at"`
  45. }
  46. // ListRepositories lists the repositories for a registry
  47. func (r *Registry) ListRepositories(
  48. repo repository.Repository,
  49. doAuth *oauth2.Config, // only required if using DOCR
  50. ) ([]*Repository, error) {
  51. // switch on the auth mechanism to get a token
  52. if r.AWSIntegrationID != 0 {
  53. return r.listECRRepositories(repo)
  54. }
  55. if r.GCPIntegrationID != 0 {
  56. return r.listGCRRepositories(repo)
  57. }
  58. if r.DOIntegrationID != 0 {
  59. return r.listDOCRRepositories(repo, doAuth)
  60. }
  61. if r.BasicIntegrationID != 0 {
  62. return r.listPrivateRegistryRepositories(repo)
  63. }
  64. return nil, fmt.Errorf("error listing repositories")
  65. }
  66. type gcrJWT struct {
  67. AccessToken string `json:"token"`
  68. ExpiresInSec int `json:"expires_in"`
  69. }
  70. type gcrRepositoryResp struct {
  71. Repositories []string `json:"repositories"`
  72. }
  73. func (r *Registry) GetGCRToken(repo repository.Repository) (*ints.TokenCache, error) {
  74. gcp, err := repo.GCPIntegration.ReadGCPIntegration(
  75. r.GCPIntegrationID,
  76. )
  77. if err != nil {
  78. return nil, err
  79. }
  80. // get oauth2 access token
  81. _, err = gcp.GetBearerToken(
  82. r.getTokenCache,
  83. r.setTokenCacheFunc(repo),
  84. "https://www.googleapis.com/auth/devstorage.read_write",
  85. )
  86. if err != nil {
  87. return nil, err
  88. }
  89. // it's now written to the token cache, so return
  90. cache, err := r.getTokenCache()
  91. if err != nil {
  92. return nil, err
  93. }
  94. return cache, nil
  95. }
  96. func (r *Registry) listGCRRepositories(
  97. repo repository.Repository,
  98. ) ([]*Repository, error) {
  99. gcp, err := repo.GCPIntegration.ReadGCPIntegration(
  100. r.GCPIntegrationID,
  101. )
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Just use service account key to authenticate, since scopes may not be in place
  106. // for oauth. This also prevents us from making more requests.
  107. client := &http.Client{}
  108. req, err := http.NewRequest(
  109. "GET",
  110. "https://gcr.io/v2/_catalog",
  111. nil,
  112. )
  113. if err != nil {
  114. return nil, err
  115. }
  116. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  117. resp, err := client.Do(req)
  118. if err != nil {
  119. return nil, err
  120. }
  121. gcrResp := gcrRepositoryResp{}
  122. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  123. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  124. }
  125. res := make([]*Repository, 0)
  126. parsedURL, err := url.Parse("https://" + r.URL)
  127. if err != nil {
  128. return nil, err
  129. }
  130. for _, repo := range gcrResp.Repositories {
  131. res = append(res, &Repository{
  132. Name: repo,
  133. URI: parsedURL.Host + "/" + repo,
  134. })
  135. }
  136. return res, nil
  137. }
  138. func (r *Registry) listECRRepositories(repo repository.Repository) ([]*Repository, error) {
  139. aws, err := repo.AWSIntegration.ReadAWSIntegration(
  140. r.AWSIntegrationID,
  141. )
  142. if err != nil {
  143. return nil, err
  144. }
  145. sess, err := aws.GetSession()
  146. if err != nil {
  147. return nil, err
  148. }
  149. svc := ecr.New(sess)
  150. resp, err := svc.DescribeRepositories(&ecr.DescribeRepositoriesInput{})
  151. if err != nil {
  152. return nil, err
  153. }
  154. res := make([]*Repository, 0)
  155. for _, repo := range resp.Repositories {
  156. res = append(res, &Repository{
  157. Name: *repo.RepositoryName,
  158. CreatedAt: *repo.CreatedAt,
  159. URI: *repo.RepositoryUri,
  160. })
  161. }
  162. return res, nil
  163. }
  164. func (r *Registry) listDOCRRepositories(
  165. repo repository.Repository,
  166. doAuth *oauth2.Config,
  167. ) ([]*Repository, error) {
  168. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  169. r.DOIntegrationID,
  170. )
  171. if err != nil {
  172. return nil, err
  173. }
  174. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  175. if err != nil {
  176. return nil, err
  177. }
  178. client := godo.NewFromToken(tok)
  179. urlArr := strings.Split(r.URL, "/")
  180. if len(urlArr) != 2 {
  181. return nil, fmt.Errorf("invalid digital ocean registry url")
  182. }
  183. name := urlArr[1]
  184. repos, _, err := client.Registry.ListRepositories(context.TODO(), name, &godo.ListOptions{})
  185. if err != nil {
  186. return nil, err
  187. }
  188. res := make([]*Repository, 0)
  189. for _, repo := range repos {
  190. res = append(res, &Repository{
  191. Name: repo.Name,
  192. URI: r.URL + "/" + repo.Name,
  193. })
  194. }
  195. return res, nil
  196. }
  197. func (r *Registry) listPrivateRegistryRepositories(
  198. repo repository.Repository,
  199. ) ([]*Repository, error) {
  200. // handle dockerhub different, as it doesn't implement the docker registry http api
  201. if strings.Contains(r.URL, "docker.io") {
  202. // in this case, we just return the single dockerhub repository that's linked
  203. res := make([]*Repository, 0)
  204. res = append(res, &Repository{
  205. Name: strings.Split(r.URL, "docker.io/")[1],
  206. URI: r.URL,
  207. })
  208. return res, nil
  209. }
  210. basic, err := repo.BasicIntegration.ReadBasicIntegration(
  211. r.BasicIntegrationID,
  212. )
  213. if err != nil {
  214. return nil, err
  215. }
  216. // Just use service account key to authenticate, since scopes may not be in place
  217. // for oauth. This also prevents us from making more requests.
  218. client := &http.Client{}
  219. // get the host and scheme to make the request
  220. parsedURL, err := url.Parse(r.URL)
  221. req, err := http.NewRequest(
  222. "GET",
  223. fmt.Sprintf("%s://%s/v2/_catalog", parsedURL.Scheme, parsedURL.Host),
  224. nil,
  225. )
  226. if err != nil {
  227. return nil, err
  228. }
  229. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  230. resp, err := client.Do(req)
  231. if err != nil {
  232. return nil, err
  233. }
  234. // if the status code is 404, fallback to the Docker Hub implementation
  235. if resp.StatusCode == 404 {
  236. req, err := http.NewRequest(
  237. "GET",
  238. fmt.Sprintf("%s/", r.URL),
  239. nil,
  240. )
  241. if err != nil {
  242. return nil, err
  243. }
  244. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  245. resp, err = client.Do(req)
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. gcrResp := gcrRepositoryResp{}
  251. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  252. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  253. }
  254. res := make([]*Repository, 0)
  255. if err != nil {
  256. return nil, err
  257. }
  258. for _, repo := range gcrResp.Repositories {
  259. res = append(res, &Repository{
  260. Name: repo,
  261. URI: parsedURL.Host + "/" + repo,
  262. })
  263. }
  264. return res, nil
  265. }
  266. func (r *Registry) getTokenCache() (tok *ints.TokenCache, err error) {
  267. return &ints.TokenCache{
  268. Token: r.TokenCache.Token,
  269. Expiry: r.TokenCache.Expiry,
  270. }, nil
  271. }
  272. func (r *Registry) setTokenCacheFunc(
  273. repo repository.Repository,
  274. ) ints.SetTokenCacheFunc {
  275. return func(token string, expiry time.Time) error {
  276. _, err := repo.Registry.UpdateRegistryTokenCache(
  277. &ints.RegTokenCache{
  278. TokenCache: ints.TokenCache{
  279. Token: []byte(token),
  280. Expiry: expiry,
  281. },
  282. RegistryID: r.ID,
  283. },
  284. )
  285. return err
  286. }
  287. }
  288. // CreateRepository creates a repository for a registry, if needed
  289. // (currently only required for ECR)
  290. func (r *Registry) CreateRepository(
  291. repo repository.Repository,
  292. name string,
  293. ) error {
  294. // if aws, create repository
  295. if r.AWSIntegrationID != 0 {
  296. return r.createECRRepository(repo, name)
  297. }
  298. // otherwise, no-op
  299. return nil
  300. }
  301. func (r *Registry) createECRRepository(
  302. repo repository.Repository,
  303. name string,
  304. ) error {
  305. aws, err := repo.AWSIntegration.ReadAWSIntegration(
  306. r.AWSIntegrationID,
  307. )
  308. if err != nil {
  309. return err
  310. }
  311. sess, err := aws.GetSession()
  312. if err != nil {
  313. return err
  314. }
  315. svc := ecr.New(sess)
  316. // determine if repository already exists
  317. _, err = svc.DescribeRepositories(&ecr.DescribeRepositoriesInput{
  318. RepositoryNames: []*string{&name},
  319. })
  320. // if the repository was not found, create it
  321. if aerr, ok := err.(awserr.Error); ok && aerr.Code() == ecr.ErrCodeRepositoryNotFoundException {
  322. _, err = svc.CreateRepository(&ecr.CreateRepositoryInput{
  323. RepositoryName: &name,
  324. })
  325. return err
  326. } else if err != nil {
  327. return err
  328. }
  329. return nil
  330. }
  331. // ListImages lists the images for an image repository
  332. func (r *Registry) ListImages(
  333. repoName string,
  334. repo repository.Repository,
  335. doAuth *oauth2.Config, // only required if using DOCR
  336. ) ([]*Image, error) {
  337. // switch on the auth mechanism to get a token
  338. if r.AWSIntegrationID != 0 {
  339. return r.listECRImages(repoName, repo)
  340. }
  341. if r.GCPIntegrationID != 0 {
  342. return r.listGCRImages(repoName, repo)
  343. }
  344. if r.DOIntegrationID != 0 {
  345. return r.listDOCRImages(repoName, repo, doAuth)
  346. }
  347. if r.BasicIntegrationID != 0 {
  348. return r.listPrivateRegistryImages(repoName, repo)
  349. }
  350. return nil, fmt.Errorf("error listing images")
  351. }
  352. func (r *Registry) listECRImages(repoName string, repo repository.Repository) ([]*Image, error) {
  353. aws, err := repo.AWSIntegration.ReadAWSIntegration(
  354. r.AWSIntegrationID,
  355. )
  356. if err != nil {
  357. return nil, err
  358. }
  359. sess, err := aws.GetSession()
  360. if err != nil {
  361. return nil, err
  362. }
  363. svc := ecr.New(sess)
  364. resp, err := svc.ListImages(&ecr.ListImagesInput{
  365. RepositoryName: &repoName,
  366. })
  367. if err != nil {
  368. return nil, err
  369. }
  370. describeResp, err := svc.DescribeImages(&ecr.DescribeImagesInput{
  371. RepositoryName: &repoName,
  372. ImageIds: resp.ImageIds,
  373. })
  374. if err != nil {
  375. return nil, err
  376. }
  377. imageDetails := describeResp.ImageDetails
  378. nextToken := describeResp.NextToken
  379. for nextToken != nil {
  380. describeResp, err := svc.DescribeImages(&ecr.DescribeImagesInput{
  381. RepositoryName: &repoName,
  382. ImageIds: resp.ImageIds,
  383. })
  384. if err != nil {
  385. return nil, err
  386. }
  387. nextToken = describeResp.NextToken
  388. imageDetails = append(imageDetails, describeResp.ImageDetails...)
  389. }
  390. res := make([]*Image, 0)
  391. for _, img := range imageDetails {
  392. for _, tag := range img.ImageTags {
  393. res = append(res, &Image{
  394. Digest: *img.ImageDigest,
  395. Tag: *tag,
  396. RepositoryName: repoName,
  397. PushedAt: img.ImagePushedAt,
  398. })
  399. }
  400. }
  401. return res, nil
  402. }
  403. type gcrImageResp struct {
  404. Tags []string `json:"tags"`
  405. }
  406. func (r *Registry) listGCRImages(repoName string, repo repository.Repository) ([]*Image, error) {
  407. gcp, err := repo.GCPIntegration.ReadGCPIntegration(
  408. r.GCPIntegrationID,
  409. )
  410. if err != nil {
  411. return nil, err
  412. }
  413. // use JWT token to request catalog
  414. client := &http.Client{}
  415. parsedURL, err := url.Parse("https://" + r.URL)
  416. if err != nil {
  417. return nil, err
  418. }
  419. trimmedPath := strings.Trim(parsedURL.Path, "/")
  420. req, err := http.NewRequest(
  421. "GET",
  422. fmt.Sprintf("https://%s/v2/%s/%s/tags/list", parsedURL.Host, trimmedPath, repoName),
  423. nil,
  424. )
  425. if err != nil {
  426. return nil, err
  427. }
  428. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  429. resp, err := client.Do(req)
  430. if err != nil {
  431. return nil, err
  432. }
  433. gcrResp := gcrImageResp{}
  434. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  435. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  436. }
  437. res := make([]*Image, 0)
  438. for _, tag := range gcrResp.Tags {
  439. res = append(res, &Image{
  440. RepositoryName: repoName,
  441. Tag: tag,
  442. })
  443. }
  444. return res, nil
  445. }
  446. func (r *Registry) listDOCRImages(
  447. repoName string,
  448. repo repository.Repository,
  449. doAuth *oauth2.Config,
  450. ) ([]*Image, error) {
  451. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  452. r.DOIntegrationID,
  453. )
  454. if err != nil {
  455. return nil, err
  456. }
  457. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  458. if err != nil {
  459. return nil, err
  460. }
  461. client := godo.NewFromToken(tok)
  462. urlArr := strings.Split(r.URL, "/")
  463. if len(urlArr) != 2 {
  464. return nil, fmt.Errorf("invalid digital ocean registry url")
  465. }
  466. name := urlArr[1]
  467. tags, _, err := client.Registry.ListRepositoryTags(context.TODO(), name, repoName, &godo.ListOptions{})
  468. if err != nil {
  469. return nil, err
  470. }
  471. res := make([]*Image, 0)
  472. for _, tag := range tags {
  473. res = append(res, &Image{
  474. RepositoryName: repoName,
  475. Tag: tag.Tag,
  476. })
  477. }
  478. return res, nil
  479. }
  480. func (r *Registry) listPrivateRegistryImages(repoName string, repo repository.Repository) ([]*Image, error) {
  481. // handle dockerhub different, as it doesn't implement the docker registry http api
  482. if strings.Contains(r.URL, "docker.io") {
  483. return r.listDockerHubImages(repoName, repo)
  484. }
  485. basic, err := repo.BasicIntegration.ReadBasicIntegration(
  486. r.BasicIntegrationID,
  487. )
  488. if err != nil {
  489. return nil, err
  490. }
  491. // Just use service account key to authenticate, since scopes may not be in place
  492. // for oauth. This also prevents us from making more requests.
  493. client := &http.Client{}
  494. // get the host and scheme to make the request
  495. parsedURL, err := url.Parse(r.URL)
  496. req, err := http.NewRequest(
  497. "GET",
  498. fmt.Sprintf("%s://%s/v2/%s/tags/list", parsedURL.Scheme, parsedURL.Host, repoName),
  499. nil,
  500. )
  501. if err != nil {
  502. return nil, err
  503. }
  504. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  505. resp, err := client.Do(req)
  506. if err != nil {
  507. return nil, err
  508. }
  509. gcrResp := gcrImageResp{}
  510. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  511. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  512. }
  513. res := make([]*Image, 0)
  514. for _, tag := range gcrResp.Tags {
  515. res = append(res, &Image{
  516. RepositoryName: repoName,
  517. Tag: tag,
  518. })
  519. }
  520. return res, nil
  521. }
  522. type dockerHubImageResult struct {
  523. Name string `json:"name"`
  524. }
  525. type dockerHubImageResp struct {
  526. Results []dockerHubImageResult `json:"results"`
  527. }
  528. type dockerHubLoginReq struct {
  529. Username string `json:"username"`
  530. Password string `json:"password"`
  531. }
  532. type dockerHubLoginResp struct {
  533. Token string `json:"token"`
  534. }
  535. func (r *Registry) listDockerHubImages(repoName string, repo repository.Repository) ([]*Image, error) {
  536. basic, err := repo.BasicIntegration.ReadBasicIntegration(
  537. r.BasicIntegrationID,
  538. )
  539. if err != nil {
  540. return nil, err
  541. }
  542. client := &http.Client{}
  543. // first, make a request for the access token
  544. data, err := json.Marshal(&dockerHubLoginReq{
  545. Username: string(basic.Username),
  546. Password: string(basic.Password),
  547. })
  548. if err != nil {
  549. return nil, err
  550. }
  551. req, err := http.NewRequest(
  552. "POST",
  553. "https://hub.docker.com/v2/users/login",
  554. strings.NewReader(string(data)),
  555. )
  556. if err != nil {
  557. return nil, err
  558. }
  559. req.Header.Add("Content-Type", "application/json")
  560. resp, err := client.Do(req)
  561. if err != nil {
  562. return nil, err
  563. }
  564. tokenObj := dockerHubLoginResp{}
  565. if err := json.NewDecoder(resp.Body).Decode(&tokenObj); err != nil {
  566. return nil, fmt.Errorf("Could not decode Dockerhub token from response: %v", err)
  567. }
  568. req, err = http.NewRequest(
  569. "GET",
  570. fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/tags", strings.Split(r.URL, "docker.io/")[1]),
  571. nil,
  572. )
  573. if err != nil {
  574. return nil, err
  575. }
  576. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tokenObj.Token))
  577. resp, err = client.Do(req)
  578. if err != nil {
  579. return nil, err
  580. }
  581. imageResp := dockerHubImageResp{}
  582. if err := json.NewDecoder(resp.Body).Decode(&imageResp); err != nil {
  583. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  584. }
  585. res := make([]*Image, 0)
  586. for _, result := range imageResp.Results {
  587. res = append(res, &Image{
  588. RepositoryName: repoName,
  589. Tag: result.Name,
  590. })
  591. }
  592. return res, nil
  593. }
  594. // GetDockerConfigJSON returns a dockerconfigjson file contents with "auths"
  595. // populated.
  596. func (r *Registry) GetDockerConfigJSON(
  597. repo repository.Repository,
  598. doAuth *oauth2.Config, // only required if using DOCR
  599. ) ([]byte, error) {
  600. var conf *configfile.ConfigFile
  601. var err error
  602. // switch on the auth mechanism to get a token
  603. if r.AWSIntegrationID != 0 {
  604. conf, err = r.getECRDockerConfigFile(repo)
  605. }
  606. if r.GCPIntegrationID != 0 {
  607. conf, err = r.getGCRDockerConfigFile(repo)
  608. }
  609. if r.DOIntegrationID != 0 {
  610. conf, err = r.getDOCRDockerConfigFile(repo, doAuth)
  611. }
  612. if r.BasicIntegrationID != 0 {
  613. conf, err = r.getPrivateRegistryDockerConfigFile(repo)
  614. }
  615. if err != nil {
  616. return nil, err
  617. }
  618. return json.Marshal(conf)
  619. }
  620. func (r *Registry) getECRDockerConfigFile(
  621. repo repository.Repository,
  622. ) (*configfile.ConfigFile, error) {
  623. aws, err := repo.AWSIntegration.ReadAWSIntegration(
  624. r.AWSIntegrationID,
  625. )
  626. if err != nil {
  627. return nil, err
  628. }
  629. sess, err := aws.GetSession()
  630. if err != nil {
  631. return nil, err
  632. }
  633. ecrSvc := ecr.New(sess)
  634. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  635. if err != nil {
  636. return nil, err
  637. }
  638. token := *output.AuthorizationData[0].AuthorizationToken
  639. decodedToken, err := base64.StdEncoding.DecodeString(token)
  640. if err != nil {
  641. return nil, err
  642. }
  643. parts := strings.SplitN(string(decodedToken), ":", 2)
  644. if len(parts) < 2 {
  645. return nil, err
  646. }
  647. key := r.URL
  648. if !strings.Contains(key, "http") {
  649. key = "https://" + key
  650. }
  651. return &configfile.ConfigFile{
  652. AuthConfigs: map[string]types.AuthConfig{
  653. key: types.AuthConfig{
  654. Username: parts[0],
  655. Password: parts[1],
  656. Auth: token,
  657. },
  658. },
  659. }, nil
  660. }
  661. func (r *Registry) getGCRDockerConfigFile(
  662. repo repository.Repository,
  663. ) (*configfile.ConfigFile, error) {
  664. gcp, err := repo.GCPIntegration.ReadGCPIntegration(
  665. r.GCPIntegrationID,
  666. )
  667. if err != nil {
  668. return nil, err
  669. }
  670. key := r.URL
  671. if !strings.Contains(key, "http") {
  672. key = "https://" + key
  673. }
  674. parsedURL, _ := url.Parse(key)
  675. return &configfile.ConfigFile{
  676. AuthConfigs: map[string]types.AuthConfig{
  677. parsedURL.Host: types.AuthConfig{
  678. Username: "_json_key",
  679. Password: string(gcp.GCPKeyData),
  680. Auth: generateAuthToken("_json_key", string(gcp.GCPKeyData)),
  681. },
  682. },
  683. }, nil
  684. }
  685. func (r *Registry) getDOCRDockerConfigFile(
  686. repo repository.Repository,
  687. doAuth *oauth2.Config,
  688. ) (*configfile.ConfigFile, error) {
  689. oauthInt, err := repo.OAuthIntegration.ReadOAuthIntegration(
  690. r.DOIntegrationID,
  691. )
  692. if err != nil {
  693. return nil, err
  694. }
  695. tok, _, err := oauth.GetAccessToken(oauthInt, doAuth, repo)
  696. if err != nil {
  697. return nil, err
  698. }
  699. key := r.URL
  700. if !strings.Contains(key, "http") {
  701. key = "https://" + key
  702. }
  703. parsedURL, _ := url.Parse(key)
  704. return &configfile.ConfigFile{
  705. AuthConfigs: map[string]types.AuthConfig{
  706. parsedURL.Host: types.AuthConfig{
  707. Username: tok,
  708. Password: tok,
  709. Auth: generateAuthToken(tok, tok),
  710. },
  711. },
  712. }, nil
  713. }
  714. func (r *Registry) getPrivateRegistryDockerConfigFile(
  715. repo repository.Repository,
  716. ) (*configfile.ConfigFile, error) {
  717. basic, err := repo.BasicIntegration.ReadBasicIntegration(
  718. r.BasicIntegrationID,
  719. )
  720. if err != nil {
  721. return nil, err
  722. }
  723. key := r.URL
  724. if !strings.Contains(key, "http") {
  725. key = "https://" + key
  726. }
  727. parsedURL, _ := url.Parse(key)
  728. authConfigKey := parsedURL.Host
  729. if strings.Contains(r.URL, "index.docker.io") {
  730. authConfigKey = "https://index.docker.io/v1/"
  731. }
  732. return &configfile.ConfigFile{
  733. AuthConfigs: map[string]types.AuthConfig{
  734. authConfigKey: types.AuthConfig{
  735. Username: string(basic.Username),
  736. Password: string(basic.Password),
  737. Auth: generateAuthToken(string(basic.Username), string(basic.Password)),
  738. },
  739. },
  740. }, nil
  741. }
  742. func generateAuthToken(username, password string) string {
  743. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  744. }