registry.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. package registry
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "sync"
  12. "time"
  13. artifactregistry "cloud.google.com/go/artifactregistry/apiv1beta2"
  14. "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
  15. "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
  16. "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/containerregistry/armcontainerregistry"
  17. "github.com/aws/aws-sdk-go-v2/service/ecr"
  18. ecrTypes "github.com/aws/aws-sdk-go-v2/service/ecr/types"
  19. "github.com/digitalocean/godo"
  20. "github.com/docker/cli/cli/config/configfile"
  21. "github.com/docker/cli/cli/config/types"
  22. "github.com/docker/distribution/reference"
  23. ptypes "github.com/porter-dev/porter/api/types"
  24. "github.com/porter-dev/porter/internal/models"
  25. ints "github.com/porter-dev/porter/internal/models/integrations"
  26. "github.com/porter-dev/porter/internal/oauth"
  27. "github.com/porter-dev/porter/internal/repository"
  28. "golang.org/x/oauth2"
  29. v1artifactregistry "google.golang.org/api/artifactregistry/v1"
  30. "google.golang.org/api/iterator"
  31. "google.golang.org/api/option"
  32. artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2"
  33. )
  34. // Registry wraps the gorm Registry model
  35. type Registry models.Registry
  36. func GetECRRegistryURL(awsIntRepo repository.AWSIntegrationRepository, projectID, awsIntID uint) (string, error) {
  37. ctx := context.Background()
  38. awsInt, err := awsIntRepo.ReadAWSIntegration(projectID, awsIntID)
  39. if err != nil {
  40. return "", err
  41. }
  42. svc := ecr.NewFromConfig(awsInt.Config())
  43. output, err := svc.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
  44. if err != nil {
  45. return "", err
  46. }
  47. return *output.AuthorizationData[0].ProxyEndpoint, nil
  48. }
  49. // ListRepositories lists the repositories for a registry
  50. func (r *Registry) ListRepositories(
  51. repo repository.Repository,
  52. doAuth *oauth2.Config, // only required if using DOCR
  53. ) ([]*ptypes.RegistryRepository, error) {
  54. // switch on the auth mechanism to get a token
  55. if r.AWSIntegrationID != 0 {
  56. return r.listECRRepositories(repo)
  57. }
  58. if r.GCPIntegrationID != 0 {
  59. if strings.Contains(r.URL, "pkg.dev") {
  60. return r.listGARRepositories(repo)
  61. }
  62. return r.listGCRRepositories(repo)
  63. }
  64. if r.DOIntegrationID != 0 {
  65. return r.listDOCRRepositories(repo, doAuth)
  66. }
  67. if r.AzureIntegrationID != 0 {
  68. return r.listACRRepositories(repo)
  69. }
  70. if r.BasicIntegrationID != 0 {
  71. return r.listPrivateRegistryRepositories(repo)
  72. }
  73. return nil, fmt.Errorf("error listing repositories")
  74. }
  75. type gcrJWT struct {
  76. AccessToken string `json:"token"`
  77. ExpiresInSec int `json:"expires_in"`
  78. }
  79. type gcrErr struct {
  80. Code string `json:"code"`
  81. Message string `json:"message"`
  82. }
  83. type gcrRepositoryResp struct {
  84. Repositories []string `json:"repositories"`
  85. Errors []gcrErr `json:"errors"`
  86. }
  87. func (r *Registry) GetGCRToken(repo repository.Repository) (*oauth2.Token, error) {
  88. getTokenCache := r.getTokenCacheFunc(repo)
  89. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  90. r.ProjectID,
  91. r.GCPIntegrationID,
  92. )
  93. if err != nil {
  94. return nil, err
  95. }
  96. // get oauth2 access token
  97. return gcp.GetBearerToken(
  98. getTokenCache,
  99. r.setTokenCacheFunc(repo),
  100. "https://www.googleapis.com/auth/devstorage.read_write",
  101. )
  102. }
  103. func (r *Registry) listGCRRepositories(
  104. repo repository.Repository,
  105. ) ([]*ptypes.RegistryRepository, error) {
  106. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  107. r.ProjectID,
  108. r.GCPIntegrationID,
  109. )
  110. if err != nil {
  111. return nil, err
  112. }
  113. // Just use service account key to authenticate, since scopes may not be in place
  114. // for oauth. This also prevents us from making more requests.
  115. client := &http.Client{}
  116. regURL := r.URL
  117. if !strings.HasPrefix(regURL, "http") {
  118. regURL = fmt.Sprintf("https://%s", regURL)
  119. }
  120. regURLParsed, err := url.Parse(regURL)
  121. regHostname := "gcr.io"
  122. if err == nil {
  123. regHostname = regURLParsed.Host
  124. }
  125. req, err := http.NewRequest(
  126. "GET",
  127. fmt.Sprintf("https://%s/v2/_catalog", regHostname),
  128. nil,
  129. )
  130. if err != nil {
  131. return nil, err
  132. }
  133. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  134. resp, err := client.Do(req)
  135. if err != nil {
  136. return nil, err
  137. }
  138. gcrResp := gcrRepositoryResp{}
  139. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  140. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  141. }
  142. if len(gcrResp.Errors) > 0 {
  143. errMsg := ""
  144. for _, gcrErr := range gcrResp.Errors {
  145. errMsg += fmt.Sprintf(": Code %s, message %s", gcrErr.Code, gcrErr.Message)
  146. }
  147. return nil, fmt.Errorf(errMsg)
  148. }
  149. res := make([]*ptypes.RegistryRepository, 0)
  150. parsedURL, err := url.Parse("https://" + r.URL)
  151. if err != nil {
  152. return nil, err
  153. }
  154. for _, repo := range gcrResp.Repositories {
  155. res = append(res, &ptypes.RegistryRepository{
  156. Name: repo,
  157. URI: parsedURL.Host + "/" + repo,
  158. })
  159. }
  160. return res, nil
  161. }
  162. func (r *Registry) GetGARToken(repo repository.Repository) (*oauth2.Token, error) {
  163. getTokenCache := r.getTokenCacheFunc(repo)
  164. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  165. r.ProjectID,
  166. r.GCPIntegrationID,
  167. )
  168. if err != nil {
  169. return nil, err
  170. }
  171. // get oauth2 access token
  172. return gcp.GetBearerToken(
  173. getTokenCache,
  174. r.setTokenCacheFunc(repo),
  175. "https://www.googleapis.com/auth/cloud-platform",
  176. )
  177. }
  178. type garTokenSource struct {
  179. reg *Registry
  180. repo repository.Repository
  181. }
  182. func (source *garTokenSource) Token() (*oauth2.Token, error) {
  183. return source.reg.GetGARToken(source.repo)
  184. }
  185. // GAR has the concept of a "repository" which is a collection of images, unlike ECR or others
  186. // where a repository is a single image. This function returns the list of fully qualified names
  187. // of GAR images including their repository names.
  188. func (r *Registry) listGARRepositories(
  189. repo repository.Repository,
  190. ) ([]*ptypes.RegistryRepository, error) {
  191. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  192. r.ProjectID,
  193. r.GCPIntegrationID,
  194. )
  195. if err != nil {
  196. return nil, err
  197. }
  198. client, err := artifactregistry.NewClient(context.Background(), option.WithTokenSource(&garTokenSource{
  199. reg: r,
  200. repo: repo,
  201. }), option.WithScopes("roles/artifactregistry.reader"))
  202. if err != nil {
  203. return nil, err
  204. }
  205. var repoNames []string
  206. nextToken := ""
  207. parsedURL, err := url.Parse("https://" + r.URL)
  208. if err != nil {
  209. return nil, err
  210. }
  211. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  212. for {
  213. it := client.ListRepositories(context.Background(), &artifactregistrypb.ListRepositoriesRequest{
  214. Parent: fmt.Sprintf("projects/%s/locations/%s", gcpInt.GCPProjectID, location),
  215. PageSize: 1000,
  216. PageToken: nextToken,
  217. })
  218. for {
  219. resp, err := it.Next()
  220. if err == iterator.Done {
  221. break
  222. } else if err != nil {
  223. return nil, err
  224. }
  225. if resp.GetFormat() == artifactregistrypb.Repository_DOCKER { // we only care about
  226. repoSlice := strings.Split(resp.GetName(), "/")
  227. repoName := repoSlice[len(repoSlice)-1]
  228. repoNames = append(repoNames, repoName)
  229. }
  230. }
  231. if it.PageInfo().Token == "" {
  232. break
  233. }
  234. nextToken = it.PageInfo().Token
  235. }
  236. svc, err := v1artifactregistry.NewService(context.Background(), option.WithTokenSource(&garTokenSource{
  237. reg: r,
  238. repo: repo,
  239. }), option.WithScopes("roles/artifactregistry.reader"))
  240. if err != nil {
  241. return nil, err
  242. }
  243. nextToken = ""
  244. dockerSvc := v1artifactregistry.NewProjectsLocationsRepositoriesDockerImagesService(svc)
  245. var (
  246. wg sync.WaitGroup
  247. resMap sync.Map
  248. )
  249. for _, repoName := range repoNames {
  250. wg.Add(1)
  251. go func(repoName string) {
  252. defer wg.Done()
  253. for {
  254. resp, err := dockerSvc.List(fmt.Sprintf("projects/%s/locations/%s/repositories/%s",
  255. gcpInt.GCPProjectID, location, repoName)).PageSize(1000).PageToken(nextToken).Do()
  256. if err != nil {
  257. // FIXME: we should report this error using a channel
  258. return
  259. }
  260. for _, image := range resp.DockerImages {
  261. named, err := reference.ParseNamed(image.Uri)
  262. if err != nil {
  263. // let us skip this image becaue it has a malformed URI coming from the GCP API
  264. continue
  265. }
  266. uploadTime, _ := time.Parse(time.RFC3339, image.UploadTime)
  267. resMap.Store(named.Name(), &ptypes.RegistryRepository{
  268. Name: repoName,
  269. URI: named.Name(),
  270. CreatedAt: uploadTime,
  271. })
  272. }
  273. if resp.NextPageToken == "" {
  274. break
  275. }
  276. nextToken = resp.NextPageToken
  277. }
  278. }(repoName)
  279. }
  280. wg.Wait()
  281. var res []*ptypes.RegistryRepository
  282. resMap.Range(func(_, value any) bool {
  283. res = append(res, value.(*ptypes.RegistryRepository))
  284. return true
  285. })
  286. return res, nil
  287. }
  288. func (r *Registry) listECRRepositories(repo repository.Repository) ([]*ptypes.RegistryRepository, error) {
  289. ctx := context.Background()
  290. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  291. r.ProjectID,
  292. r.AWSIntegrationID,
  293. )
  294. if err != nil {
  295. return nil, err
  296. }
  297. svc := ecr.NewFromConfig(aws.Config())
  298. resp, err := svc.DescribeRepositories(ctx, &ecr.DescribeRepositoriesInput{})
  299. if err != nil {
  300. return nil, err
  301. }
  302. res := make([]*ptypes.RegistryRepository, 0)
  303. for _, repo := range resp.Repositories {
  304. res = append(res, &ptypes.RegistryRepository{
  305. Name: *repo.RepositoryName,
  306. CreatedAt: *repo.CreatedAt,
  307. URI: *repo.RepositoryUri,
  308. })
  309. }
  310. return res, nil
  311. }
  312. func (r *Registry) listACRRepositories(repo repository.Repository) ([]*ptypes.RegistryRepository, error) {
  313. az, err := repo.AzureIntegration().ReadAzureIntegration(
  314. r.ProjectID,
  315. r.AzureIntegrationID,
  316. )
  317. if err != nil {
  318. return nil, err
  319. }
  320. client := &http.Client{}
  321. req, err := http.NewRequest(
  322. "GET",
  323. fmt.Sprintf("%s/v2/_catalog", r.URL),
  324. nil,
  325. )
  326. if err != nil {
  327. return nil, err
  328. }
  329. req.SetBasicAuth(az.AzureClientID, string(az.ServicePrincipalSecret))
  330. resp, err := client.Do(req)
  331. if err != nil {
  332. return nil, err
  333. }
  334. gcrResp := gcrRepositoryResp{}
  335. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  336. return nil, fmt.Errorf("Could not read Azure registry repositories: %v", err)
  337. }
  338. res := make([]*ptypes.RegistryRepository, 0)
  339. if err != nil {
  340. return nil, err
  341. }
  342. for _, repo := range gcrResp.Repositories {
  343. res = append(res, &ptypes.RegistryRepository{
  344. Name: repo,
  345. URI: strings.TrimPrefix(r.URL, "https://") + "/" + repo,
  346. })
  347. }
  348. return res, nil
  349. }
  350. // Returns the username/password pair for the registry
  351. func (r *Registry) GetACRCredentials(repo repository.Repository) (string, string, error) {
  352. az, err := repo.AzureIntegration().ReadAzureIntegration(
  353. r.ProjectID,
  354. r.AzureIntegrationID,
  355. )
  356. if err != nil {
  357. return "", "", err
  358. }
  359. // if the passwords and name aren't set, generate them
  360. if az.ACRTokenName == "" || len(az.ACRPassword1) == 0 {
  361. az.ACRTokenName = "porter-acr-token"
  362. // create an acr repo token
  363. cred, err := azidentity.NewClientSecretCredential(az.AzureTenantID, az.AzureClientID, string(az.ServicePrincipalSecret), nil)
  364. if err != nil {
  365. return "", "", err
  366. }
  367. scopeMapsClient, err := armcontainerregistry.NewScopeMapsClient(az.AzureSubscriptionID, cred, nil)
  368. if err != nil {
  369. return "", "", err
  370. }
  371. smRes, err := scopeMapsClient.Get(
  372. context.Background(),
  373. az.ACRResourceGroupName,
  374. az.ACRName,
  375. "_repositories_admin",
  376. nil,
  377. )
  378. if err != nil {
  379. return "", "", err
  380. }
  381. tokensClient, err := armcontainerregistry.NewTokensClient(az.AzureSubscriptionID, cred, nil)
  382. if err != nil {
  383. return "", "", err
  384. }
  385. pollerResp, err := tokensClient.BeginCreate(
  386. context.Background(),
  387. az.ACRResourceGroupName,
  388. az.ACRName,
  389. "porter-acr-token",
  390. armcontainerregistry.Token{
  391. Properties: &armcontainerregistry.TokenProperties{
  392. ScopeMapID: smRes.ID,
  393. Status: to.Ptr(armcontainerregistry.TokenStatusEnabled),
  394. },
  395. },
  396. nil,
  397. )
  398. if err != nil {
  399. return "", "", err
  400. }
  401. tokResp, err := pollerResp.PollUntilDone(context.Background(), 2*time.Second)
  402. if err != nil {
  403. return "", "", err
  404. }
  405. registriesClient, err := armcontainerregistry.NewRegistriesClient(az.AzureSubscriptionID, cred, nil)
  406. if err != nil {
  407. return "", "", err
  408. }
  409. poller, err := registriesClient.BeginGenerateCredentials(
  410. context.Background(),
  411. az.ACRResourceGroupName,
  412. az.ACRName,
  413. armcontainerregistry.GenerateCredentialsParameters{
  414. TokenID: tokResp.ID,
  415. },
  416. &armcontainerregistry.RegistriesClientBeginGenerateCredentialsOptions{ResumeToken: ""})
  417. if err != nil {
  418. return "", "", err
  419. }
  420. genCredentialsResp, err := poller.PollUntilDone(context.Background(), 2*time.Second)
  421. if err != nil {
  422. return "", "", err
  423. }
  424. for i, tokPassword := range genCredentialsResp.Passwords {
  425. if i == 0 {
  426. az.ACRPassword1 = []byte(*tokPassword.Value)
  427. } else if i == 1 {
  428. az.ACRPassword2 = []byte(*tokPassword.Value)
  429. }
  430. }
  431. // update the az integration
  432. az, err = repo.AzureIntegration().OverwriteAzureIntegration(
  433. az,
  434. )
  435. if err != nil {
  436. return "", "", err
  437. }
  438. }
  439. return az.ACRTokenName, string(az.ACRPassword1), nil
  440. }
  441. func (r *Registry) listDOCRRepositories(
  442. repo repository.Repository,
  443. doAuth *oauth2.Config,
  444. ) ([]*ptypes.RegistryRepository, error) {
  445. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  446. r.ProjectID,
  447. r.DOIntegrationID,
  448. )
  449. if err != nil {
  450. return nil, err
  451. }
  452. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  453. if err != nil {
  454. return nil, err
  455. }
  456. client := godo.NewFromToken(tok)
  457. urlArr := strings.Split(r.URL, "/")
  458. if len(urlArr) != 2 {
  459. return nil, fmt.Errorf("invalid digital ocean registry url")
  460. }
  461. name := urlArr[1]
  462. repos, _, err := client.Registry.ListRepositories(context.TODO(), name, &godo.ListOptions{})
  463. if err != nil {
  464. return nil, err
  465. }
  466. res := make([]*ptypes.RegistryRepository, 0)
  467. for _, repo := range repos {
  468. res = append(res, &ptypes.RegistryRepository{
  469. Name: repo.Name,
  470. URI: r.URL + "/" + repo.Name,
  471. })
  472. }
  473. return res, nil
  474. }
  475. func (r *Registry) listPrivateRegistryRepositories(
  476. repo repository.Repository,
  477. ) ([]*ptypes.RegistryRepository, error) {
  478. // handle dockerhub different, as it doesn't implement the docker registry http api
  479. if strings.Contains(r.URL, "docker.io") {
  480. // in this case, we just return the single dockerhub repository that's linked
  481. res := make([]*ptypes.RegistryRepository, 0)
  482. res = append(res, &ptypes.RegistryRepository{
  483. Name: strings.Split(r.URL, "docker.io/")[1],
  484. URI: r.URL,
  485. })
  486. return res, nil
  487. }
  488. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  489. r.ProjectID,
  490. r.BasicIntegrationID,
  491. )
  492. if err != nil {
  493. return nil, err
  494. }
  495. // Just use service account key to authenticate, since scopes may not be in place
  496. // for oauth. This also prevents us from making more requests.
  497. client := &http.Client{}
  498. // get the host and scheme to make the request
  499. parsedURL, err := url.Parse(r.URL)
  500. req, err := http.NewRequest(
  501. "GET",
  502. fmt.Sprintf("%s://%s/v2/_catalog", parsedURL.Scheme, parsedURL.Host),
  503. nil,
  504. )
  505. if err != nil {
  506. return nil, err
  507. }
  508. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  509. resp, err := client.Do(req)
  510. if err != nil {
  511. return nil, err
  512. }
  513. // if the status code is 404, fallback to the Docker Hub implementation
  514. if resp.StatusCode == 404 {
  515. req, err := http.NewRequest(
  516. "GET",
  517. fmt.Sprintf("%s/", r.URL),
  518. nil,
  519. )
  520. if err != nil {
  521. return nil, err
  522. }
  523. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  524. resp, err = client.Do(req)
  525. if err != nil {
  526. return nil, err
  527. }
  528. }
  529. gcrResp := gcrRepositoryResp{}
  530. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  531. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  532. }
  533. res := make([]*ptypes.RegistryRepository, 0)
  534. if err != nil {
  535. return nil, err
  536. }
  537. for _, repo := range gcrResp.Repositories {
  538. res = append(res, &ptypes.RegistryRepository{
  539. Name: repo,
  540. URI: parsedURL.Host + "/" + repo,
  541. })
  542. }
  543. return res, nil
  544. }
  545. func (r *Registry) getTokenCacheFunc(
  546. repo repository.Repository,
  547. ) ints.GetTokenCacheFunc {
  548. return func() (tok *ints.TokenCache, err error) {
  549. reg, err := repo.Registry().ReadRegistry(r.ProjectID, r.ID)
  550. if err != nil {
  551. return nil, err
  552. }
  553. return &reg.TokenCache.TokenCache, nil
  554. }
  555. }
  556. func (r *Registry) setTokenCacheFunc(
  557. repo repository.Repository,
  558. ) ints.SetTokenCacheFunc {
  559. return func(token string, expiry time.Time) error {
  560. _, err := repo.Registry().UpdateRegistryTokenCache(
  561. &ints.RegTokenCache{
  562. TokenCache: ints.TokenCache{
  563. Token: []byte(token),
  564. Expiry: expiry,
  565. },
  566. RegistryID: r.ID,
  567. },
  568. )
  569. return err
  570. }
  571. }
  572. // CreateRepository creates a repository for a registry, if needed
  573. // (currently only required for ECR)
  574. func (r *Registry) CreateRepository(
  575. repo repository.Repository,
  576. name string,
  577. ) error {
  578. // if aws, create repository
  579. if r.AWSIntegrationID != 0 {
  580. return r.createECRRepository(repo, name)
  581. } else if r.GCPIntegrationID != 0 && strings.Contains(r.URL, "pkg.dev") {
  582. return r.createGARRepository(repo, name)
  583. }
  584. // otherwise, no-op
  585. return nil
  586. }
  587. func (r *Registry) createECRRepository(
  588. repo repository.Repository,
  589. name string,
  590. ) error {
  591. ctx := context.Background()
  592. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  593. r.ProjectID,
  594. r.AWSIntegrationID,
  595. )
  596. if err != nil {
  597. return err
  598. }
  599. svc := ecr.NewFromConfig(aws.Config())
  600. // determine if repository already exists
  601. _, err = svc.DescribeRepositories(ctx, &ecr.DescribeRepositoriesInput{
  602. RepositoryNames: []string{name},
  603. })
  604. if err != nil {
  605. // if the repository was not found, create it
  606. var nsk *ecrTypes.RegistryPolicyNotFoundException
  607. if errors.As(err, &nsk) {
  608. _, err = svc.CreateRepository(ctx, &ecr.CreateRepositoryInput{
  609. RepositoryName: &name,
  610. })
  611. if err != nil {
  612. return err
  613. }
  614. }
  615. return err
  616. }
  617. return nil
  618. }
  619. func (r *Registry) createGARRepository(
  620. repo repository.Repository,
  621. name string,
  622. ) error {
  623. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  624. r.ProjectID,
  625. r.GCPIntegrationID,
  626. )
  627. if err != nil {
  628. return err
  629. }
  630. client, err := artifactregistry.NewClient(context.Background(), option.WithTokenSource(&garTokenSource{
  631. reg: r,
  632. repo: repo,
  633. }), option.WithScopes("roles/artifactregistry.admin"))
  634. if err != nil {
  635. return err
  636. }
  637. defer client.Close()
  638. parsedURL, err := url.Parse("https://" + r.URL)
  639. if err != nil {
  640. return err
  641. }
  642. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  643. _, err = client.GetRepository(context.Background(), &artifactregistrypb.GetRepositoryRequest{
  644. Name: fmt.Sprintf("projects/%s/locations/%s/repositories/%s", gcpInt.GCPProjectID, location, name),
  645. })
  646. if err != nil && strings.Contains(err.Error(), "not found") {
  647. // create a new repository
  648. _, err := client.CreateRepository(context.Background(), &artifactregistrypb.CreateRepositoryRequest{
  649. Parent: fmt.Sprintf("projects/%s/locations/%s", gcpInt.GCPProjectID, location),
  650. RepositoryId: name,
  651. Repository: &artifactregistrypb.Repository{
  652. Format: artifactregistrypb.Repository_DOCKER,
  653. },
  654. })
  655. if err != nil {
  656. return err
  657. }
  658. } else if err != nil {
  659. return err
  660. }
  661. return nil
  662. }
  663. // ListImages lists the images for an image repository
  664. func (r *Registry) ListImages(
  665. repoName string,
  666. repo repository.Repository,
  667. doAuth *oauth2.Config, // only required if using DOCR
  668. ) ([]*ptypes.Image, error) {
  669. // switch on the auth mechanism to get a token
  670. if r.AWSIntegrationID != 0 {
  671. return r.listECRImages(repoName, repo)
  672. }
  673. if r.AzureIntegrationID != 0 {
  674. return r.listACRImages(repoName, repo)
  675. }
  676. if r.GCPIntegrationID != 0 {
  677. if strings.Contains(r.URL, "pkg.dev") {
  678. return r.listGARImages(repoName, repo)
  679. }
  680. return r.listGCRImages(repoName, repo)
  681. }
  682. if r.DOIntegrationID != 0 {
  683. return r.listDOCRImages(repoName, repo, doAuth)
  684. }
  685. if r.BasicIntegrationID != 0 {
  686. return r.listPrivateRegistryImages(repoName, repo)
  687. }
  688. return nil, fmt.Errorf("error listing images")
  689. }
  690. func (r *Registry) GetECRPaginatedImages(
  691. repoName string,
  692. repo repository.Repository,
  693. maxResults int64,
  694. nextToken *string,
  695. ) ([]*ptypes.Image, *string, error) {
  696. ctx := context.Background()
  697. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  698. r.ProjectID,
  699. r.AWSIntegrationID,
  700. )
  701. if err != nil {
  702. return nil, nil, err
  703. }
  704. svc := ecr.NewFromConfig(aws.Config())
  705. mr := int32(maxResults)
  706. resp, err := svc.ListImages(ctx, &ecr.ListImagesInput{
  707. RepositoryName: &repoName,
  708. MaxResults: &mr,
  709. NextToken: nextToken,
  710. })
  711. if err != nil {
  712. return nil, nil, err
  713. }
  714. if len(resp.ImageIds) == 0 {
  715. return []*ptypes.Image{}, nil, nil
  716. }
  717. imageIDLen := len(resp.ImageIds)
  718. imageDetails := make([]ecrTypes.ImageDetail, 0)
  719. imageIDMap := make(map[string]bool)
  720. for _, id := range resp.ImageIds {
  721. if id.ImageDigest != nil && id.ImageTag != nil {
  722. imageIDMap[*id.ImageTag] = true
  723. }
  724. }
  725. var wg sync.WaitGroup
  726. var mu sync.Mutex
  727. // AWS API expects the length of imageIDs to be at max 100 at a time
  728. for start := 0; start < imageIDLen; start += 100 {
  729. end := start + 100
  730. if end > imageIDLen {
  731. end = imageIDLen
  732. }
  733. wg.Add(1)
  734. go func(start, end int) {
  735. defer wg.Done()
  736. describeResp, err := svc.DescribeImages(ctx, &ecr.DescribeImagesInput{
  737. RepositoryName: &repoName,
  738. ImageIds: resp.ImageIds[start:end],
  739. })
  740. if err != nil {
  741. return
  742. }
  743. mu.Lock()
  744. imageDetails = append(imageDetails, describeResp.ImageDetails...)
  745. mu.Unlock()
  746. }(start, end)
  747. }
  748. wg.Wait()
  749. res := make([]*ptypes.Image, 0)
  750. imageInfoMap := make(map[string]*ptypes.Image)
  751. for _, img := range imageDetails {
  752. for _, tag := range img.ImageTags {
  753. newImage := &ptypes.Image{
  754. Digest: *img.ImageDigest,
  755. Tag: tag,
  756. RepositoryName: repoName,
  757. PushedAt: img.ImagePushedAt,
  758. }
  759. if _, ok := imageIDMap[tag]; ok {
  760. if _, ok := imageInfoMap[tag]; !ok {
  761. imageInfoMap[tag] = newImage
  762. }
  763. }
  764. if len(imageInfoMap) == int(maxResults) {
  765. break
  766. }
  767. }
  768. if len(imageInfoMap) == int(maxResults) {
  769. break
  770. }
  771. }
  772. for _, v := range imageInfoMap {
  773. res = append(res, v)
  774. }
  775. return res, resp.NextToken, nil
  776. }
  777. func (r *Registry) listECRImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  778. ctx := context.Background()
  779. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  780. r.ProjectID,
  781. r.AWSIntegrationID,
  782. )
  783. if err != nil {
  784. return nil, err
  785. }
  786. svc := ecr.NewFromConfig(aws.Config())
  787. maxResults := int64(1000)
  788. var imageIDs []ecrTypes.ImageIdentifier
  789. mr := int32(maxResults)
  790. resp, err := svc.ListImages(ctx, &ecr.ListImagesInput{
  791. RepositoryName: &repoName,
  792. MaxResults: &mr,
  793. })
  794. if err != nil {
  795. return nil, err
  796. }
  797. if len(resp.ImageIds) == 0 {
  798. return []*ptypes.Image{}, nil
  799. }
  800. imageIDs = append(imageIDs, resp.ImageIds...)
  801. nextToken := resp.NextToken
  802. for nextToken != nil {
  803. resp, err := svc.ListImages(ctx, &ecr.ListImagesInput{
  804. RepositoryName: &repoName,
  805. MaxResults: &mr,
  806. NextToken: nextToken,
  807. })
  808. if err != nil {
  809. return nil, err
  810. }
  811. imageIDs = append(imageIDs, resp.ImageIds...)
  812. nextToken = resp.NextToken
  813. }
  814. imageIDLen := len(imageIDs)
  815. imageDetails := make([]ecrTypes.ImageDetail, 0)
  816. var wg sync.WaitGroup
  817. var mu sync.Mutex
  818. // AWS API expects the length of imageIDs to be at max 100 at a time
  819. for start := 0; start < imageIDLen; start += 100 {
  820. end := start + 100
  821. if end > imageIDLen {
  822. end = imageIDLen
  823. }
  824. wg.Add(1)
  825. go func(start, end int) {
  826. defer wg.Done()
  827. describeResp, err := svc.DescribeImages(ctx, &ecr.DescribeImagesInput{
  828. RepositoryName: &repoName,
  829. ImageIds: imageIDs[start:end],
  830. })
  831. if err != nil {
  832. return
  833. }
  834. mu.Lock()
  835. imageDetails = append(imageDetails, describeResp.ImageDetails...)
  836. mu.Unlock()
  837. }(start, end)
  838. }
  839. wg.Wait()
  840. res := make([]*ptypes.Image, 0)
  841. imageInfoMap := make(map[string]*ptypes.Image)
  842. for _, img := range imageDetails {
  843. for _, tag := range img.ImageTags {
  844. newImage := &ptypes.Image{
  845. Digest: *img.ImageDigest,
  846. Tag: tag,
  847. RepositoryName: repoName,
  848. PushedAt: img.ImagePushedAt,
  849. }
  850. if _, ok := imageInfoMap[tag]; !ok {
  851. imageInfoMap[tag] = newImage
  852. }
  853. }
  854. }
  855. for _, v := range imageInfoMap {
  856. res = append(res, v)
  857. }
  858. return res, nil
  859. }
  860. func (r *Registry) listACRImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  861. az, err := repo.AzureIntegration().ReadAzureIntegration(
  862. r.ProjectID,
  863. r.AzureIntegrationID,
  864. )
  865. if err != nil {
  866. return nil, err
  867. }
  868. // use JWT token to request catalog
  869. client := &http.Client{}
  870. req, err := http.NewRequest(
  871. "GET",
  872. fmt.Sprintf("%s/v2/%s/tags/list", r.URL, repoName),
  873. nil,
  874. )
  875. if err != nil {
  876. return nil, err
  877. }
  878. req.SetBasicAuth(az.AzureClientID, string(az.ServicePrincipalSecret))
  879. resp, err := client.Do(req)
  880. if err != nil {
  881. return nil, err
  882. }
  883. gcrResp := gcrImageResp{}
  884. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  885. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  886. }
  887. res := make([]*ptypes.Image, 0)
  888. for _, tag := range gcrResp.Tags {
  889. res = append(res, &ptypes.Image{
  890. RepositoryName: strings.TrimPrefix(repoName, "https://"),
  891. Tag: tag,
  892. })
  893. }
  894. return res, nil
  895. }
  896. type gcrImageResp struct {
  897. Tags []string `json:"tags"`
  898. }
  899. func (r *Registry) listGCRImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  900. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  901. r.ProjectID,
  902. r.GCPIntegrationID,
  903. )
  904. if err != nil {
  905. return nil, err
  906. }
  907. // use JWT token to request catalog
  908. client := &http.Client{}
  909. parsedURL, err := url.Parse("https://" + r.URL)
  910. if err != nil {
  911. return nil, err
  912. }
  913. trimmedPath := strings.Trim(parsedURL.Path, "/")
  914. req, err := http.NewRequest(
  915. "GET",
  916. fmt.Sprintf("https://%s/v2/%s/%s/tags/list", parsedURL.Host, trimmedPath, repoName),
  917. nil,
  918. )
  919. if err != nil {
  920. return nil, err
  921. }
  922. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  923. resp, err := client.Do(req)
  924. if err != nil {
  925. return nil, err
  926. }
  927. gcrResp := gcrImageResp{}
  928. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  929. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  930. }
  931. res := make([]*ptypes.Image, 0)
  932. for _, tag := range gcrResp.Tags {
  933. res = append(res, &ptypes.Image{
  934. RepositoryName: repoName,
  935. Tag: tag,
  936. })
  937. }
  938. return res, nil
  939. }
  940. func (r *Registry) listGARImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  941. repoImageSlice := strings.Split(repoName, "/")
  942. if len(repoImageSlice) != 2 {
  943. return nil, fmt.Errorf("invalid GAR repo name: %s. Expected to be in the form of REPOSITORY/IMAGE", repoName)
  944. }
  945. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  946. r.ProjectID,
  947. r.GCPIntegrationID,
  948. )
  949. if err != nil {
  950. return nil, err
  951. }
  952. svc, err := v1artifactregistry.NewService(context.Background(), option.WithTokenSource(&garTokenSource{
  953. reg: r,
  954. repo: repo,
  955. }), option.WithScopes("roles/artifactregistry.reader"))
  956. if err != nil {
  957. return nil, err
  958. }
  959. var res []*ptypes.Image
  960. parsedURL, err := url.Parse("https://" + r.URL)
  961. if err != nil {
  962. return nil, err
  963. }
  964. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  965. dockerSvc := v1artifactregistry.NewProjectsLocationsRepositoriesDockerImagesService(svc)
  966. nextToken := ""
  967. for {
  968. resp, err := dockerSvc.List(fmt.Sprintf("projects/%s/locations/%s/repositories/%s",
  969. gcpInt.GCPProjectID, location, repoImageSlice[0])).PageSize(1000).PageToken(nextToken).Do()
  970. if err != nil {
  971. return nil, err
  972. }
  973. for _, image := range resp.DockerImages {
  974. named, err := reference.ParseNamed(image.Uri)
  975. if err != nil {
  976. continue
  977. }
  978. paths := strings.Split(reference.Path(named), "/")
  979. imageName := paths[len(paths)-1]
  980. if imageName == repoImageSlice[1] {
  981. uploadTime, _ := time.Parse(time.RFC3339, image.UploadTime)
  982. for _, tag := range image.Tags {
  983. res = append(res, &ptypes.Image{
  984. RepositoryName: repoName,
  985. Tag: tag,
  986. PushedAt: &uploadTime,
  987. Digest: strings.Split(image.Uri, "@")[1],
  988. })
  989. }
  990. }
  991. }
  992. if resp.NextPageToken == "" {
  993. break
  994. }
  995. nextToken = resp.NextPageToken
  996. }
  997. return res, nil
  998. }
  999. func (r *Registry) listDOCRImages(
  1000. repoName string,
  1001. repo repository.Repository,
  1002. doAuth *oauth2.Config,
  1003. ) ([]*ptypes.Image, error) {
  1004. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  1005. r.ProjectID,
  1006. r.DOIntegrationID,
  1007. )
  1008. if err != nil {
  1009. return nil, err
  1010. }
  1011. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  1012. if err != nil {
  1013. return nil, err
  1014. }
  1015. client := godo.NewFromToken(tok)
  1016. urlArr := strings.Split(r.URL, "/")
  1017. if len(urlArr) != 2 {
  1018. return nil, fmt.Errorf("invalid digital ocean registry url")
  1019. }
  1020. name := urlArr[1]
  1021. var tags []*godo.RepositoryTag
  1022. opt := &godo.ListOptions{
  1023. PerPage: 200,
  1024. }
  1025. for {
  1026. nextTags, resp, err := client.Registry.ListRepositoryTags(context.TODO(), name, repoName, opt)
  1027. if err != nil {
  1028. return nil, err
  1029. }
  1030. tags = append(tags, nextTags...)
  1031. if resp.Links == nil || resp.Links.IsLastPage() {
  1032. break
  1033. }
  1034. page, err := resp.Links.CurrentPage()
  1035. if err != nil {
  1036. return nil, err
  1037. }
  1038. opt.Page = page + 1
  1039. }
  1040. res := make([]*ptypes.Image, 0)
  1041. for _, tag := range tags {
  1042. res = append(res, &ptypes.Image{
  1043. RepositoryName: repoName,
  1044. Tag: tag.Tag,
  1045. })
  1046. }
  1047. return res, nil
  1048. }
  1049. func (r *Registry) listPrivateRegistryImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1050. // handle dockerhub different, as it doesn't implement the docker registry http api
  1051. if strings.Contains(r.URL, "docker.io") {
  1052. return r.listDockerHubImages(repoName, repo)
  1053. }
  1054. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1055. r.ProjectID,
  1056. r.BasicIntegrationID,
  1057. )
  1058. if err != nil {
  1059. return nil, err
  1060. }
  1061. // Just use service account key to authenticate, since scopes may not be in place
  1062. // for oauth. This also prevents us from making more requests.
  1063. client := &http.Client{}
  1064. // get the host and scheme to make the request
  1065. parsedURL, err := url.Parse(r.URL)
  1066. req, err := http.NewRequest(
  1067. "GET",
  1068. fmt.Sprintf("%s://%s/v2/%s/tags/list", parsedURL.Scheme, parsedURL.Host, repoName),
  1069. nil,
  1070. )
  1071. if err != nil {
  1072. return nil, err
  1073. }
  1074. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  1075. resp, err := client.Do(req)
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. gcrResp := gcrImageResp{}
  1080. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  1081. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  1082. }
  1083. res := make([]*ptypes.Image, 0)
  1084. for _, tag := range gcrResp.Tags {
  1085. res = append(res, &ptypes.Image{
  1086. RepositoryName: repoName,
  1087. Tag: tag,
  1088. })
  1089. }
  1090. return res, nil
  1091. }
  1092. type dockerHubImageResult struct {
  1093. Name string `json:"name"`
  1094. }
  1095. type dockerHubImageResp struct {
  1096. Results []dockerHubImageResult `json:"results"`
  1097. }
  1098. type dockerHubLoginReq struct {
  1099. Username string `json:"username"`
  1100. Password string `json:"password"`
  1101. }
  1102. type dockerHubLoginResp struct {
  1103. Token string `json:"token"`
  1104. }
  1105. func (r *Registry) listDockerHubImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1106. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1107. r.ProjectID,
  1108. r.BasicIntegrationID,
  1109. )
  1110. if err != nil {
  1111. return nil, err
  1112. }
  1113. client := &http.Client{}
  1114. // first, make a request for the access token
  1115. data, err := json.Marshal(&dockerHubLoginReq{
  1116. Username: string(basic.Username),
  1117. Password: string(basic.Password),
  1118. })
  1119. if err != nil {
  1120. return nil, err
  1121. }
  1122. req, err := http.NewRequest(
  1123. "POST",
  1124. "https://hub.docker.com/v2/users/login",
  1125. strings.NewReader(string(data)),
  1126. )
  1127. if err != nil {
  1128. return nil, err
  1129. }
  1130. req.Header.Add("Content-Type", "application/json")
  1131. resp, err := client.Do(req)
  1132. if err != nil {
  1133. return nil, err
  1134. }
  1135. tokenObj := dockerHubLoginResp{}
  1136. if err := json.NewDecoder(resp.Body).Decode(&tokenObj); err != nil {
  1137. return nil, fmt.Errorf("Could not decode Dockerhub token from response: %v", err)
  1138. }
  1139. req, err = http.NewRequest(
  1140. "GET",
  1141. fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/tags", strings.Split(r.URL, "docker.io/")[1]),
  1142. nil,
  1143. )
  1144. if err != nil {
  1145. return nil, err
  1146. }
  1147. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tokenObj.Token))
  1148. resp, err = client.Do(req)
  1149. if err != nil {
  1150. return nil, err
  1151. }
  1152. imageResp := dockerHubImageResp{}
  1153. if err := json.NewDecoder(resp.Body).Decode(&imageResp); err != nil {
  1154. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  1155. }
  1156. res := make([]*ptypes.Image, 0)
  1157. for _, result := range imageResp.Results {
  1158. res = append(res, &ptypes.Image{
  1159. RepositoryName: repoName,
  1160. Tag: result.Name,
  1161. })
  1162. }
  1163. return res, nil
  1164. }
  1165. // GetDockerConfigJSON returns a dockerconfigjson file contents with "auths"
  1166. // populated.
  1167. func (r *Registry) GetDockerConfigJSON(
  1168. repo repository.Repository,
  1169. doAuth *oauth2.Config, // only required if using DOCR
  1170. ) ([]byte, error) {
  1171. var conf *configfile.ConfigFile
  1172. var err error
  1173. // switch on the auth mechanism to get a token
  1174. if r.AWSIntegrationID != 0 {
  1175. conf, err = r.getECRDockerConfigFile(repo)
  1176. }
  1177. if r.GCPIntegrationID != 0 {
  1178. conf, err = r.getGCRDockerConfigFile(repo)
  1179. }
  1180. if r.DOIntegrationID != 0 {
  1181. conf, err = r.getDOCRDockerConfigFile(repo, doAuth)
  1182. }
  1183. if r.BasicIntegrationID != 0 {
  1184. conf, err = r.getPrivateRegistryDockerConfigFile(repo)
  1185. }
  1186. if r.AzureIntegrationID != 0 {
  1187. conf, err = r.getACRDockerConfigFile(repo)
  1188. }
  1189. if err != nil {
  1190. return nil, err
  1191. }
  1192. return json.Marshal(conf)
  1193. }
  1194. func (r *Registry) getECRDockerConfigFile(
  1195. repo repository.Repository,
  1196. ) (*configfile.ConfigFile, error) {
  1197. ctx := context.Background()
  1198. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  1199. r.ProjectID,
  1200. r.AWSIntegrationID,
  1201. )
  1202. if err != nil {
  1203. return nil, err
  1204. }
  1205. svc := ecr.NewFromConfig(aws.Config())
  1206. output, err := svc.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
  1207. if err != nil {
  1208. return nil, err
  1209. }
  1210. token := *output.AuthorizationData[0].AuthorizationToken
  1211. decodedToken, err := base64.StdEncoding.DecodeString(token)
  1212. if err != nil {
  1213. return nil, err
  1214. }
  1215. parts := strings.SplitN(string(decodedToken), ":", 2)
  1216. if len(parts) < 2 {
  1217. return nil, err
  1218. }
  1219. key := r.URL
  1220. if !strings.Contains(key, "http") {
  1221. key = "https://" + key
  1222. }
  1223. return &configfile.ConfigFile{
  1224. AuthConfigs: map[string]types.AuthConfig{
  1225. key: {
  1226. Username: parts[0],
  1227. Password: parts[1],
  1228. Auth: token,
  1229. },
  1230. },
  1231. }, nil
  1232. }
  1233. func (r *Registry) getGCRDockerConfigFile(
  1234. repo repository.Repository,
  1235. ) (*configfile.ConfigFile, error) {
  1236. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  1237. r.ProjectID,
  1238. r.GCPIntegrationID,
  1239. )
  1240. if err != nil {
  1241. return nil, err
  1242. }
  1243. key := r.URL
  1244. if !strings.Contains(key, "http") {
  1245. key = "https://" + key
  1246. }
  1247. parsedURL, _ := url.Parse(key)
  1248. return &configfile.ConfigFile{
  1249. AuthConfigs: map[string]types.AuthConfig{
  1250. parsedURL.Host: {
  1251. Username: "_json_key",
  1252. Password: string(gcp.GCPKeyData),
  1253. Auth: generateAuthToken("_json_key", string(gcp.GCPKeyData)),
  1254. },
  1255. },
  1256. }, nil
  1257. }
  1258. func (r *Registry) getDOCRDockerConfigFile(
  1259. repo repository.Repository,
  1260. doAuth *oauth2.Config,
  1261. ) (*configfile.ConfigFile, error) {
  1262. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  1263. r.ProjectID,
  1264. r.DOIntegrationID,
  1265. )
  1266. if err != nil {
  1267. return nil, err
  1268. }
  1269. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  1270. if err != nil {
  1271. return nil, err
  1272. }
  1273. key := r.URL
  1274. if !strings.Contains(key, "http") {
  1275. key = "https://" + key
  1276. }
  1277. parsedURL, _ := url.Parse(key)
  1278. return &configfile.ConfigFile{
  1279. AuthConfigs: map[string]types.AuthConfig{
  1280. parsedURL.Host: {
  1281. Username: tok,
  1282. Password: tok,
  1283. Auth: generateAuthToken(tok, tok),
  1284. },
  1285. },
  1286. }, nil
  1287. }
  1288. func (r *Registry) getPrivateRegistryDockerConfigFile(
  1289. repo repository.Repository,
  1290. ) (*configfile.ConfigFile, error) {
  1291. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1292. r.ProjectID,
  1293. r.BasicIntegrationID,
  1294. )
  1295. if err != nil {
  1296. return nil, err
  1297. }
  1298. key := r.URL
  1299. if !strings.Contains(key, "http") {
  1300. key = "https://" + key
  1301. }
  1302. parsedURL, _ := url.Parse(key)
  1303. authConfigKey := parsedURL.Host
  1304. if strings.Contains(r.URL, "index.docker.io") {
  1305. authConfigKey = "https://index.docker.io/v1/"
  1306. }
  1307. return &configfile.ConfigFile{
  1308. AuthConfigs: map[string]types.AuthConfig{
  1309. authConfigKey: {
  1310. Username: string(basic.Username),
  1311. Password: string(basic.Password),
  1312. Auth: generateAuthToken(string(basic.Username), string(basic.Password)),
  1313. },
  1314. },
  1315. }, nil
  1316. }
  1317. func (r *Registry) getACRDockerConfigFile(
  1318. repo repository.Repository,
  1319. ) (*configfile.ConfigFile, error) {
  1320. username, pw, err := r.GetACRCredentials(repo)
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. key := r.URL
  1325. if !strings.Contains(key, "http") {
  1326. key = "https://" + key
  1327. }
  1328. parsedURL, _ := url.Parse(key)
  1329. return &configfile.ConfigFile{
  1330. AuthConfigs: map[string]types.AuthConfig{
  1331. parsedURL.Host: {
  1332. Username: string(username),
  1333. Password: string(pw),
  1334. Auth: generateAuthToken(string(username), string(pw)),
  1335. },
  1336. },
  1337. }, nil
  1338. }
  1339. func generateAuthToken(username, password string) string {
  1340. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  1341. }