registry.go 37 KB

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