registry.go 45 KB

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