/
updatevulnerabilities.go
243 lines (218 loc) · 7.04 KB
/
updatevulnerabilities.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
package postgres
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/quay/zlog"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/label"
"github.com/quay/claircore"
"github.com/quay/claircore/libvuln/driver"
"github.com/quay/claircore/pkg/microbatch"
)
var (
zeroRepo claircore.Repository
zeroDist claircore.Distribution
)
var (
updateVulnerabilitiesCounter = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "updatevulnerabilities_total",
Help: "Total number of database queries issued in the updateVulnerabilities method.",
},
[]string{"query"},
)
updateVulnerabilitiesDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "updatevulnerabilities_duration_seconds",
Help: "The duration of all queries issued in the updateVulnerabilities method",
},
[]string{"query"},
)
)
// UpdateVulnerabilities creates a new UpdateOperation for this update call,
// inserts the provided vulnerabilities and computes a diff comprising the
// removed and added vulnerabilities for this UpdateOperation.
func updateVulnerabilites(ctx context.Context, pool *pgxpool.Pool, updater string, fingerprint driver.Fingerprint, vulns []*claircore.Vulnerability) (uuid.UUID, error) {
const (
// Create makes a new update operation and returns the reference and ID.
create = `INSERT INTO update_operation (updater, fingerprint, kind) VALUES ($1, $2, 'vulnerability') RETURNING id, ref;`
// Insert attempts to create a new vulnerability. It fails silently.
insert = `
INSERT INTO vuln (
hash_kind, hash,
name, updater, description, issued, links, severity, normalized_severity,
package_name, package_version, package_module, package_arch, package_kind,
dist_id, dist_name, dist_version, dist_version_code_name, dist_version_id, dist_arch, dist_cpe, dist_pretty_name,
repo_name, repo_key, repo_uri,
fixed_in_version, arch_operation, version_kind, vulnerable_range
) VALUES (
$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, VersionRange($29, $30)
)
ON CONFLICT (hash_kind, hash) DO NOTHING;`
// Assoc associates an update operation and a vulnerability. It fails
// silently.
assoc = `
INSERT INTO uo_vuln (uo, vuln) VALUES (
$3,
(SELECT id FROM vuln WHERE hash_kind = $1 AND hash = $2))
ON CONFLICT DO NOTHING;`
)
ctx = baggage.ContextWithValues(ctx,
label.String("component", "internal/vulnstore/postgres/updateVulnerabilities"))
tx, err := pool.Begin(ctx)
if err != nil {
return uuid.Nil, fmt.Errorf("unable to start transaction: %w", err)
}
defer tx.Rollback(ctx)
var id uint64
var ref uuid.UUID
start := time.Now()
if err := pool.QueryRow(ctx, create, updater, string(fingerprint)).Scan(&id, &ref); err != nil {
return uuid.Nil, fmt.Errorf("failed to create update_operation: %w", err)
}
updateVulnerabilitiesCounter.WithLabelValues("create").Add(1)
updateVulnerabilitiesDuration.WithLabelValues("create").Observe(time.Since(start).Seconds())
zlog.Debug(ctx).
Str("ref", ref.String()).
Msg("update_operation created")
// batch insert vulnerabilities
skipCt := 0
start = time.Now()
mBatcher := microbatch.NewInsert(tx, 2000, time.Minute)
for _, vuln := range vulns {
if vuln.Package == nil || vuln.Package.Name == "" {
skipCt++
continue
}
pkg := vuln.Package
dist := vuln.Dist
repo := vuln.Repo
if dist == nil {
dist = &zeroDist
}
if repo == nil {
repo = &zeroRepo
}
hashKind, hash := md5Vuln(vuln)
vKind, vrLower, vrUpper := rangefmt(vuln.Range)
err := mBatcher.Queue(ctx, insert,
hashKind, hash,
vuln.Name, vuln.Updater, vuln.Description, vuln.Issued, vuln.Links, vuln.Severity, vuln.NormalizedSeverity,
pkg.Name, pkg.Version, pkg.Module, pkg.Arch, pkg.Kind,
dist.DID, dist.Name, dist.Version, dist.VersionCodeName, dist.VersionID, dist.Arch, dist.CPE, dist.PrettyName,
repo.Name, repo.Key, repo.URI,
vuln.FixedInVersion, vuln.ArchOperation, vKind, vrLower, vrUpper,
)
if err != nil {
return uuid.Nil, fmt.Errorf("failed to queue vulnerability: %w", err)
}
if err := mBatcher.Queue(ctx, assoc, hashKind, hash, id); err != nil {
return uuid.Nil, fmt.Errorf("failed to queue association: %w", err)
}
}
if err := mBatcher.Done(ctx); err != nil {
return uuid.Nil, fmt.Errorf("failed to finish batch vulnerability insert: %w", err)
}
updateVulnerabilitiesCounter.WithLabelValues("insert_batch").Add(1)
updateVulnerabilitiesDuration.WithLabelValues("insert_batch").Observe(time.Since(start).Seconds())
if err := tx.Commit(ctx); err != nil {
return uuid.Nil, fmt.Errorf("failed to commit transaction: %w", err)
}
zlog.Debug(ctx).
Str("ref", ref.String()).
Int("skipped", skipCt).
Int("inserted", len(vulns)-skipCt).
Msg("update_operation committed")
return ref, nil
}
// Md5Vuln creates an md5 hash from the members of the passed-in Vulnerability,
// giving us a stable, context-free identifier for this revision of the
// Vulnerability.
func md5Vuln(v *claircore.Vulnerability) (string, []byte) {
var b bytes.Buffer
b.WriteString(v.Name)
b.WriteString(v.Description)
b.WriteString(v.Issued.String())
b.WriteString(v.Links)
b.WriteString(v.Severity)
if v.Package != nil {
b.WriteString(v.Package.Name)
b.WriteString(v.Package.Version)
b.WriteString(v.Package.Module)
b.WriteString(v.Package.Arch)
b.WriteString(v.Package.Kind)
}
if v.Dist != nil {
b.WriteString(v.Dist.DID)
b.WriteString(v.Dist.Name)
b.WriteString(v.Dist.Version)
b.WriteString(v.Dist.VersionCodeName)
b.WriteString(v.Dist.VersionID)
b.WriteString(v.Dist.Arch)
b.WriteString(v.Dist.CPE.BindFS())
b.WriteString(v.Dist.PrettyName)
}
if v.Repo != nil {
b.WriteString(v.Repo.Name)
b.WriteString(v.Repo.Key)
b.WriteString(v.Repo.URI)
}
b.WriteString(v.ArchOperation.String())
b.WriteString(v.FixedInVersion)
if k, l, u := rangefmt(v.Range); k != nil {
b.WriteString(*k)
b.WriteString(l)
b.WriteString(u)
}
s := md5.Sum(b.Bytes())
return "md5", s[:]
}
func rangefmt(r *claircore.Range) (kind *string, lower, upper string) {
lower, upper = "{}", "{}"
if r == nil || r.Lower.Kind != r.Upper.Kind {
return kind, lower, upper
}
kind = &r.Lower.Kind // Just tested the both kinds are the same.
v := &r.Lower
var buf strings.Builder
b := make([]byte, 0, 16) // 16 byte wide scratch buffer
buf.WriteByte('{')
for i := 0; i < 10; i++ {
if i != 0 {
buf.WriteByte(',')
}
buf.Write(strconv.AppendInt(b, int64(v.V[i]), 10))
}
buf.WriteByte('}')
lower = buf.String()
buf.Reset()
v = &r.Upper
buf.WriteByte('{')
for i := 0; i < 10; i++ {
if i != 0 {
buf.WriteByte(',')
}
buf.Write(strconv.AppendInt(b, int64(v.V[i]), 10))
}
buf.WriteByte('}')
upper = buf.String()
return kind, lower, upper
}