Repository navigation
Expand file tree
/
Copy pathactivities.go
More file actions
410 lines (353 loc) · 13 KB
/
Copy pathactivities.go
File metadata and controls
410 lines (353 loc) · 13 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package detection
import (
"context"
"fmt"
"strings"
"sync"
"go.temporal.io/sdk/activity"
"github.com/block/Version-Guard/pkg/eol"
"github.com/block/Version-Guard/pkg/inventory"
"github.com/block/Version-Guard/pkg/policy"
"github.com/block/Version-Guard/pkg/store"
"github.com/block/Version-Guard/pkg/telemetry"
"github.com/block/Version-Guard/pkg/types"
)
// Activity names (stable for replay - following block-am pattern)
const (
FetchInventoryActivityName = "version-guard.FetchInventory"
FetchEOLDataActivityName = "version-guard.FetchEOLData"
DetectDriftActivityName = "version-guard.DetectDrift"
StoreFindingsActivityName = "version-guard.StoreFindings"
EmitMetricsActivityName = "version-guard.EmitMetrics"
)
// Activity input/output types
type FetchInventoryInput struct {
ScanID string
ResourceType types.ResourceType
}
type InventoryResult struct {
ResourceBatchID string
Resources []*types.Resource
}
type FetchEOLInput struct {
ResourceType types.ResourceType
ResourceBatchID string
Resources []*types.Resource
}
type EOLResult struct {
VersionLifecycles map[string]*types.VersionLifecycle // key: "engine:version"
}
//nolint:govet // field alignment sacrificed for logical grouping
type DetectInput struct {
ResourceBatchID string
Resources []*types.Resource
VersionLifecycles map[string]*types.VersionLifecycle
}
//nolint:govet // field alignment sacrificed for logical grouping
type DetectResult struct {
FindingsBatchID string
FindingsCount int
Findings []*types.Finding
}
//nolint:govet // field alignment sacrificed for logical grouping
type StoreInput struct {
FindingsBatchID string
Findings []*types.Finding
ResourceType types.ResourceType
}
//nolint:govet // field alignment sacrificed for logical grouping
type MetricsInput struct {
FindingsBatchID string
Findings []*types.Finding
ResourceType types.ResourceType
}
type MetricsResult struct {
Summary *types.ScanSummary
}
// Activities struct holds dependencies for all activities.
//
// EOLProviders is keyed by the YAML config ID (e.g. "aurora-postgresql",
// "lambda") because each Provider is bound to a single endoflife.date
// product and schema at construction time. FetchEOLData routes to the
// right Provider via the resource type carried on FetchEOLInput, so a
// scan touching N resource types fans out across N Providers — each
// hitting only its own product's cycles.
type Activities struct {
InventorySources map[types.ResourceType]inventory.InventorySource
EOLProviders map[types.ResourceType]eol.Provider
Policy policy.VersionPolicy
Store store.Store
resourceCache sync.Map
}
// NewActivities creates a new Activities instance with dependencies.
// eolProviders MUST contain one entry per resource type the scan will
// touch; FetchEOLData fails with an explicit error if a resource type's
// provider is missing rather than silently producing UNKNOWN findings.
func NewActivities(
inventorySources map[types.ResourceType]inventory.InventorySource,
eolProviders map[types.ResourceType]eol.Provider,
policy policy.VersionPolicy,
store store.Store,
) *Activities {
return &Activities{
InventorySources: inventorySources,
EOLProviders: eolProviders,
Policy: policy,
Store: store,
}
}
func (a *Activities) loadResources(batchID string, fallback []*types.Resource) ([]*types.Resource, error) {
if batchID == "" {
return fallback, nil
}
v, ok := a.resourceCache.Load(batchID)
if !ok {
return nil, fmt.Errorf("resource batch %q not found", batchID)
}
resources, ok := v.([]*types.Resource)
if !ok {
return nil, fmt.Errorf("resource batch %q has invalid type", batchID)
}
return resources, nil
}
func (a *Activities) loadFindings(batchID string, fallback []*types.Finding) ([]*types.Finding, error) {
if batchID == "" {
return fallback, nil
}
v, ok := a.resourceCache.Load(batchID)
if !ok {
return nil, fmt.Errorf("findings batch %q not found", batchID)
}
findings, ok := v.([]*types.Finding)
if !ok {
return nil, fmt.Errorf("findings batch %q has invalid type", batchID)
}
return findings, nil
}
// FetchInventory fetches all resources of a given type from the inventory source
func (a *Activities) FetchInventory(ctx context.Context, input FetchInventoryInput) (*InventoryResult, error) {
logger := activity.GetLogger(ctx)
logger.Info("Fetching inventory", "resourceType", input.ResourceType)
source, ok := a.InventorySources[input.ResourceType]
if !ok {
return nil, fmt.Errorf("no inventory source registered for resource type: %s", input.ResourceType)
}
resources, err := source.ListResources(ctx, input.ResourceType)
if err != nil {
return nil, err
}
logger.Info("Inventory fetched", "count", len(resources))
if input.ScanID == "" {
return &InventoryResult{Resources: resources}, nil
}
// Cache key must include the resource type — the orchestrator
// fans out one detection workflow per resource type and they all
// share the same ScanID. Keying solely on ScanID caused parallel
// workflows to overwrite each other's resources, so e.g. the
// memcached detection would read the valkey resources back and
// the per-type counts ended up scrambled.
batchID := input.ScanID + ":" + string(input.ResourceType)
a.resourceCache.Store(batchID, resources)
return &InventoryResult{ResourceBatchID: batchID}, nil
}
// FetchEOLData fetches EOL lifecycle information for all resource versions.
//
// The provider is selected by input.ResourceType — each Provider is
// bound to a single endoflife.date product, so we MUST use the one
// matching this resource type. A missing entry is a configuration bug
// (the server-side detector loop should have created a provider for
// every configured resource), so we fail loud rather than silently
// returning UNKNOWN findings — that was the symptom of the regression
// fixed in this commit.
func (a *Activities) FetchEOLData(ctx context.Context, input FetchEOLInput) (*EOLResult, error) {
resources, err := a.loadResources(input.ResourceBatchID, input.Resources)
if err != nil {
return nil, err
}
logger := activity.GetLogger(ctx)
logger.Info("Fetching EOL data", "resourceCount", len(resources), "resourceType", input.ResourceType)
provider, ok := a.EOLProviders[input.ResourceType]
if !ok {
return nil, fmt.Errorf("no EOL provider configured for resource type %q", input.ResourceType)
}
lifecycles := make(map[string]*types.VersionLifecycle)
// Fetch lifecycle for each unique engine:version combination
seen := make(map[string]bool)
for _, resource := range resources {
key := resource.Engine + ":" + resource.CurrentVersion
if seen[key] {
continue
}
seen[key] = true
if strings.TrimSpace(resource.CurrentVersion) == "" {
lifecycles[key] = &types.VersionLifecycle{
Engine: resource.Engine,
DataSource: types.LifecycleDataSourceUnknown,
UnknownCause: types.LifecycleUnknownCauseEmptyInventoryVersion,
}
continue
}
lifecycle, err := provider.GetVersionLifecycle(ctx, resource.Engine, resource.CurrentVersion)
if err != nil {
logger.Warn("Failed to get lifecycle", "engine", resource.Engine, "version", resource.CurrentVersion, "error", err)
if lifecycle == nil {
lifecycle = &types.VersionLifecycle{
Version: resource.CurrentVersion,
Engine: resource.Engine,
Source: provider.Name(),
DataSource: types.LifecycleDataSourceUnknown,
UnknownCause: types.LifecycleUnknownCauseSourceError,
}
}
} else if lifecycle == nil {
lifecycle = &types.VersionLifecycle{
Version: resource.CurrentVersion,
Engine: resource.Engine,
Source: provider.Name(),
DataSource: types.LifecycleDataSourceUnknown,
UnknownCause: types.LifecycleUnknownCauseUnattributed,
}
}
lifecycles[key] = lifecycle
}
logger.Info("EOL data fetched", "versionCount", len(lifecycles))
return &EOLResult{
VersionLifecycles: lifecycles,
}, nil
}
// DetectDrift analyzes resources against EOL data and classifies them
func (a *Activities) DetectDrift(ctx context.Context, input DetectInput) (*DetectResult, error) {
resources, err := a.loadResources(input.ResourceBatchID, input.Resources)
if err != nil {
return nil, err
}
logger := activity.GetLogger(ctx)
logger.Info("Detecting version drift", "resourceCount", len(resources))
var findings []*types.Finding
for _, resource := range resources {
key := resource.Engine + ":" + resource.CurrentVersion
lifecycle, ok := input.VersionLifecycles[key]
if !ok || lifecycle == nil {
// No lifecycle data - create unknown finding
lifecycle = &types.VersionLifecycle{
Version: resource.CurrentVersion,
Engine: resource.Engine,
IsSupported: false,
DataSource: types.LifecycleDataSourceUnknown,
UnknownCause: types.LifecycleUnknownCauseUnattributed,
}
}
// Classify and annotate a copy so provider and cache-owned lifecycle
// pointers remain raw and reusable by other resources.
annotated := *lifecycle
status := a.Policy.Classify(resource, &annotated)
annotated.UnknownCause = policy.UnknownCause(resource, &annotated, status)
message := a.Policy.GetMessage(resource, &annotated, status)
lifecycleDetails := types.LifecycleDetailsFromVersionLifecycle(&annotated)
// Create finding. Name, account, and region (when configured) are
// part of resource.Extra and propagate through verbatim.
finding := &types.Finding{
ResourceID: resource.ID,
ResourceType: resource.Type,
Service: resource.Service,
CloudProvider: resource.CloudProvider,
CurrentVersion: resource.CurrentVersion,
Engine: resource.Engine,
Status: status,
Message: message,
EOLDate: annotated.EOLDate,
Tags: resource.Tags,
Extra: resource.Extra,
EOL: lifecycleDetails,
LifecycleDetails: lifecycleDetails,
}
findings = append(findings, finding)
}
logger.Info("Drift detection complete", "findingsCount", len(findings))
if input.ResourceBatchID != "" {
a.resourceCache.Delete(input.ResourceBatchID)
findingsBatchID := input.ResourceBatchID + "-findings"
a.resourceCache.Store(findingsBatchID, findings)
return &DetectResult{FindingsBatchID: findingsBatchID, FindingsCount: len(findings)}, nil
}
return &DetectResult{
Findings: findings,
FindingsCount: len(findings),
}, nil
}
// StoreFindings replaces the resource type's findings with this scan's
// output, evicting entries that dropped out of the inventory. Without
// eviction, deleted resources persist in the worker-local store (and in
// every snapshot) until the pod restarts. Inputs recorded by workflows
// started before ResourceType existed carry the zero value and fall
// back to plain upserts.
func (a *Activities) StoreFindings(ctx context.Context, input StoreInput) error {
findings, err := a.loadFindings(input.FindingsBatchID, input.Findings)
if err != nil {
return err
}
logger := activity.GetLogger(ctx)
logger.Info("Storing findings", "count", len(findings))
if input.ResourceType == "" {
if err := a.Store.SaveFindings(ctx, findings); err != nil {
return err
}
logger.Info("Findings stored successfully")
return nil
}
if len(findings) == 0 {
logger.Warn("Scan returned no findings; evicting all findings for type",
"resourceType", input.ResourceType)
}
if err := a.Store.ReplaceFindings(ctx, input.ResourceType, findings); err != nil {
return err
}
logger.Info("Findings stored successfully")
return nil
}
// EmitMetrics calculates summary statistics and emits metrics
func (a *Activities) EmitMetrics(ctx context.Context, input MetricsInput) (*MetricsResult, error) {
findings, err := a.loadFindings(input.FindingsBatchID, input.Findings)
if err != nil {
return nil, err
}
logger := activity.GetLogger(ctx)
logger.Info("Emitting metrics", "findingsCount", len(findings))
// Calculate summary
summary := &types.ScanSummary{
TotalResources: len(findings),
}
unknownCounts := make(map[types.LifecycleUnknownCause]int)
sourceCounts := make(map[types.LifecycleDataSource]int)
for _, f := range findings {
sourceCounts[f.EOL.DataSource]++
switch f.Status {
case types.StatusRed:
summary.RedCount++
case types.StatusYellow:
summary.YellowCount++
case types.StatusGreen:
summary.GreenCount++
case types.StatusUnknown:
summary.UnknownCount++
unknownCounts[f.EOL.UnknownCause]++
}
}
if summary.TotalResources > 0 {
summary.CompliancePercentage = (float64(summary.GreenCount) / float64(summary.TotalResources)) * 100
}
logger.Info("Metrics calculated",
"total", summary.TotalResources,
"red", summary.RedCount,
"yellow", summary.YellowCount,
"green", summary.GreenCount,
"compliance", summary.CompliancePercentage)
telemetry.RecordDetectionSummary(input.ResourceType, summary)
telemetry.RecordDetectionBreakdown(input.ResourceType, unknownCounts, sourceCounts)
if input.FindingsBatchID != "" {
a.resourceCache.Delete(input.FindingsBatchID)
}
return &MetricsResult{
Summary: summary,
}, nil
}