-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevguard_target.go
More file actions
306 lines (274 loc) · 9.48 KB
/
Copy pathdevguard_target.go
File metadata and controls
306 lines (274 loc) · 9.48 KB
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package main
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/l3montree-dev/devguard/pkg/devguard"
parser "github.com/novln/docker-parser"
libk8s "github.com/ckotzbauer/libk8soci/pkg/oci"
"github.com/l3montree-dev/devguard-k8s-image-inventory/kubernetes"
)
type DevGuardTarget struct {
projectPath string
token string
tags []string
client *devguard.HTTPClient
}
type DevGuardRequest struct {
Verb string `json:"verb"`
ProjectExternalEntityID string `json:"projectExternalEntityId"`
ProjectName string `json:"projectName"`
ProjectDescription string `json:"projectDescription,omitempty"`
SubProjectExternalEntityID string `json:"subProjectExternalEntityId,omitempty"`
SubProjectName string `json:"subProjectName,omitempty"`
SubProjectDescription string `json:"subProjectDescription,omitempty"`
AssetExternalEntityID string `json:"assetExternalEntityId"`
AssetName string `json:"assetName"`
AssetDescription string `json:"assetDescription,omitempty"`
AssetVersionName string `json:"assetVersionName,omitempty"`
Artifact string `json:"artifact,omitempty"`
Sbom json.RawMessage `json:"sbom,omitempty"`
}
type projectAssetsResponse struct {
ProjectExternalEntityID string `json:"projectExternalEntityId"`
ProjectName string `json:"projectName"`
SubProjects []struct {
SubProjectExternalEntityID string `json:"subProjectExternalEntityId,omitempty"`
SubProjectName string `json:"subProjectName,omitempty"`
SubProjectDescription string `json:"subProjectDescription,omitempty"`
Assets []struct {
AssetExternalEntityID string `json:"assetExternalEntityId"`
AssetName string `json:"assetName"`
AssetVersions []struct {
AssetVersionName string `json:"assetVersionName"`
Artifacts []string `json:"artifacts"`
} `json:"assetVersions,omitempty"`
} `json:"assets"`
} `json:"subProjects,omitempty"`
Assets []struct {
AssetExternalEntityID string `json:"assetExternalEntityId"`
AssetName string `json:"assetName"`
AssetVersions []struct {
AssetVersionName string `json:"assetVersionName"`
Artifacts []string `json:"artifacts"`
} `json:"assetVersions,omitempty"`
} `json:"assets"`
}
func NewDevGuardTarget(token, projectURL string, tags []string) *DevGuardTarget {
// get the base from the projectURL
u, err := url.Parse(projectURL)
if err != nil {
panic("Failed to parse DevGuard project URL: " + err.Error())
}
client, err := devguard.NewHTTPClient(token, u.Scheme+"://"+u.Host)
if err != nil {
panic("Failed to create DevGuard HTTP client: " + err.Error())
}
// check if the token is valid
ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", "/api/v1/whoami", nil)
resp, err := client.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
panic("Failed to validate DevGuard token: " + err.Error())
}
return &DevGuardTarget{
projectPath: u.Path,
token: token,
tags: tags,
client: client,
}
}
func (g *DevGuardTarget) LoadImages() ([]kubernetes.ImageInNamespace, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", g.projectPath, nil)
if err != nil {
return nil, err
}
resp, err := g.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("failed to load images from DevGuard: " + resp.Status)
}
var assets []projectAssetsResponse
if err := json.NewDecoder(resp.Body).Decode(&assets); err != nil {
return nil, err
}
return flattenProjectAssets(assets), nil
}
func flattenProjectAssets(assets []projectAssetsResponse) []kubernetes.ImageInNamespace {
result := make([]kubernetes.ImageInNamespace, 0)
for _, a := range assets {
for _, asset := range a.Assets {
for _, version := range asset.AssetVersions {
for _, artifact := range version.Artifacts {
result = append(result, kubernetes.ImageInNamespace{
Namespace: a.ProjectExternalEntityID,
ContainerName: asset.AssetExternalEntityID,
Image: &libk8s.RegistryImage{
ImageID: buildImageNameFromArtifact(artifact),
Image: buildImageNameFromArtifact(artifact),
},
})
}
}
}
for _, sp := range a.SubProjects {
for _, asset := range sp.Assets {
for _, version := range asset.AssetVersions {
for _, artifact := range version.Artifacts {
result = append(result, kubernetes.ImageInNamespace{
Namespace: a.ProjectExternalEntityID,
ControllerName: &sp.SubProjectExternalEntityID,
ContainerName: asset.AssetExternalEntityID,
Image: &libk8s.RegistryImage{
Image: buildImageNameFromArtifact(artifact),
ImageID: buildImageNameFromArtifact(artifact),
},
})
}
}
}
}
}
return result
}
func buildArtifactName(image *libk8s.RegistryImage) string {
if strings.HasPrefix(image.Image, "pkg:oci/") {
return image.Image
}
imageRepo, tag, shortName, err := getRepoWithVersion(image)
if err != nil {
slog.Error("Could not parse image!!!", "image", image.Image)
return image.Image
}
if tag == "" {
tag = "latest"
}
name := shortName
if idx := strings.LastIndex(shortName, "/"); idx >= 0 {
name = shortName[idx+1:]
}
return "pkg:oci/" + name + "@" + tag + "?repository_url=" + imageRepo
}
func buildImageNameFromArtifact(artifact string) string {
if !strings.HasPrefix(artifact, "pkg:oci/") {
return artifact
}
parts := strings.SplitN(artifact, "@", 2)
if len(parts) != 2 {
return artifact
}
p := strings.SplitN(parts[1], "?repository_url=", 2)
if len(p) != 2 {
return artifact
}
digest := p[0]
repo := p[1]
if strings.HasPrefix(digest, "sha256:") {
return repo + "@" + digest
}
return repo + ":" + digest
}
func isWorkloadOwner(kind string) bool {
return kind == "Deployment" || kind == "DaemonSet" || kind == "StatefulSet"
}
func buildSbomPayload(ctx *TargetContext) DevGuardRequest {
payload := DevGuardRequest{
Verb: "update",
ProjectExternalEntityID: ctx.Pod.PodNamespace,
ProjectName: ctx.Pod.PodNamespace,
ProjectDescription: "Namespace",
AssetExternalEntityID: ctx.Container.Name,
AssetName: ctx.Container.Name,
AssetVersionName: "latest",
Artifact: buildArtifactName(ctx.Image),
Sbom: json.RawMessage(ctx.Sbom),
}
if isWorkloadOwner(ctx.Pod.OwnerReferences.Kind) {
payload.SubProjectExternalEntityID = ctx.Pod.OwnerReferences.Name
payload.SubProjectName = ctx.Pod.OwnerReferences.Name
payload.SubProjectDescription = ctx.Pod.OwnerReferences.Kind
payload.AssetDescription = "container"
} else {
payload.AssetDescription = "container controlled by " + ctx.Pod.OwnerReferences.Kind + " " + ctx.Pod.OwnerReferences.Name
}
return payload
}
func buildDeletePayload(img kubernetes.ImageInNamespace) DevGuardRequest {
controllerName := ""
if img.ControllerName != nil {
controllerName = *img.ControllerName
}
return DevGuardRequest{
Verb: "delete",
ProjectExternalEntityID: img.Namespace,
ProjectName: img.Namespace,
SubProjectExternalEntityID: controllerName,
AssetExternalEntityID: img.ContainerName,
AssetName: img.ContainerName,
AssetVersionName: "latest",
Artifact: buildArtifactName(img.Image),
}
}
func (g *DevGuardTarget) post(payload DevGuardRequest) error {
jsonBody, err := json.Marshal(payload)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", g.projectPath, strings.NewReader(string(jsonBody)))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
_, err = g.client.Do(req)
return err
}
func (g *DevGuardTarget) ProcessSbom(ctx *TargetContext) error {
if ctx.Sbom == "" {
slog.Info("Empty SBOM - skip image", "image", ctx.Image.ImageID)
return nil
}
slog.Info("Sending SBOM to DevGuard", "Namespace", ctx.Pod.PodNamespace, "Container", ctx.Container.Name)
if err := g.post(buildSbomPayload(ctx)); err != nil {
slog.Error("Could not upload SBOM", "err", err)
return err
}
slog.Info("Uploaded SBOM to DevGuard", "Namespace", ctx.Pod.PodNamespace, "Container", ctx.Container.Name)
return nil
}
func (g *DevGuardTarget) Remove(images []kubernetes.ImageInNamespace) error {
wg := sync.WaitGroup{}
for _, img := range images {
wg.Add(1)
go func(img kubernetes.ImageInNamespace) {
defer wg.Done()
slog.Info("Deleting asset", "Namespace", img.Namespace, "Container", img.ContainerName)
if err := g.post(buildDeletePayload(img)); err != nil {
slog.Error("could not delete asset", "err", err)
}
}(img)
}
wg.Wait()
return nil
}
func getRepoWithVersion(image *libk8s.RegistryImage) (string, string, string, error) {
imageRef, err := parser.Parse(image.Image)
if err != nil {
slog.Error("Could not parse image", "image", image.Image)
return "", "", "", err
}
return imageRef.Repository(), imageRef.Tag(), imageRef.ShortName(), nil
}