registry.go 40 KB

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