/
image_apk.go
253 lines (203 loc) · 6.8 KB
/
image_apk.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package cli
import (
"context"
"fmt"
"path"
"slices"
"chainguard.dev/melange/pkg/config"
"github.com/anchore/stereoscope"
"github.com/anchore/stereoscope/pkg/image"
"github.com/anchore/syft/syft"
"github.com/anchore/syft/syft/artifact"
"github.com/anchore/syft/syft/pkg"
"github.com/anchore/syft/syft/sbom"
"github.com/anchore/syft/syft/source/stereoscopesource"
"github.com/spf13/cobra"
"github.com/wolfi-dev/wolfictl/pkg/configs"
"github.com/wolfi-dev/wolfictl/pkg/configs/build"
rwos "github.com/wolfi-dev/wolfictl/pkg/configs/rwfs/os"
)
func cmdImageAPK() *cobra.Command {
p := &imageAPKParams{}
cmd := &cobra.Command{
Use: "apk <image>",
Short: "Show APK(s) in a container image",
Example: `
# Show all APKs in an image
wolfictl image apk cgr.dev/chainguard/bash
# Show all APKs in an image that own a component (based on a Syft analysis)
wolfictl image apk cgr.dev/chainguard/coredns -c 'github.com/aws/aws-sdk-go'
# Show all APKs in an image that own a component, and show the path to the
# Melange configuration file for each APK, within the given directory
wolfictl image apk cgr.dev/chainguard/prometheus-operator -c 'github.com/aws/aws-sdk-go' -d ~/code/wolfi-os
`,
SilenceErrors: true,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
imageRef := args[0]
img, err := stereoscope.GetImageFromSource(cmd.Context(), imageRef, image.OciRegistrySource)
if err != nil {
return fmt.Errorf("unable to construct scan source for image %q: %w", imageRef, err)
}
imgSource := stereoscopesource.New(img, stereoscopesource.ImageConfig{
Reference: imageRef,
})
defer imgSource.Close()
cfg := syft.DefaultCreateSBOMConfig()
imgSBOM, err := syft.CreateSBOM(cmd.Context(), imgSource, cfg)
if err != nil {
return fmt.Errorf("unable to create SBOM: %w", err)
}
distroID := imgSBOM.Artifacts.LinuxDistribution.ID
if !slices.Contains([]string{"wolfi", "chainguard"}, distroID) {
return fmt.Errorf("unsupported distro: %s", distroID)
}
r := &syftResults{sbom: imgSBOM}
var apks []pkg.Package
if c := p.component; c != "" {
apks, err = r.apksOwningPackageWithName(c)
if err != nil {
return fmt.Errorf("unable to find APK package owning a component %q: %w", c, err)
}
} else {
apks = r.apks()
}
if len(p.distroDirPaths) == 0 {
for i := range apks {
apk := apks[i]
fmt.Println(apk.Name)
}
return nil
}
configPaths, err := apkConfigPaths(cmd.Context(), apks, p.distroDirPaths)
if err != nil {
return fmt.Errorf("unable to find configuration files for APK packages: %w", err)
}
for _, p := range configPaths {
fmt.Println(p)
}
return nil
},
}
p.addFlags(cmd)
return cmd
}
type imageAPKParams struct {
component string
distroDirPaths []string
}
func (p *imageAPKParams) addFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&p.component, "component", "c", "", "show only APKs containing the given component")
cmd.Flags().StringSliceVarP(&p.distroDirPaths, "distro-dir", "d", nil, "path to a directory containing Melange build configuration files")
}
type syftResults struct {
sbom *sbom.SBOM
packageOwnershipsByOwnedPackageName ownershipsByOwnedName
}
type ownership struct {
owner pkg.Package
owned pkg.Package
}
// ownershipsByOwnedName is a map of package name to a list of ownerships that
// describe the APK packages that own packages with that name.
type ownershipsByOwnedName map[string][]ownership
func (r *syftResults) apks() []pkg.Package {
var apks []pkg.Package
pkgs := r.sbom.Artifacts.Packages.Sorted(pkg.ApkPkg)
for _, p := range pkgs { //nolint:gocritic // prefer this copy syntax
// Skip findings from SBOMs
if p.FoundBy == "sbom-cataloger" {
continue
}
apks = append(apks, p)
}
return apks
}
func (r *syftResults) apksOwningPackageWithName(name string) ([]pkg.Package, error) {
ownershipIndex, err := r.indexPackageOwnerships()
if err != nil {
return nil, fmt.Errorf("unable to get index of APK package ownerships: %w", err)
}
// Lookup the APK package that owns the given package name
ownerships, ok := ownershipIndex[name]
if !ok || len(ownerships) == 0 {
return nil, fmt.Errorf("no APK package owns %q", name)
}
var apks []pkg.Package
for _, o := range ownerships { //nolint:gocritic // prefer this copy syntax
apks = append(apks, o.owner)
}
return apks, nil
}
func (r *syftResults) indexPackageOwnerships() (ownershipsByOwnedName, error) {
// Lazily create the index of owned package (by name) to APK package
if r.packageOwnershipsByOwnedPackageName != nil {
return r.packageOwnershipsByOwnedPackageName, nil
}
index := make(ownershipsByOwnedName)
for _, rel := range r.sbom.Relationships {
if rel.Type != artifact.OwnershipByFileOverlapRelationship {
continue
}
apkPkgID := rel.From.ID()
ownedPkgID := rel.To.ID()
apkPkg := r.sbom.Artifacts.Packages.Package(apkPkgID)
if apkPkg == nil {
return nil, fmt.Errorf("unable to find owner package %q", apkPkgID)
}
if apkPkg.Type != pkg.ApkPkg {
return nil, fmt.Errorf(
"expected APK package as owner in relationship, got %s (for package %q)",
apkPkg.Type,
apkPkg.Name,
)
}
ownedPkg := r.sbom.Artifacts.Packages.Package(ownedPkgID)
if ownedPkg == nil {
return nil, fmt.Errorf("unable to find owned package %q", ownedPkgID)
}
o := ownership{
owner: *apkPkg,
owned: *ownedPkg,
}
index[ownedPkg.Name] = append(index[ownedPkg.Name], o)
}
// Cache the index for future use
r.packageOwnershipsByOwnedPackageName = index
return index, nil
}
func apkConfigPaths(ctx context.Context, apks []pkg.Package, distroDirPaths []string) ([]string, error) {
configIndexes := make([]*configs.Index[config.Configuration], 0, len(distroDirPaths))
indexRootPaths := make([]string, 0, len(distroDirPaths))
for _, p := range distroDirPaths {
index, err := build.NewIndex(ctx, rwos.DirFS(p))
if err != nil {
return nil, fmt.Errorf("unable to index configuration files from %q: %w", p, err)
}
configIndexes = append(configIndexes, index)
indexRootPaths = append(indexRootPaths, p)
}
configPaths := make([]string, 0, len(apks))
for _, apk := range apks { //nolint:gocritic // prefer this copy syntax
pathFound := false
var origin string
if m, ok := apk.Metadata.(pkg.ApkDBEntry); ok {
origin = m.OriginPackage
} else {
origin = apk.Name
}
for i, index := range configIndexes {
if p := index.Path(origin); p != "" {
pathFound = true
fullPath := path.Join(indexRootPaths[i], p)
configPaths = append(configPaths, fullPath)
}
}
if !pathFound {
return nil, fmt.Errorf("unable to find configuration file for APK package %q", apk.Name)
}
}
slices.Sort(configPaths)
uniqueConfigPaths := slices.Compact(configPaths)
return uniqueConfigPaths, nil
}