registry.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  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. // if aws, create repository
  702. if r.AWSIntegrationID != 0 {
  703. aws, err := conf.Repo.AWSIntegration().ReadAWSIntegration(
  704. r.ProjectID,
  705. r.AWSIntegrationID,
  706. )
  707. if err != nil {
  708. return err
  709. }
  710. return r.createECRRepository(aws, name)
  711. } else if r.GCPIntegrationID != 0 && strings.Contains(r.URL, "pkg.dev") {
  712. return r.createGARRepository(ctx, conf.Repo, name)
  713. }
  714. project, err := conf.Repo.Project().ReadProject(r.ProjectID)
  715. if err != nil {
  716. return fmt.Errorf("error getting project for repository: %w", err)
  717. }
  718. if project.CapiProvisionerEnabled {
  719. // no need to create repository if pushing to ACR
  720. if strings.Contains(r.URL, ".azurecr.") {
  721. return nil
  722. }
  723. uri := strings.TrimPrefix(r.URL, "https://")
  724. splits := strings.Split(uri, ".")
  725. accountID := splits[0]
  726. region := splits[3]
  727. req := connect.NewRequest(&porterv1.AssumeRoleCredentialsRequest{
  728. ProjectId: int64(r.ProjectID),
  729. AwsAccountId: accountID,
  730. })
  731. creds, err := conf.ClusterControlPlaneClient.AssumeRoleCredentials(ctx, req)
  732. if err != nil {
  733. return fmt.Errorf("error getting capi credentials for repository: %w", err)
  734. }
  735. aws := &ints.AWSIntegration{
  736. AWSAccessKeyID: []byte(creds.Msg.AwsAccessId),
  737. AWSSecretAccessKey: []byte(creds.Msg.AwsSecretKey),
  738. AWSSessionToken: []byte(creds.Msg.AwsSessionToken),
  739. AWSRegion: region,
  740. }
  741. return r.createECRRepository(aws, name)
  742. }
  743. // otherwise, no-op
  744. return nil
  745. }
  746. func (r *Registry) createECRRepository(
  747. aws *ints.AWSIntegration,
  748. name string,
  749. ) error {
  750. sess, err := aws.GetSession()
  751. if err != nil {
  752. return err
  753. }
  754. svc := ecr.New(sess)
  755. // determine if repository already exists
  756. _, err = svc.DescribeRepositories(&ecr.DescribeRepositoriesInput{
  757. RepositoryNames: []*string{&name},
  758. })
  759. // if the repository was not found, create it
  760. if aerr, ok := err.(awserr.Error); ok && aerr.Code() == ecr.ErrCodeRepositoryNotFoundException {
  761. _, err = svc.CreateRepository(&ecr.CreateRepositoryInput{
  762. RepositoryName: &name,
  763. })
  764. return err
  765. } else if err != nil {
  766. return err
  767. }
  768. return nil
  769. }
  770. func (r *Registry) createGARRepository(
  771. ctx context.Context,
  772. repo repository.Repository,
  773. name string,
  774. ) error {
  775. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  776. r.ProjectID,
  777. r.GCPIntegrationID,
  778. )
  779. if err != nil {
  780. return err
  781. }
  782. client, err := artifactregistry.NewClient(ctx, option.WithTokenSource(&garTokenSource{
  783. reg: r,
  784. repo: repo,
  785. ctx: ctx,
  786. }), option.WithScopes("roles/artifactregistry.admin"))
  787. if err != nil {
  788. return err
  789. }
  790. defer client.Close()
  791. parsedURL, err := url.Parse("https://" + r.URL)
  792. if err != nil {
  793. return err
  794. }
  795. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  796. _, err = client.GetRepository(context.Background(), &artifactregistrypb.GetRepositoryRequest{
  797. Name: fmt.Sprintf("projects/%s/locations/%s/repositories/%s", gcpInt.GCPProjectID, location, name),
  798. })
  799. if err != nil && strings.Contains(err.Error(), "not found") {
  800. // create a new repository
  801. _, err := client.CreateRepository(context.Background(), &artifactregistrypb.CreateRepositoryRequest{
  802. Parent: fmt.Sprintf("projects/%s/locations/%s", gcpInt.GCPProjectID, location),
  803. RepositoryId: name,
  804. Repository: &artifactregistrypb.Repository{
  805. Format: artifactregistrypb.Repository_DOCKER,
  806. },
  807. })
  808. if err != nil {
  809. return err
  810. }
  811. } else if err != nil {
  812. return err
  813. }
  814. return nil
  815. }
  816. // ListImages lists the images for an image repository
  817. func (r *Registry) ListImages(
  818. ctx context.Context,
  819. repoName string,
  820. repo repository.Repository,
  821. conf *config.Config,
  822. ) ([]*ptypes.Image, error) {
  823. // switch on the auth mechanism to get a token
  824. if r.AWSIntegrationID != 0 {
  825. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  826. r.ProjectID,
  827. r.AWSIntegrationID,
  828. )
  829. if err != nil {
  830. return nil, err
  831. }
  832. return r.listECRImages(aws, repoName, repo)
  833. }
  834. if r.AzureIntegrationID != 0 {
  835. return r.listACRImages(repoName, repo)
  836. }
  837. if r.GCPIntegrationID != 0 {
  838. if strings.Contains(r.URL, "pkg.dev") {
  839. return r.listGARImages(ctx, repoName, repo)
  840. }
  841. return r.listGCRImages(repoName, repo)
  842. }
  843. if r.DOIntegrationID != 0 {
  844. return r.listDOCRImages(repoName, repo, conf.DOConf)
  845. }
  846. if r.BasicIntegrationID != 0 {
  847. return r.listPrivateRegistryImages(repoName, repo)
  848. }
  849. project, err := conf.Repo.Project().ReadProject(r.ProjectID)
  850. if err != nil {
  851. return nil, fmt.Errorf("error getting project for repository: %w", err)
  852. }
  853. if project.CapiProvisionerEnabled {
  854. uri := strings.TrimPrefix(r.URL, "https://")
  855. splits := strings.Split(uri, ".")
  856. accountID := splits[0]
  857. region := splits[3]
  858. req := connect.NewRequest(&porterv1.AssumeRoleCredentialsRequest{
  859. ProjectId: int64(r.ProjectID),
  860. AwsAccountId: accountID,
  861. })
  862. creds, err := conf.ClusterControlPlaneClient.AssumeRoleCredentials(ctx, req)
  863. if err != nil {
  864. return nil, fmt.Errorf("error getting capi credentials for repository: %w", err)
  865. }
  866. aws := &ints.AWSIntegration{
  867. AWSAccessKeyID: []byte(creds.Msg.AwsAccessId),
  868. AWSSecretAccessKey: []byte(creds.Msg.AwsSecretKey),
  869. AWSSessionToken: []byte(creds.Msg.AwsSessionToken),
  870. AWSRegion: region,
  871. }
  872. return r.listECRImages(aws, repoName, repo)
  873. }
  874. return nil, fmt.Errorf("error listing images")
  875. }
  876. func (r *Registry) GetECRPaginatedImages(
  877. repoName string,
  878. repo repository.Repository,
  879. maxResults int64,
  880. nextToken *string,
  881. ) ([]*ptypes.Image, *string, error) {
  882. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  883. r.ProjectID,
  884. r.AWSIntegrationID,
  885. )
  886. if err != nil {
  887. return nil, nil, err
  888. }
  889. sess, err := aws.GetSession()
  890. if err != nil {
  891. return nil, nil, err
  892. }
  893. svc := ecr.New(sess)
  894. resp, err := svc.ListImages(&ecr.ListImagesInput{
  895. RepositoryName: &repoName,
  896. MaxResults: &maxResults,
  897. NextToken: nextToken,
  898. })
  899. if err != nil {
  900. return nil, nil, err
  901. }
  902. if len(resp.ImageIds) == 0 {
  903. return []*ptypes.Image{}, nil, nil
  904. }
  905. imageIDLen := len(resp.ImageIds)
  906. imageDetails := make([]*ecr.ImageDetail, 0)
  907. imageIDMap := make(map[string]bool)
  908. for _, id := range resp.ImageIds {
  909. if id != nil && id.ImageTag != nil {
  910. imageIDMap[*id.ImageTag] = true
  911. }
  912. }
  913. var wg sync.WaitGroup
  914. var mu sync.Mutex
  915. // AWS API expects the length of imageIDs to be at max 100 at a time
  916. for start := 0; start < imageIDLen; start += 100 {
  917. end := start + 100
  918. if end > imageIDLen {
  919. end = imageIDLen
  920. }
  921. wg.Add(1)
  922. go func(start, end int) {
  923. defer wg.Done()
  924. describeResp, err := svc.DescribeImages(&ecr.DescribeImagesInput{
  925. RepositoryName: &repoName,
  926. ImageIds: resp.ImageIds[start:end],
  927. })
  928. if err != nil {
  929. return
  930. }
  931. mu.Lock()
  932. imageDetails = append(imageDetails, describeResp.ImageDetails...)
  933. mu.Unlock()
  934. }(start, end)
  935. }
  936. wg.Wait()
  937. res := make([]*ptypes.Image, 0)
  938. imageInfoMap := make(map[string]*ptypes.Image)
  939. for _, img := range imageDetails {
  940. for _, tag := range img.ImageTags {
  941. newImage := &ptypes.Image{
  942. Digest: *img.ImageDigest,
  943. Tag: *tag,
  944. RepositoryName: repoName,
  945. PushedAt: img.ImagePushedAt,
  946. }
  947. if _, ok := imageIDMap[*tag]; ok {
  948. if _, ok := imageInfoMap[*tag]; !ok {
  949. imageInfoMap[*tag] = newImage
  950. }
  951. }
  952. if len(imageInfoMap) == int(maxResults) {
  953. break
  954. }
  955. }
  956. if len(imageInfoMap) == int(maxResults) {
  957. break
  958. }
  959. }
  960. for _, v := range imageInfoMap {
  961. res = append(res, v)
  962. }
  963. sort.Slice(res, func(i, j int) bool {
  964. if res[i].PushedAt == nil || res[j].PushedAt == nil {
  965. return false
  966. }
  967. return res[i].PushedAt.After(*res[j].PushedAt)
  968. })
  969. return res, resp.NextToken, nil
  970. }
  971. func (r *Registry) listECRImages(aws *ints.AWSIntegration, repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  972. sess, err := aws.GetSession()
  973. if err != nil {
  974. return nil, err
  975. }
  976. svc := ecr.New(sess)
  977. maxResults := int64(1000)
  978. var imageIDs []*ecr.ImageIdentifier
  979. resp, err := svc.ListImages(&ecr.ListImagesInput{
  980. RepositoryName: &repoName,
  981. MaxResults: &maxResults,
  982. })
  983. if err != nil {
  984. return nil, err
  985. }
  986. if len(resp.ImageIds) == 0 {
  987. return []*ptypes.Image{}, nil
  988. }
  989. imageIDs = append(imageIDs, resp.ImageIds...)
  990. nextToken := resp.NextToken
  991. for nextToken != nil {
  992. resp, err := svc.ListImages(&ecr.ListImagesInput{
  993. RepositoryName: &repoName,
  994. MaxResults: &maxResults,
  995. NextToken: nextToken,
  996. })
  997. if err != nil {
  998. return nil, err
  999. }
  1000. imageIDs = append(imageIDs, resp.ImageIds...)
  1001. nextToken = resp.NextToken
  1002. }
  1003. imageIDLen := len(imageIDs)
  1004. imageDetails := make([]*ecr.ImageDetail, 0)
  1005. var wg sync.WaitGroup
  1006. var mu sync.Mutex
  1007. // AWS API expects the length of imageIDs to be at max 100 at a time
  1008. for start := 0; start < imageIDLen; start += 100 {
  1009. end := start + 100
  1010. if end > imageIDLen {
  1011. end = imageIDLen
  1012. }
  1013. wg.Add(1)
  1014. go func(start, end int) {
  1015. defer wg.Done()
  1016. describeResp, err := svc.DescribeImages(&ecr.DescribeImagesInput{
  1017. RepositoryName: &repoName,
  1018. ImageIds: imageIDs[start:end],
  1019. })
  1020. if err != nil {
  1021. return
  1022. }
  1023. mu.Lock()
  1024. imageDetails = append(imageDetails, describeResp.ImageDetails...)
  1025. mu.Unlock()
  1026. }(start, end)
  1027. }
  1028. wg.Wait()
  1029. res := make([]*ptypes.Image, 0)
  1030. imageInfoMap := make(map[string]*ptypes.Image)
  1031. for _, img := range imageDetails {
  1032. for _, tag := range img.ImageTags {
  1033. newImage := &ptypes.Image{
  1034. Digest: *img.ImageDigest,
  1035. Tag: *tag,
  1036. RepositoryName: repoName,
  1037. PushedAt: img.ImagePushedAt,
  1038. }
  1039. if _, ok := imageInfoMap[*tag]; !ok {
  1040. imageInfoMap[*tag] = newImage
  1041. }
  1042. }
  1043. }
  1044. for _, v := range imageInfoMap {
  1045. res = append(res, v)
  1046. }
  1047. return res, nil
  1048. }
  1049. func (r *Registry) listACRImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1050. az, err := repo.AzureIntegration().ReadAzureIntegration(
  1051. r.ProjectID,
  1052. r.AzureIntegrationID,
  1053. )
  1054. if err != nil {
  1055. return nil, err
  1056. }
  1057. // use JWT token to request catalog
  1058. client := &http.Client{}
  1059. req, err := http.NewRequest(
  1060. "GET",
  1061. fmt.Sprintf("%s/v2/%s/tags/list", r.URL, repoName),
  1062. nil,
  1063. )
  1064. if err != nil {
  1065. return nil, err
  1066. }
  1067. req.SetBasicAuth(az.AzureClientID, string(az.ServicePrincipalSecret))
  1068. resp, err := client.Do(req)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. gcrResp := gcrImageResp{}
  1073. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  1074. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  1075. }
  1076. res := make([]*ptypes.Image, 0)
  1077. for _, tag := range gcrResp.Tags {
  1078. res = append(res, &ptypes.Image{
  1079. RepositoryName: strings.TrimPrefix(repoName, "https://"),
  1080. Tag: tag,
  1081. })
  1082. }
  1083. return res, nil
  1084. }
  1085. type gcrImageResp struct {
  1086. Tags []string `json:"tags"`
  1087. }
  1088. func (r *Registry) listGCRImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1089. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  1090. r.ProjectID,
  1091. r.GCPIntegrationID,
  1092. )
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. // use JWT token to request catalog
  1097. client := &http.Client{}
  1098. parsedURL, err := url.Parse("https://" + r.URL)
  1099. if err != nil {
  1100. return nil, err
  1101. }
  1102. trimmedPath := strings.Trim(parsedURL.Path, "/")
  1103. req, err := http.NewRequest(
  1104. "GET",
  1105. fmt.Sprintf("https://%s/v2/%s/%s/tags/list", parsedURL.Host, trimmedPath, repoName),
  1106. nil,
  1107. )
  1108. if err != nil {
  1109. return nil, err
  1110. }
  1111. req.SetBasicAuth("_json_key", string(gcp.GCPKeyData))
  1112. resp, err := client.Do(req)
  1113. if err != nil {
  1114. return nil, err
  1115. }
  1116. gcrResp := gcrImageResp{}
  1117. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  1118. return nil, fmt.Errorf("Could not read GCR repositories: %v", err)
  1119. }
  1120. res := make([]*ptypes.Image, 0)
  1121. for _, tag := range gcrResp.Tags {
  1122. res = append(res, &ptypes.Image{
  1123. RepositoryName: repoName,
  1124. Tag: tag,
  1125. })
  1126. }
  1127. return res, nil
  1128. }
  1129. func (r *Registry) listGARImages(ctx context.Context, repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1130. repoImageSlice := strings.Split(repoName, "/")
  1131. if len(repoImageSlice) != 2 {
  1132. return nil, fmt.Errorf("invalid GAR repo name: %s. Expected to be in the form of REPOSITORY/IMAGE", repoName)
  1133. }
  1134. gcpInt, err := repo.GCPIntegration().ReadGCPIntegration(
  1135. r.ProjectID,
  1136. r.GCPIntegrationID,
  1137. )
  1138. if err != nil {
  1139. return nil, err
  1140. }
  1141. svc, err := v1artifactregistry.NewService(ctx, option.WithTokenSource(&garTokenSource{
  1142. reg: r,
  1143. repo: repo,
  1144. ctx: ctx,
  1145. }), option.WithScopes("roles/artifactregistry.reader"))
  1146. if err != nil {
  1147. return nil, err
  1148. }
  1149. var res []*ptypes.Image
  1150. parsedURL, err := url.Parse("https://" + r.URL)
  1151. if err != nil {
  1152. return nil, err
  1153. }
  1154. location := strings.TrimSuffix(parsedURL.Host, "-docker.pkg.dev")
  1155. dockerSvc := v1artifactregistry.NewProjectsLocationsRepositoriesDockerImagesService(svc)
  1156. nextToken := ""
  1157. for {
  1158. resp, err := dockerSvc.List(fmt.Sprintf("projects/%s/locations/%s/repositories/%s",
  1159. gcpInt.GCPProjectID, location, repoImageSlice[0])).PageSize(1000).PageToken(nextToken).Do()
  1160. if err != nil {
  1161. return nil, err
  1162. }
  1163. for _, image := range resp.DockerImages {
  1164. named, err := reference.ParseNamed(image.Uri)
  1165. if err != nil {
  1166. continue
  1167. }
  1168. paths := strings.Split(reference.Path(named), "/")
  1169. imageName := paths[len(paths)-1]
  1170. if imageName == repoImageSlice[1] {
  1171. uploadTime, _ := time.Parse(time.RFC3339, image.UploadTime)
  1172. for _, tag := range image.Tags {
  1173. res = append(res, &ptypes.Image{
  1174. RepositoryName: repoName,
  1175. Tag: tag,
  1176. PushedAt: &uploadTime,
  1177. Digest: strings.Split(image.Uri, "@")[1],
  1178. })
  1179. }
  1180. }
  1181. }
  1182. if resp.NextPageToken == "" {
  1183. break
  1184. }
  1185. nextToken = resp.NextPageToken
  1186. }
  1187. return res, nil
  1188. }
  1189. func (r *Registry) listDOCRImages(
  1190. repoName string,
  1191. repo repository.Repository,
  1192. doAuth *oauth2.Config,
  1193. ) ([]*ptypes.Image, error) {
  1194. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  1195. r.ProjectID,
  1196. r.DOIntegrationID,
  1197. )
  1198. if err != nil {
  1199. return nil, err
  1200. }
  1201. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  1202. if err != nil {
  1203. return nil, err
  1204. }
  1205. client := godo.NewFromToken(tok)
  1206. urlArr := strings.Split(r.URL, "/")
  1207. if len(urlArr) != 2 {
  1208. return nil, fmt.Errorf("invalid digital ocean registry url")
  1209. }
  1210. name := urlArr[1]
  1211. var tags []*godo.RepositoryTag
  1212. opt := &godo.ListOptions{
  1213. PerPage: 200,
  1214. }
  1215. for {
  1216. nextTags, resp, err := client.Registry.ListRepositoryTags(context.TODO(), name, repoName, opt)
  1217. if err != nil {
  1218. return nil, err
  1219. }
  1220. tags = append(tags, nextTags...)
  1221. if resp.Links == nil || resp.Links.IsLastPage() {
  1222. break
  1223. }
  1224. page, err := resp.Links.CurrentPage()
  1225. if err != nil {
  1226. return nil, err
  1227. }
  1228. opt.Page = page + 1
  1229. }
  1230. res := make([]*ptypes.Image, 0)
  1231. for _, tag := range tags {
  1232. res = append(res, &ptypes.Image{
  1233. RepositoryName: repoName,
  1234. Tag: tag.Tag,
  1235. })
  1236. }
  1237. return res, nil
  1238. }
  1239. func (r *Registry) listPrivateRegistryImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1240. // handle dockerhub different, as it doesn't implement the docker registry http api
  1241. if strings.Contains(r.URL, "docker.io") {
  1242. return r.listDockerHubImages(repoName, repo)
  1243. }
  1244. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1245. r.ProjectID,
  1246. r.BasicIntegrationID,
  1247. )
  1248. if err != nil {
  1249. return nil, err
  1250. }
  1251. // Just use service account key to authenticate, since scopes may not be in place
  1252. // for oauth. This also prevents us from making more requests.
  1253. client := &http.Client{}
  1254. // get the host and scheme to make the request
  1255. parsedURL, err := url.Parse(r.URL)
  1256. req, err := http.NewRequest(
  1257. "GET",
  1258. fmt.Sprintf("%s://%s/v2/%s/tags/list", parsedURL.Scheme, parsedURL.Host, repoName),
  1259. nil,
  1260. )
  1261. if err != nil {
  1262. return nil, err
  1263. }
  1264. req.SetBasicAuth(string(basic.Username), string(basic.Password))
  1265. resp, err := client.Do(req)
  1266. if err != nil {
  1267. return nil, err
  1268. }
  1269. gcrResp := gcrImageResp{}
  1270. if err := json.NewDecoder(resp.Body).Decode(&gcrResp); err != nil {
  1271. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  1272. }
  1273. res := make([]*ptypes.Image, 0)
  1274. for _, tag := range gcrResp.Tags {
  1275. res = append(res, &ptypes.Image{
  1276. RepositoryName: repoName,
  1277. Tag: tag,
  1278. })
  1279. }
  1280. return res, nil
  1281. }
  1282. type dockerHubImageResult struct {
  1283. Name string `json:"name"`
  1284. }
  1285. type dockerHubImageResp struct {
  1286. Results []dockerHubImageResult `json:"results"`
  1287. }
  1288. type dockerHubLoginReq struct {
  1289. Username string `json:"username"`
  1290. Password string `json:"password"`
  1291. }
  1292. type dockerHubLoginResp struct {
  1293. Token string `json:"token"`
  1294. }
  1295. func (r *Registry) listDockerHubImages(repoName string, repo repository.Repository) ([]*ptypes.Image, error) {
  1296. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1297. r.ProjectID,
  1298. r.BasicIntegrationID,
  1299. )
  1300. if err != nil {
  1301. return nil, err
  1302. }
  1303. client := &http.Client{}
  1304. // first, make a request for the access token
  1305. data, err := json.Marshal(&dockerHubLoginReq{
  1306. Username: string(basic.Username),
  1307. Password: string(basic.Password),
  1308. })
  1309. if err != nil {
  1310. return nil, err
  1311. }
  1312. req, err := http.NewRequest(
  1313. "POST",
  1314. "https://hub.docker.com/v2/users/login",
  1315. strings.NewReader(string(data)),
  1316. )
  1317. if err != nil {
  1318. return nil, err
  1319. }
  1320. req.Header.Add("Content-Type", "application/json")
  1321. resp, err := client.Do(req)
  1322. if err != nil {
  1323. return nil, err
  1324. }
  1325. tokenObj := dockerHubLoginResp{}
  1326. if err := json.NewDecoder(resp.Body).Decode(&tokenObj); err != nil {
  1327. return nil, fmt.Errorf("Could not decode Dockerhub token from response: %v", err)
  1328. }
  1329. req, err = http.NewRequest(
  1330. "GET",
  1331. fmt.Sprintf("https://hub.docker.com/v2/repositories/%s/tags", strings.Split(r.URL, "docker.io/")[1]),
  1332. nil,
  1333. )
  1334. if err != nil {
  1335. return nil, err
  1336. }
  1337. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tokenObj.Token))
  1338. resp, err = client.Do(req)
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. imageResp := dockerHubImageResp{}
  1343. if err := json.NewDecoder(resp.Body).Decode(&imageResp); err != nil {
  1344. return nil, fmt.Errorf("Could not read private registry repositories: %v", err)
  1345. }
  1346. res := make([]*ptypes.Image, 0)
  1347. for _, result := range imageResp.Results {
  1348. res = append(res, &ptypes.Image{
  1349. RepositoryName: repoName,
  1350. Tag: result.Name,
  1351. })
  1352. }
  1353. return res, nil
  1354. }
  1355. // GetDockerConfigJSON returns a dockerconfigjson file contents with "auths"
  1356. // populated.
  1357. func (r *Registry) GetDockerConfigJSON(
  1358. repo repository.Repository,
  1359. doAuth *oauth2.Config, // only required if using DOCR
  1360. ) ([]byte, error) {
  1361. var conf *configfile.ConfigFile
  1362. var err error
  1363. // switch on the auth mechanism to get a token
  1364. if r.AWSIntegrationID != 0 {
  1365. conf, err = r.getECRDockerConfigFile(repo)
  1366. }
  1367. if r.GCPIntegrationID != 0 {
  1368. conf, err = r.getGCRDockerConfigFile(repo)
  1369. }
  1370. if r.DOIntegrationID != 0 {
  1371. conf, err = r.getDOCRDockerConfigFile(repo, doAuth)
  1372. }
  1373. if r.BasicIntegrationID != 0 {
  1374. conf, err = r.getPrivateRegistryDockerConfigFile(repo)
  1375. }
  1376. if r.AzureIntegrationID != 0 {
  1377. conf, err = r.getACRDockerConfigFile(repo)
  1378. }
  1379. if err != nil {
  1380. return nil, err
  1381. }
  1382. return json.Marshal(conf)
  1383. }
  1384. func (r *Registry) getECRDockerConfigFile(
  1385. repo repository.Repository,
  1386. ) (*configfile.ConfigFile, error) {
  1387. aws, err := repo.AWSIntegration().ReadAWSIntegration(
  1388. r.ProjectID,
  1389. r.AWSIntegrationID,
  1390. )
  1391. if err != nil {
  1392. return nil, err
  1393. }
  1394. sess, err := aws.GetSession()
  1395. if err != nil {
  1396. return nil, err
  1397. }
  1398. ecrSvc := ecr.New(sess)
  1399. output, err := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
  1400. if err != nil {
  1401. return nil, err
  1402. }
  1403. token := *output.AuthorizationData[0].AuthorizationToken
  1404. decodedToken, err := base64.StdEncoding.DecodeString(token)
  1405. if err != nil {
  1406. return nil, err
  1407. }
  1408. parts := strings.SplitN(string(decodedToken), ":", 2)
  1409. if len(parts) < 2 {
  1410. return nil, err
  1411. }
  1412. key := r.URL
  1413. if !strings.Contains(key, "http") {
  1414. key = "https://" + key
  1415. }
  1416. return &configfile.ConfigFile{
  1417. AuthConfigs: map[string]types.AuthConfig{
  1418. key: {
  1419. Username: parts[0],
  1420. Password: parts[1],
  1421. Auth: token,
  1422. },
  1423. },
  1424. }, nil
  1425. }
  1426. func (r *Registry) getGCRDockerConfigFile(
  1427. repo repository.Repository,
  1428. ) (*configfile.ConfigFile, error) {
  1429. gcp, err := repo.GCPIntegration().ReadGCPIntegration(
  1430. r.ProjectID,
  1431. r.GCPIntegrationID,
  1432. )
  1433. if err != nil {
  1434. return nil, err
  1435. }
  1436. key := r.URL
  1437. if !strings.Contains(key, "http") {
  1438. key = "https://" + key
  1439. }
  1440. parsedURL, _ := url.Parse(key)
  1441. return &configfile.ConfigFile{
  1442. AuthConfigs: map[string]types.AuthConfig{
  1443. parsedURL.Host: {
  1444. Username: "_json_key",
  1445. Password: string(gcp.GCPKeyData),
  1446. Auth: generateAuthToken("_json_key", string(gcp.GCPKeyData)),
  1447. },
  1448. },
  1449. }, nil
  1450. }
  1451. func (r *Registry) getDOCRDockerConfigFile(
  1452. repo repository.Repository,
  1453. doAuth *oauth2.Config,
  1454. ) (*configfile.ConfigFile, error) {
  1455. oauthInt, err := repo.OAuthIntegration().ReadOAuthIntegration(
  1456. r.ProjectID,
  1457. r.DOIntegrationID,
  1458. )
  1459. if err != nil {
  1460. return nil, err
  1461. }
  1462. tok, _, err := oauth.GetAccessToken(oauthInt.SharedOAuthModel, doAuth, oauth.MakeUpdateOAuthIntegrationTokenFunction(oauthInt, repo))
  1463. if err != nil {
  1464. return nil, err
  1465. }
  1466. key := r.URL
  1467. if !strings.Contains(key, "http") {
  1468. key = "https://" + key
  1469. }
  1470. parsedURL, _ := url.Parse(key)
  1471. return &configfile.ConfigFile{
  1472. AuthConfigs: map[string]types.AuthConfig{
  1473. parsedURL.Host: {
  1474. Username: tok,
  1475. Password: tok,
  1476. Auth: generateAuthToken(tok, tok),
  1477. },
  1478. },
  1479. }, nil
  1480. }
  1481. func (r *Registry) getPrivateRegistryDockerConfigFile(
  1482. repo repository.Repository,
  1483. ) (*configfile.ConfigFile, error) {
  1484. basic, err := repo.BasicIntegration().ReadBasicIntegration(
  1485. r.ProjectID,
  1486. r.BasicIntegrationID,
  1487. )
  1488. if err != nil {
  1489. return nil, err
  1490. }
  1491. key := r.URL
  1492. if !strings.Contains(key, "http") {
  1493. key = "https://" + key
  1494. }
  1495. parsedURL, _ := url.Parse(key)
  1496. authConfigKey := parsedURL.Host
  1497. if strings.Contains(r.URL, "index.docker.io") {
  1498. authConfigKey = "https://index.docker.io/v1/"
  1499. }
  1500. return &configfile.ConfigFile{
  1501. AuthConfigs: map[string]types.AuthConfig{
  1502. authConfigKey: {
  1503. Username: string(basic.Username),
  1504. Password: string(basic.Password),
  1505. Auth: generateAuthToken(string(basic.Username), string(basic.Password)),
  1506. },
  1507. },
  1508. }, nil
  1509. }
  1510. func (r *Registry) getACRDockerConfigFile(
  1511. repo repository.Repository,
  1512. ) (*configfile.ConfigFile, error) {
  1513. username, pw, err := r.GetACRCredentials(repo)
  1514. if err != nil {
  1515. return nil, err
  1516. }
  1517. key := r.URL
  1518. if !strings.Contains(key, "http") {
  1519. key = "https://" + key
  1520. }
  1521. parsedURL, _ := url.Parse(key)
  1522. return &configfile.ConfigFile{
  1523. AuthConfigs: map[string]types.AuthConfig{
  1524. parsedURL.Host: {
  1525. Username: string(username),
  1526. Password: string(pw),
  1527. Auth: generateAuthToken(string(username), string(pw)),
  1528. },
  1529. },
  1530. }, nil
  1531. }
  1532. func generateAuthToken(username, password string) string {
  1533. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  1534. }