registry.go 20 KB

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