github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/image/remote.go (about) 1 package image 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 8 "github.com/google/go-containerregistry/pkg/name" 9 v1 "github.com/google/go-containerregistry/pkg/v1" 10 11 "github.com/devseccon/trivy/pkg/fanal/types" 12 "github.com/devseccon/trivy/pkg/remote" 13 ) 14 15 func tryRemote(ctx context.Context, imageName string, ref name.Reference, option types.ImageOptions) (types.Image, func(), error) { 16 // This function doesn't need cleanup 17 cleanup := func() {} 18 19 desc, err := remote.Get(ctx, ref, option.RegistryOptions) 20 if err != nil { 21 return nil, cleanup, err 22 } 23 img, err := desc.Image() 24 if err != nil { 25 return nil, cleanup, err 26 } 27 28 // Return v1.Image if the image is found in Docker Registry 29 return remoteImage{ 30 name: imageName, 31 Image: img, 32 ref: implicitReference{ref: ref}, 33 descriptor: desc, 34 }, cleanup, nil 35 36 } 37 38 type remoteImage struct { 39 name string 40 ref implicitReference 41 descriptor *remote.Descriptor 42 v1.Image 43 } 44 45 func (img remoteImage) Name() string { 46 return img.name 47 } 48 49 func (img remoteImage) ID() (string, error) { 50 return ID(img) 51 } 52 53 func (img remoteImage) RepoTags() []string { 54 tag := img.ref.TagName() 55 if tag == "" { 56 return []string{} 57 } 58 return []string{fmt.Sprintf("%s:%s", img.ref.RepositoryName(), tag)} 59 } 60 61 func (img remoteImage) RepoDigests() []string { 62 repoDigest := fmt.Sprintf("%s@%s", img.ref.RepositoryName(), img.descriptor.Digest.String()) 63 return []string{repoDigest} 64 } 65 66 type implicitReference struct { 67 ref name.Reference 68 } 69 70 func (r implicitReference) TagName() string { 71 if t, ok := r.ref.(name.Tag); ok { 72 return t.TagStr() 73 } 74 return "" 75 } 76 77 func (r implicitReference) RepositoryName() string { 78 ctx := r.ref.Context() 79 reg := ctx.RegistryStr() 80 repo := ctx.RepositoryStr() 81 82 // Default registry 83 if reg != name.DefaultRegistry { 84 return fmt.Sprintf("%s/%s", reg, repo) 85 } 86 87 // Trim default namespace 88 // See https://docs.docker.com/docker-hub/official_repos 89 return strings.TrimPrefix(repo, "library/") 90 }