registry.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925
  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. "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
  16. "github.com/aws/aws-sdk-go/aws/awserr"
  17. "github.com/aws/aws-sdk-go/service/ecr"
  18. "github.com/bufbuild/connect-go"
  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.CapiProvisionerEnabled {
  125. // TODO: Remove this conditional when AWS list repos is supported in CCP
  126. if strings.Contains(r.URL, ".azurecr.") {
  127. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "auth-mechanism", Value: "capi-azure"})
  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 ecr 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. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "auth-mechanism", Value: "capi-aws"})
  150. uri := strings.TrimPrefix(r.URL, "https://")
  151. splits := strings.Split(uri, ".")
  152. if len(splits) < 4 {
  153. return nil, telemetry.Error(ctx, span, nil, "uri does not have enough splits")
  154. }
  155. accountID := splits[0]
  156. region := splits[3]
  157. req := connect.NewRequest(&porterv1.AssumeRoleCredentialsRequest{
  158. ProjectId: int64(r.ProjectID),
  159. AwsAccountId: accountID,
  160. })
  161. creds, err := conf.ClusterControlPlaneClient.AssumeRoleCredentials(ctx, req)
  162. if err != nil {
  163. return nil, telemetry.Error(ctx, span, err, "error getting capi credentials for registry")
  164. }
  165. aws := &ints.AWSIntegration{
  166. AWSAccessKeyID: []byte(creds.Msg.AwsAccessId),
  167. AWSSecretAccessKey: []byte(creds.Msg.AwsSecretKey),
  168. AWSSessionToken: []byte(creds.Msg.AwsSessionToken),
  169. AWSRegion: region,
  170. }
  171. repos, err := r.listECRRepositories(aws)
  172. if err != nil {
  173. return nil, telemetry.Error(ctx, span, err, "error listing ecr repositories")
  174. }
  175. return repos, nil
  176. }
  177. }
  178. return nil, telemetry.Error(ctx, span, nil, "error listing repositories")
  179. }
  180. type gcrJWT struct {
  181. AccessToken string `json:"token"`
  182. ExpiresInSec int `json:"expires_in"`
  183. }
  184. type gcrErr struct {
  185. Code string `json:"code"`
  186. Message string `json:"message"`
  187. }
  188. type gcrRepositoryResp struct {
  189. Repositories []string `json:"repositories"`
  190. Errors []gcrErr `json:"errors"`
  191. }
  192. func (r *Registry) GetGCRToken(ctx context.Context, repo repository.Repository) (*oauth2.Token, error) {
  193. getTokenCache := r.getTokenCacheFunc(ctx, repo)
  194. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  195. r.ProjectID,
  196. r.GCPIntegrationID,
  197. )
  198. if err != nil {
  199. return nil, err
  200. }
  201. // get oauth2 access token
  202. return gcp.GetBearerToken(
  203. ctx,
  204. getTokenCache,
  205. r.setTokenCacheFunc(ctx, repo),
  206. "https://www.googleapis.com/auth/devstorage.read_write",
  207. )
  208. }
  209. func (r *Registry) listGCRRepositories(
  210. repo repository.Repository,
  211. ) ([]*ptypes.RegistryRepository, error) {
  212. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  213. r.ProjectID,
  214. r.GCPIntegrationID,
  215. )
  216. if err != nil {
  217. return nil, err
  218. }
  219. // Just use service account key to authenticate, since scopes may not be in place
  220. // for oauth. This also prevents us from making more requests.
  221. client := &http.Client{}
  222. regURL := r.URL
  223. if !strings.HasPrefix(regURL, "http") {
  224. regURL = fmt.Sprintf("https://%s", regURL)
  225. }
  226. regURLParsed, err := url.Parse(regURL)
  227. regHostname := "gcr.io"
  228. if err == nil {
  229. regHostname = regURLParsed.Host
  230. }
  231. req, err := http.NewRequest(
  232. "GET",
  233. fmt.Sprintf("https://%s/v2/_catalog", regHostname),
  234. nil,
  235. )
  236. if err != nil {
  237. return nil, err
  238. }
  239. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  240. resp, err := client.Do(req)
  241. if err != nil {
  242. return nil, err
  243. }
  244. gcrResp := gcrRepositoryResp{}
  245. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  246. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  247. }
  248. if len(gcrResp.Errors) > 0 {
  249. errMsg := ""
  250. for _, gcrErr := range gcrResp.Errors {
  251. errMsg += fmt.Sprintf(": Code %s, message %s", gcrErr.Code, gcrErr.Message)
  252. }
  253. return nil, fmt.Errorf(errMsg)
  254. }
  255. res := make([]*ptypes.RegistryRepository, 0)
  256. parsedURL, err := url.Parse("https://" + r.URL)
  257. if err != nil {
  258. return nil, err
  259. }
  260. for _, repo := range gcrResp.Repositories {
  261. res = append(res, &ptypes.RegistryRepository{
  262. Name: repo,
  263. URI: parsedURL.Host + "/" + repo,
  264. })
  265. }
  266. return res, nil
  267. }
  268. func (r *Registry) GetGARToken(ctx context.Context, repo repository.Repository) (*oauth2.Token, error) {
  269. getTokenCache := r.getTokenCacheFunc(ctx, repo)
  270. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  271. r.ProjectID,
  272. r.GCPIntegrationID,
  273. )
  274. if err != nil {
  275. return nil, err
  276. }
  277. // get oauth2 access token
  278. return gcp.GetBearerToken(
  279. ctx,
  280. getTokenCache,
  281. r.setTokenCacheFunc(ctx, repo),
  282. "https://www.googleapis.com/auth/cloud-platform",
  283. )
  284. }
  285. type garTokenSource struct {
  286. // ctx is only passed in here as the oauth2.Token() doesnt support contexts
  287. ctx context.Context
  288. reg *Registry
  289. repo repository.Repository
  290. }
  291. func (source *garTokenSource) Token() (*oauth2.Token, error) {
  292. return source.reg.GetGARToken(source.ctx, source.repo)
  293. }
  294. // GAR has the concept of a "repository" which is a collection of images, unlike ECR or others
  295. // where a repository is a single image. This function returns the list of fully qualified names
  296. // of GAR images including their repository names.
  297. func (r *Registry) listGARRepositories(
  298. ctx context.Context,
  299. repo repository.Repository,
  300. ) ([]*ptypes.RegistryRepository, error) {
  301. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  302. r.ProjectID,
  303. r.GCPIntegrationID,
  304. )
  305. if err != nil {
  306. return nil, err
  307. }
  308. client, err := artifactregistry.NewClient(ctx, option.WithTokenSource(&garTokenSource{
  309. reg: r,
  310. repo: repo,
  311. ctx: ctx,
  312. }), option.WithScopes("roles/artifactregistry.reader"))
  313. if err != nil {
  314. return nil, err
  315. }
  316. var repoNames []string
  317. nextToken := ""
  318. parsedURL, err := url.Parse("https://" + r.URL)
  319. if err != nil {
  320. return nil, err
  321. }
  322. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  323. for {
  324. it := client.ListRepositories(context.Background(), &artifactregistrypb.ListRepositoriesRequest{
  325. Parent: fmt.Sprintf("projects/%s/locations/%s", gcpInt.GCPProjectID, location),
  326. PageSize: 1000,
  327. PageToken: nextToken,
  328. })
  329. for {
  330. resp, err := it.Next()
  331. if err == iterator.Done {
  332. break
  333. } else if err != nil {
  334. return nil, err
  335. }
  336. if resp.GetFormat() == artifactregistrypb.Repository_DOCKER { // we only care about
  337. repoSlice := strings.Split(resp.GetName(), "/")
  338. repoName := repoSlice[len(repoSlice)-1]
  339. repoNames = append(repoNames, repoName)
  340. }
  341. }
  342. if it.PageInfo().Token == "" {
  343. break
  344. }
  345. nextToken = it.PageInfo().Token
  346. }
  347. svc, err := v1artifactregistry.NewService(ctx, option.WithTokenSource(&garTokenSource{
  348. reg: r,
  349. repo: repo,
  350. ctx: ctx,
  351. }), option.WithScopes("roles/artifactregistry.reader"))
  352. if err != nil {
  353. return nil, err
  354. }
  355. nextToken = ""
  356. dockerSvc := v1artifactregistry.NewProjectsLocationsRepositoriesDockerImagesService(svc)
  357. var (
  358. wg sync.WaitGroup
  359. resMap sync.Map
  360. )
  361. for _, repoName := range repoNames {
  362. wg.Add(1)
  363. go func(repoName string) {
  364. defer wg.Done()
  365. for {
  366. resp, err := dockerSvc.List(fmt.Sprintf("projects/%s/locations/%s/repositories/%s",
  367. gcpInt.GCPProjectID, location, repoName)).PageSize(1000).PageToken(nextToken).Do()
  368. if err != nil {
  369. // FIXME: we should report this error using a channel
  370. return
  371. }
  372. for _, image := range resp.DockerImages {
  373. named, err := reference.ParseNamed(image.Uri)
  374. if err != nil {
  375. // let us skip this image becaue it has a malformed URI coming from the GCP API
  376. continue
  377. }
  378. uploadTime, _ := time.Parse(time.RFC3339, image.UploadTime)
  379. resMap.Store(named.Name(), &ptypes.RegistryRepository{
  380. Name: repoName,
  381. URI: named.Name(),
  382. CreatedAt: uploadTime,
  383. })
  384. }
  385. if resp.NextPageToken == "" {
  386. break
  387. }
  388. nextToken = resp.NextPageToken
  389. }
  390. }(repoName)
  391. }
  392. wg.Wait()
  393. var res []*ptypes.RegistryRepository
  394. resMap.Range(func(_, value any) bool {
  395. res = append(res, value.(*ptypes.RegistryRepository))
  396. return true
  397. })
  398. return res, nil
  399. }
  400. func (r *Registry) listECRRepositories(aws *ints.AWSIntegration) ([]*ptypes.RegistryRepository, error) {
  401. sess, err := aws.GetSession()
  402. if err != nil {
  403. return nil, err
  404. }
  405. svc := ecr.New(sess)
  406. resp, err := svc.DescribeRepositories(&ecr.DescribeRepositoriesInput{})
  407. if err != nil {
  408. return nil, err
  409. }
  410. res := make([]*ptypes.RegistryRepository, 0)
  411. for _, repo := range resp.Repositories {
  412. res = append(res, &ptypes.RegistryRepository{
  413. Name: *repo.RepositoryName,
  414. CreatedAt: *repo.CreatedAt,
  415. URI: *repo.RepositoryUri,
  416. })
  417. }
  418. return res, nil
  419. }
  420. type acrRepositoryResp struct {
  421. Repositories []string `json:"repositories"`
  422. }
  423. func (r *Registry) listACRRepositories(ctx context.Context, repo repository.Repository) ([]*ptypes.RegistryRepository, error) {
  424. ctx, span := telemetry.NewSpan(ctx, "list-acr-repositories")
  425. defer span.End()
  426. telemetry.WithAttributes(span,
  427. telemetry.AttributeKV{Key: "registry-name", Value: r.Name},
  428. telemetry.AttributeKV{Key: "registry-id", Value: r.ID},
  429. telemetry.AttributeKV{Key: "project-id", Value: r.ProjectID},
  430. )
  431. az, err := repo.AzureIntegration().ReadAzureIntegration(
  432. r.ProjectID,
  433. r.AzureIntegrationID,
  434. )
  435. if err != nil {
  436. return nil, telemetry.Error(ctx, span, err, "error reading azure integration")
  437. }
  438. client := &http.Client{}
  439. acrURL := r.URL
  440. if !strings.Contains(acrURL, "http") {
  441. acrURL = fmt.Sprintf("https://%s", acrURL)
  442. }
  443. req, err := http.NewRequest(
  444. "GET",
  445. fmt.Sprintf("%s/v2/_catalog", acrURL),
  446. nil,
  447. )
  448. if err != nil {
  449. return nil, telemetry.Error(ctx, span, err, "error getting http request")
  450. }
  451. req.SetBasicAuth(az.AzureClientID, string(az.ServicePrincipalSecret))
  452. resp, err := client.Do(req)
  453. if err != nil {
  454. return nil, telemetry.Error(ctx, span, err, "error making http call")
  455. }
  456. acrResp := acrRepositoryResp{}
  457. if err := json.NewDecoder(resp.Body).Decode(&acrResp); err != nil {
  458. return nil, telemetry.Error(ctx, span, err, "could not read Azure registry repository response")
  459. }
  460. res := make([]*ptypes.RegistryRepository, 0)
  461. for _, repo := range acrResp.Repositories {
  462. res = append(res, &ptypes.RegistryRepository{
  463. Name: repo,
  464. URI: strings.TrimPrefix(r.URL, "https://") + "/" + repo,
  465. })
  466. }
  467. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "repo-count", Value: len(acrResp.Repositories)})
  468. return res, nil
  469. }
  470. // Returns the username/password pair for the registry
  471. func (r *Registry) GetACRCredentials(repo repository.Repository) (string, string, error) {
  472. az, err := repo.AzureIntegration().ReadAzureIntegration(
  473. r.ProjectID,
  474. r.AzureIntegrationID,
  475. )
  476. if err != nil {
  477. return "", "", err
  478. }
  479. // if the passwords and name aren't set, generate them
  480. if az.ACRTokenName == "" || len(az.ACRPassword1) == 0 {
  481. az.ACRTokenName = "porter-acr-token"
  482. // create an acr repo token
  483. cred, err := azidentity.NewClientSecretCredential(az.AzureTenantID, az.AzureClientID, string(az.ServicePrincipalSecret), nil)
  484. if err != nil {
  485. return "", "", err
  486. }
  487. scopeMapsClient, err := armcontainerregistry.NewScopeMapsClient(az.AzureSubscriptionID, cred, nil)
  488. if err != nil {
  489. return "", "", err
  490. }
  491. smRes, err := scopeMapsClient.Get(
  492. context.Background(),
  493. az.ACRResourceGroupName,
  494. az.ACRName,
  495. "_repositories_admin",
  496. nil,
  497. )
  498. if err != nil {
  499. return "", "", err
  500. }
  501. tokensClient, err := armcontainerregistry.NewTokensClient(az.AzureSubscriptionID, cred, nil)
  502. if err != nil {
  503. return "", "", err
  504. }
  505. pollerResp, err := tokensClient.BeginCreate(
  506. context.Background(),
  507. az.ACRResourceGroupName,
  508. az.ACRName,
  509. "porter-acr-token",
  510. armcontainerregistry.Token{
  511. Properties: &armcontainerregistry.TokenProperties{
  512. ScopeMapID: smRes.ID,
  513. Status: to.Ptr(armcontainerregistry.TokenStatusEnabled),
  514. },
  515. },
  516. nil,
  517. )
  518. if err != nil {
  519. return "", "", err
  520. }
  521. tokResp, err := pollerResp.PollUntilDone(context.Background(), 2*time.Second)
  522. if err != nil {
  523. return "", "", err
  524. }
  525. registriesClient, err := armcontainerregistry.NewRegistriesClient(az.AzureSubscriptionID, cred, nil)
  526. if err != nil {
  527. return "", "", err
  528. }
  529. poller, err := registriesClient.BeginGenerateCredentials(
  530. context.Background(),
  531. az.ACRResourceGroupName,
  532. az.ACRName,
  533. armcontainerregistry.GenerateCredentialsParameters{
  534. TokenID: tokResp.ID,
  535. },
  536. &armcontainerregistry.RegistriesClientBeginGenerateCredentialsOptions{ResumeToken: ""})
  537. if err != nil {
  538. return "", "", err
  539. }
  540. genCredentialsResp, err := poller.PollUntilDone(context.Background(), 2*time.Second)
  541. if err != nil {
  542. return "", "", err
  543. }
  544. for i, tokPassword := range genCredentialsResp.Passwords {
  545. if i == 0 {
  546. az.ACRPassword1 = []byte(*tokPassword.Value)
  547. } else if i == 1 {
  548. az.ACRPassword2 = []byte(*tokPassword.Value)
  549. }
  550. }
  551. // update the az integration
  552. az, err = repo.AzureIntegration().OverwriteAzureIntegration(
  553. az,
  554. )
  555. if err != nil {
  556. return "", "", err
  557. }
  558. }
  559. return az.ACRTokenName, string(az.ACRPassword1), nil
  560. }
  561. func (r *Registry) listDOCRRepositories(
  562. repo repository.Repository,
  563. doAuth *oauth2.Config,
  564. ) ([]*ptypes.RegistryRepository, error) {
  565. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  566. r.ProjectID,
  567. r.DOIntegrationID,
  568. )
  569. if err != nil {
  570. return nil, err
  571. }
  572. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  573. if err != nil {
  574. return nil, err
  575. }
  576. client := godo.NewFromToken(tok)
  577. urlArr := strings.Split(r.URL, "/")
  578. if len(urlArr) != 2 {
  579. return nil, fmt.Errorf("invalid digital ocean registry url")
  580. }
  581. name := urlArr[1]
  582. repos, _, err := client.Registry.ListRepositories(context.TODO(), name, &godo.ListOptions{})
  583. if err != nil {
  584. return nil, err
  585. }
  586. res := make([]*ptypes.RegistryRepository, 0)
  587. for _, repo := range repos {
  588. res = append(res, &ptypes.RegistryRepository{
  589. Name: repo.Name,
  590. URI: r.URL + "/" + repo.Name,
  591. })
  592. }
  593. return res, nil
  594. }
  595. func (r *Registry) listPrivateRegistryRepositories(
  596. repo repository.Repository,
  597. ) ([]*ptypes.RegistryRepository, error) {
  598. // handle dockerhub different, as it doesn't implement the docker registry http api
  599. if strings.Contains(r.URL, "docker.io") {
  600. // in this case, we just return the single dockerhub repository that's linked
  601. res := make([]*ptypes.RegistryRepository, 0)
  602. res = append(res, &ptypes.RegistryRepository{
  603. Name: strings.Split(r.URL, "docker.io/")[1],
  604. URI: r.URL,
  605. })
  606. return res, nil
  607. }
  608. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  609. r.ProjectID,
  610. r.BasicIntegrationID,
  611. )
  612. if err != nil {
  613. return nil, err
  614. }
  615. // Just use service account key to authenticate, since scopes may not be in place
  616. // for oauth. This also prevents us from making more requests.
  617. client := &http.Client{}
  618. // get the host and scheme to make the request
  619. parsedURL, err := url.Parse(r.URL)
  620. req, err := http.NewRequest(
  621. "GET",
  622. fmt.Sprintf("%s://%s/v2/_catalog", parsedURL.Scheme, parsedURL.Host),
  623. nil,
  624. )
  625. if err != nil {
  626. return nil, err
  627. }
  628. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  629. resp, err := client.Do(req)
  630. if err != nil {
  631. return nil, err
  632. }
  633. // if the status code is 404, fallback to the Docker Hub implementation
  634. if resp.StatusCode == 404 {
  635. req, err := http.NewRequest(
  636. "GET",
  637. fmt.Sprintf("%s/", r.URL),
  638. nil,
  639. )
  640. if err != nil {
  641. return nil, err
  642. }
  643. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  644. resp, err = client.Do(req)
  645. if err != nil {
  646. return nil, err
  647. }
  648. }
  649. gcrResp := gcrRepositoryResp{}
  650. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  651. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  652. }
  653. res := make([]*ptypes.RegistryRepository, 0)
  654. if err != nil {
  655. return nil, err
  656. }
  657. for _, repo := range gcrResp.Repositories {
  658. res = append(res, &ptypes.RegistryRepository{
  659. Name: repo,
  660. URI: parsedURL.Host + "/" + repo,
  661. })
  662. }
  663. return res, nil
  664. }
  665. func (r *Registry) getTokenCacheFunc(
  666. ctx context.Context,
  667. repo repository.Repository,
  668. ) ints.GetTokenCacheFunc {
  669. return func(ctx context.Context) (tok *ints.TokenCache, err error) {
  670. reg, err := repo.Registry().ReadRegistry(r.ProjectID, r.ID)
  671. if err != nil {
  672. return nil, err
  673. }
  674. return &reg.TokenCache.TokenCache, nil
  675. }
  676. }
  677. func (r *Registry) setTokenCacheFunc(
  678. ctx context.Context,
  679. repo repository.Repository,
  680. ) ints.SetTokenCacheFunc {
  681. return func(ctx context.Context, token string, expiry time.Time) error {
  682. _, err := repo.Registry().UpdateRegistryTokenCache(
  683. &ints.RegTokenCache{
  684. TokenCache: ints.TokenCache{
  685. Token: []byte(token),
  686. Expiry: expiry,
  687. },
  688. RegistryID: r.ID,
  689. },
  690. )
  691. return err
  692. }
  693. }
  694. // CreateRepository creates a repository for a registry, if needed
  695. // (currently only required for ECR)
  696. func (r *Registry) CreateRepository(
  697. ctx context.Context,
  698. conf *config.Config,
  699. name string,
  700. ) error {
  701. ctx, span := telemetry.NewSpan(ctx, "create-repository")
  702. defer span.End()
  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.CapiProvisionerEnabled {
  731. // no need to create repository if pushing to ACR
  732. if strings.Contains(r.URL, ".azurecr.") {
  733. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "skipping-create-because-azure", 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.CapiProvisionerEnabled {
  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. }