registry.go 35 KB

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