-
Notifications
You must be signed in to change notification settings - Fork 14
/
resolver.go
2016 lines (1734 loc) · 61.9 KB
/
resolver.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
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Mondoo, Inc.
// SPDX-License-Identifier: BUSL-1.1
package policy
import (
"context"
"encoding/base64"
"encoding/binary"
"math/rand"
"slices"
"sort"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/segmentio/fasthash/fnv1a"
"go.mondoo.com/cnquery/v11/checksums"
"go.mondoo.com/cnquery/v11/explorer"
resources "go.mondoo.com/cnquery/v11/explorer/resources"
"go.mondoo.com/cnquery/v11/llx"
"go.mondoo.com/cnquery/v11/logger"
"go.mondoo.com/cnquery/v11/mqlc"
"go.mondoo.com/cnquery/v11/mrn"
"go.mondoo.com/cnquery/v11/utils/sortx"
"go.mondoo.com/ranger-rpc/codes"
"go.mondoo.com/ranger-rpc/status"
)
const (
POLICY_SERVICE_NAME = "policy.api.mondoo.com"
// This is used to change the checksum of the resolved policy when we want it to be recalculated
// This can be updated, e.g., when we change how the report jobs are generated
// A change of this string will force an update of all the stored resolved policies
RESOLVER_VERSION = "v2024-08-29"
RESOLVER_VERSION_NG = "v2024-11-11"
)
type AssetMutation struct {
AssetMrn string
PolicyMrns []string
FrameworkMrns []string
Action explorer.Action
PolicyScoringSystem explorer.ScoringSystem
}
// Assign a policy to an asset
//
// We need to handle multiple cases:
// 1. all local, policies and assets are available locally
// 2. asset is local (via incognito mode) but policy is upstream
// 3. asset and policy are upstream
func (s *LocalServices) Assign(ctx context.Context, assignment *PolicyAssignment) (*Empty, error) {
if len(assignment.PolicyMrns)+len(assignment.FrameworkMrns) == 0 {
return nil, status.Error(codes.InvalidArgument, "a policy or framework mrn is required")
}
// all remote, call upstream
if s.Upstream != nil && !s.Incognito {
return s.Upstream.PolicyResolver.Assign(ctx, assignment)
}
// policies may be stored in upstream, cache them first
if s.Upstream != nil && s.Incognito {
// NOTE: by calling GetPolicy it is automatically cached
for i := range assignment.PolicyMrns {
mrn := assignment.PolicyMrns[i]
_, err := s.GetPolicy(ctx, &Mrn{
Mrn: mrn,
})
if err != nil {
return nil, err
}
}
}
if err := s.DataLake.EnsureAsset(ctx, assignment.AssetMrn); err != nil {
return nil, err
}
err := s.DataLake.MutateAssignments(ctx, &AssetMutation{
AssetMrn: assignment.AssetMrn,
PolicyMrns: assignment.PolicyMrns,
FrameworkMrns: assignment.FrameworkMrns,
Action: assignment.Action,
PolicyScoringSystem: assignment.ScoringSystem,
}, true)
return globalEmpty, err
}
// Unassign a policy to an asset
func (s *LocalServices) Unassign(ctx context.Context, assignment *PolicyAssignment) (*Empty, error) {
if len(assignment.PolicyMrns)+len(assignment.FrameworkMrns) == 0 {
return nil, status.Error(codes.InvalidArgument, "a policy or framework mrn is required")
}
// all remote, call upstream
if s.Upstream != nil && !s.Incognito {
return s.Upstream.PolicyResolver.Unassign(ctx, assignment)
}
err := s.DataLake.MutateAssignments(ctx, &AssetMutation{
AssetMrn: assignment.AssetMrn,
PolicyMrns: assignment.PolicyMrns,
FrameworkMrns: assignment.FrameworkMrns,
Action: explorer.Action_DEACTIVATE,
}, true)
return globalEmpty, err
}
func (s *LocalServices) SetProps(ctx context.Context, req *explorer.PropsReq) (*explorer.Empty, error) {
// validate that the queries compile and fill in checksums
conf := s.NewCompilerConfig()
for i := range req.Props {
prop := req.Props[i]
// set props is used for both setting and unsetting props
if prop.Mql == "" {
continue
}
code, err := prop.RefreshChecksumAndType(conf)
if err != nil {
return nil, err
}
prop.CodeId = code.CodeV2.Id
}
return &explorer.Empty{}, s.DataLake.SetProps(ctx, req)
}
// Resolve a given policy for a set of asset filters
func (s *LocalServices) Resolve(ctx context.Context, req *ResolveReq) (*ResolvedPolicy, error) {
if s.Upstream != nil && !s.Incognito {
return s.Upstream.Resolve(ctx, req)
}
return s.resolve(ctx, req.PolicyMrn, req.AssetFilters)
}
// ResolveAndUpdateJobs will resolve an asset's policy and update its jobs
func (s *LocalServices) ResolveAndUpdateJobs(ctx context.Context, req *UpdateAssetJobsReq) (*ResolvedPolicy, error) {
if s.Upstream == nil || s.Incognito {
res, err := s.resolve(ctx, req.AssetMrn, req.AssetFilters)
if err != nil {
return nil, err
}
if res.CollectorJob != nil {
err := res.CollectorJob.Validate()
if err != nil {
logger.FromContext(ctx).Error().
Err(err).
Msg("resolver> resolved policy is invalid")
}
}
err = s.DataLake.SetAssetResolvedPolicy(ctx, req.AssetMrn, res, V2Code)
if err != nil {
return nil, err
}
return res, nil
}
res, err := s.Upstream.PolicyResolver.ResolveAndUpdateJobs(ctx, req)
if err != nil {
return nil, err
}
err = s.cacheUpstreamJobs(ctx, req.AssetMrn, res)
if err != nil {
return nil, err
}
return res, nil
}
// UpdateAssetJobs by recalculating them
func (s *LocalServices) UpdateAssetJobs(ctx context.Context, req *UpdateAssetJobsReq) (*Empty, error) {
if s.Upstream == nil || s.Incognito {
return globalEmpty, s.updateAssetJobs(ctx, req.AssetMrn, req.AssetFilters)
}
if _, err := s.Upstream.PolicyResolver.UpdateAssetJobs(ctx, req); err != nil {
return nil, err
}
resolvedPolicy, err := s.Upstream.PolicyResolver.Resolve(ctx, &ResolveReq{
PolicyMrn: req.AssetMrn,
AssetFilters: req.AssetFilters,
})
if err != nil {
return nil, errors.New("resolver> failed to resolve upstream jobs for caching: " + err.Error())
}
return globalEmpty, s.cacheUpstreamJobs(ctx, req.AssetMrn, resolvedPolicy)
}
// GetResolvedPolicy for a given asset
func (s *LocalServices) GetResolvedPolicy(ctx context.Context, mrn *Mrn) (*ResolvedPolicy, error) {
if s.Upstream != nil && !s.Incognito {
return s.Upstream.GetResolvedPolicy(ctx, mrn)
}
res, err := s.DataLake.GetResolvedPolicy(ctx, mrn.Mrn)
return res, err
}
// StoreResults saves the given scores and date for an asset
func (s *LocalServices) StoreResults(ctx context.Context, req *StoreResultsReq) (*Empty, error) {
logger.AddTag(ctx, "asset", req.AssetMrn)
_, err := s.DataLake.UpdateScores(ctx, req.AssetMrn, req.Scores)
if err != nil {
return globalEmpty, err
}
_, err = s.DataLake.UpdateData(ctx, req.AssetMrn, req.Data)
if err != nil {
return globalEmpty, err
}
_, err = s.DataLake.UpdateRisks(ctx, req.AssetMrn, req.Risks)
if err != nil {
return globalEmpty, err
}
if s.Upstream != nil && !s.Incognito {
_, err := s.Upstream.PolicyResolver.StoreResults(ctx, req)
if err != nil {
return globalEmpty, err
}
}
return globalEmpty, nil
}
// GetReport retrieves a report for a given asset and policy
func (s *LocalServices) GetReport(ctx context.Context, req *EntityScoreReq) (*Report, error) {
return s.DataLake.GetReport(ctx, req.EntityMrn, req.ScoreMrn)
}
// GetFrameworkReport retrieves a report for a given asset and framework
func (s *LocalServices) GetFrameworkReport(ctx context.Context, req *EntityScoreReq) (*FrameworkReport, error) {
panic("NOT YET IMPLEMENTED")
}
func (s *LocalServices) GetResourcesData(ctx context.Context, req *resources.EntityResourcesReq) (*resources.EntityResourcesRes, error) {
res, err := s.DataLake.GetResources(ctx, req.EntityMrn, req.Resources)
return &resources.EntityResourcesRes{
Resources: res,
EntityMrn: req.EntityMrn,
}, err
}
// GetScore retrieves one score for an asset
func (s *LocalServices) GetScore(ctx context.Context, req *EntityScoreReq) (*Report, error) {
score, err := s.DataLake.GetScore(ctx, req.EntityMrn, req.ScoreMrn)
if err != nil {
return nil, err
}
return &Report{
EntityMrn: req.EntityMrn,
ScoringMrn: req.ScoreMrn,
Score: &score,
}, nil
}
// SynchronizeAssets is not require for local services
func (s *LocalServices) SynchronizeAssets(ctx context.Context, req *SynchronizeAssetsReq) (*SynchronizeAssetsResp, error) {
return nil, nil
}
// DeleteAssets is not require for local services
func (s *LocalServices) PurgeAssets(context.Context, *PurgeAssetsRequest) (*PurgeAssetsConfirmation, error) {
return nil, nil
}
// HELPER METHODS
// =================
// CreatePolicyObject creates a policy object without saving it and returns it
func (s *LocalServices) CreatePolicyObject(policyMrn string, ownerMrn string) *Policy {
// TODO: this should be handled better and I'm not sure yet how...
// we need to ensure a good owner MRN exists for all objects, including orgs and spaces
// this is the case when we are in incognito mode
if ownerMrn == "" {
log.Debug().Str("policyMrn", policyMrn).Msg("resolver> ownerMrn is missing")
ownerMrn = "//policy.api.mondoo.app"
}
name, _ := mrn.GetResource(policyMrn, MRN_RESOURCE_ASSET)
if name == "" {
name = policyMrn
}
return &Policy{
Mrn: policyMrn,
Name: name, // placeholder
Version: "", // no version, semver otherwise
Groups: []*PolicyGroup{{
Policies: []*PolicyRef{},
Checks: []*explorer.Mquery{},
Queries: []*explorer.Mquery{},
}},
ComputedFilters: &explorer.Filters{},
OwnerMrn: ownerMrn,
}
}
// CreateFrameworkObject creates a framework object without saving it and returns it
func (s *LocalServices) CreateFrameworkObject(frameworkMrn string, ownerMrn string) *Framework {
// TODO: this should be handled better, similar to CreatePolicyObject.
// we need to ensure a good owner MRN exists for all objects, including orgs and spaces
// this is the case when we are in incognito mode
if ownerMrn == "" {
log.Debug().Str("frameworkMrn", frameworkMrn).Msg("resolver> ownerMrn is missing")
ownerMrn = "//policy.api.mondoo.app"
}
name, _ := mrn.GetResource(frameworkMrn, MRN_RESOURCE_ASSET)
if name == "" {
name = frameworkMrn
}
return &Framework{
Mrn: frameworkMrn,
Name: name, // placeholder
Version: "", // no version, semver otherwise
// no Groups; this call usually creates frameworks for assets, where we
// don't need groups since dependencies are handled in the Dependencies field
}
}
// POLICY RESOLUTION
// =====================
const (
maxResolveRetry = 3
maxResolveRetryBackoff = 25 * time.Millisecond
maxResolveRetryBackoffjitter = 25 * time.Millisecond
)
var ErrRetryResolution = errors.New("retry policy resolution")
type policyResolutionError struct {
ID string
IsPolicy bool
Error string
}
type resolverCache struct {
baseChecksum string
assetFiltersChecksum string
assetFilters map[string]struct{}
codeIdToMrn map[string][]string
riskFactors map[string]*RiskFactor
// assigned queries, listed by their UUID (i.e. policy context)
executionQueries map[string]*ExecutionQuery
dataQueries map[string]struct{}
queriesByMsum map[string]*explorer.Mquery // Msum == Mquery.Checksum
riskMrns map[string]*explorer.Mquery
riskInfos map[string]*RiskFactor
propsCache explorer.PropsCache
reportingJobsByUUID map[string]*ReportingJob
reportingJobsByMsum map[string][]*ReportingJob // Msum == Mquery.Checksum, i.e. only reporting jobs for mqueries
reportingJobsByCodeId map[string][]*ReportingJob // CodeId == Mquery.CodeId
reportingJobsActive map[string]bool
errors []*policyResolutionError
bundleMap *PolicyBundleMap
compilerConfig mqlc.CompilerConfig
}
type policyResolverCache struct {
removedPolicies map[string]struct{} // tracks policies that will not be added
removedQueries map[string]struct{} // tracks queries that will not be added
parentPolicies map[string]struct{} // tracks policies in the ancestry, to prevent loops
childJobsByMrn map[string][]*ReportingJob // tracks policies+queries+checks that were added below (at any level)
global *resolverCache
}
func checksum2string(checksum uint64) string {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, checksum)
return base64.StdEncoding.EncodeToString(b)
}
func checksumStrings(strings ...string) string {
checksum := fnv1a.Init64
for i := range strings {
checksum = fnv1a.AddString64(checksum, strings[i])
}
return checksum2string(checksum)
}
func (r *resolverCache) relativeChecksum(s string) string {
return checksumStrings(r.baseChecksum, r.assetFiltersChecksum, "v2", s)
}
func (p *policyResolverCache) clone() *policyResolverCache {
res := &policyResolverCache{
removedPolicies: map[string]struct{}{},
removedQueries: map[string]struct{}{},
parentPolicies: map[string]struct{}{},
childJobsByMrn: map[string][]*ReportingJob{},
global: p.global,
}
for k, v := range p.removedPolicies {
res.removedPolicies[k] = v
}
for k, v := range p.removedQueries {
res.removedQueries[k] = v
}
for k, v := range p.parentPolicies {
res.parentPolicies[k] = v
}
return res
}
func (p *policyResolverCache) addChildren(other *policyResolverCache) {
// we copy these back into the parent, but don't keep them around in the global
// cache. The reason for that is that policy siblings could accidentally access
// each others jobs when they shouldn't be able to.
// In this sense, reporting jobs by MRN only bubble up, never down or sideways.
for k, v := range other.childJobsByMrn {
p.childJobsByMrn[k] = append(p.childJobsByMrn[k], v...)
}
}
func (s *LocalServices) resolve(ctx context.Context, policyMrn string, assetFilters []*explorer.Mquery) (*ResolvedPolicy, error) {
logCtx := logger.FromContext(ctx)
for i := 0; i < maxResolveRetry; i++ {
resolvedPolicy, err := s.tryResolve(ctx, policyMrn, assetFilters)
if err != nil {
if !errors.Is(err, ErrRetryResolution) {
return nil, err
}
if i+1 < maxResolveRetry {
jitter := time.Duration(rand.Int63n(int64(maxResolveRetryBackoffjitter)))
sleepTime := maxResolveRetryBackoff + jitter
logCtx.Error().Int("try", i+1).Dur("sleepTime", sleepTime).Msg("retrying policy resolution")
time.Sleep(sleepTime)
}
} else {
return resolvedPolicy, nil
}
}
return nil, errors.New("concurrent policy resolve")
}
type nextGenResolverFeature struct{}
func WithNextGenResolver(context.Context) context.Context {
return context.WithValue(context.Background(), nextGenResolverFeature{}, true)
}
func IsNextGenResolver(ctx context.Context) bool {
return ctx.Value(nextGenResolverFeature{}) != nil
}
func (s *LocalServices) tryResolve(ctx context.Context, bundleMrn string, assetFilters []*explorer.Mquery) (*ResolvedPolicy, error) {
logCtx := logger.FromContext(ctx)
now := time.Now()
conf := s.NewCompilerConfig()
// phase 1: resolve asset filters and see if we can find a cached policy
// trying first with all asset filters
allFiltersChecksum, err := ChecksumAssetFilters(assetFilters, conf)
if err != nil {
return nil, err
}
var rp *ResolvedPolicy
rp, err = s.DataLake.CachedResolvedPolicy(ctx, bundleMrn, allFiltersChecksum, V2Code)
if err != nil {
return nil, err
}
if rp != nil {
return rp, nil
}
// next we will try to only use the matching asset filters for the given policy...
bundle, err := s.DataLake.GetValidatedBundle(ctx, bundleMrn)
if err != nil {
return nil, err
}
bundleMap := bundle.ToMap()
frameworkObj := bundleMap.Frameworks[bundleMrn]
policyObj := bundleMap.Policies[bundleMrn]
resolvedPolicyExecutionChecksum := BundleExecutionChecksum(ctx, policyObj, frameworkObj)
matchingFilters, err := MatchingAssetFilters(bundleMrn, assetFilters, policyObj)
if err != nil {
return nil, err
}
if len(matchingFilters) == 0 {
return nil, explorer.NewAssetMatchError(bundleMrn, "policies", "no-matching-policy", assetFilters, policyObj.ComputedFilters)
}
if IsNextGenResolver(ctx) {
resolvedPolicy, err := buildResolvedPolicy(ctx, bundleMrn, bundle, matchingFilters, time.Now(), conf)
if err != nil {
return nil, err
}
err = s.DataLake.SetResolvedPolicy(ctx, bundleMrn, resolvedPolicy, V2Code, false)
if err != nil {
return nil, err
}
return resolvedPolicy, nil
}
assetFiltersMap := make(map[string]struct{}, len(matchingFilters))
for i := range matchingFilters {
assetFiltersMap[matchingFilters[i].CodeId] = struct{}{}
}
assetFiltersChecksum, err := ChecksumAssetFilters(matchingFilters, conf)
if err != nil {
return nil, err
}
// ... and if the filters changed, try to look up the resolved policy again
if assetFiltersChecksum != allFiltersChecksum {
rp, err = s.DataLake.CachedResolvedPolicy(ctx, bundleMrn, assetFiltersChecksum, V2Code)
if err != nil {
return nil, err
}
if rp != nil {
return rp, nil
}
}
// intermission: prep for the other phases
logCtx.Debug().
Str("bundle mrn", bundleMrn).
Interface("asset filters", matchingFilters).
Msg("resolver> phase 1: no cached result, resolve the bundle now")
cache := &resolverCache{
baseChecksum: BundleExecutionChecksum(ctx, policyObj, frameworkObj),
assetFiltersChecksum: assetFiltersChecksum,
assetFilters: assetFiltersMap,
executionQueries: map[string]*ExecutionQuery{},
codeIdToMrn: map[string][]string{},
dataQueries: map[string]struct{}{},
propsCache: explorer.NewPropsCache(),
queriesByMsum: map[string]*explorer.Mquery{},
riskMrns: map[string]*explorer.Mquery{},
riskInfos: map[string]*RiskFactor{},
reportingJobsByUUID: map[string]*ReportingJob{},
reportingJobsByMsum: map[string][]*ReportingJob{},
reportingJobsByCodeId: map[string][]*ReportingJob{},
reportingJobsActive: map[string]bool{},
riskFactors: map[string]*RiskFactor{},
bundleMap: bundleMap,
compilerConfig: conf,
}
rjUUID := cache.relativeChecksum(policyObj.GraphExecutionChecksum)
reportingJob := &ReportingJob{
Uuid: rjUUID,
QrId: "root",
ChildJobs: map[string]*explorer.Impact{},
Datapoints: map[string]bool{},
Type: ReportingJob_POLICY,
}
cache.reportingJobsByUUID[reportingJob.Uuid] = reportingJob
if err := s.collectRisks(ctx, cache, bundleMrn); err != nil {
logCtx.Error().
Err(err).
Str("bundle", bundleMrn).
Msg("resolver> internal error, trying to collect risk modifications")
return nil, err
}
// phase 2: optimizations for assets
// assets are always connected to a space, so figure out if a space policy exists
// everything else in an asset can be aggregated into a shared policy
// TODO: IMPLEMENT
// phase 3: build the policy and scoring tree
policyToJobsCache := &policyResolverCache{
removedPolicies: map[string]struct{}{},
removedQueries: map[string]struct{}{},
parentPolicies: map[string]struct{}{},
childJobsByMrn: map[string][]*ReportingJob{},
global: cache,
}
err = s.policyToJobs(ctx, bundleMrn, reportingJob, policyToJobsCache, now)
if err != nil {
logCtx.Error().
Err(err).
Str("policy", bundleMrn).
Msg("resolver> phase 3: internal error, trying to turn policy mrn into jobs")
return nil, err
}
logCtx.Debug().
Str("policy", bundleMrn).
Msg("resolver> phase 3: turn policy into jobs [ok]")
// phase 4: get all queries + assign them reporting jobs + update scoring jobs
executionJob, collectorJob, err := s.jobsToQueries(ctx, bundleMrn, cache)
if err != nil {
logCtx.Error().
Err(err).
Str("policy", bundleMrn).
Msg("resolver> phase 4: internal error, trying to turn policy jobs into queries")
return nil, err
}
// prune policies without children
// Its possible to get here and have a policy reporting job with no queries attached.
// This happens because a reporting job is created for a policy if its ComputedFilters
// field has a match with the asset filters. This field seems to include all filters
// for any checks/queries that are attached to the policy. If all the policies groups
// could say this group does not match, a reporting job for the policy is still created
// in this case, so we prune them here
reportingJobUUIDs := topologicalSortReportingJobs(collectorJob.ReportingJobs)
for _, rjUUID := range reportingJobUUIDs {
rj := collectorJob.ReportingJobs[rjUUID]
if rj.QrId == "root" {
// If we prune the root, we're going to get a broken resolved policy.
// For example, the framework code that follows wants to report to it.
continue
}
if rj.Type == ReportingJob_POLICY && (len(rj.ChildJobs)+len(rj.Datapoints) == 0) {
logCtx.Debug().
Str("policy", bundleMrn).
Str("uuid", rjUUID).
Str("qrId", rj.QrId).
Msg("resolver> phase 4: pruning empty policy reporting job")
delete(collectorJob.ReportingJobs, rj.Uuid)
for _, parentUuid := range rj.Notify {
parentJob, ok := collectorJob.ReportingJobs[parentUuid]
if !ok {
continue
}
delete(parentJob.ChildJobs, rj.Uuid)
}
}
}
logCtx.Debug().
Str("policy", bundleMrn).
Msg("resolver> phase 4: aggregate queries and jobs [ok]")
// phase 5: add frameworks and controls
resolvedFramework := ResolveFramework(bundleMrn, bundleMap.Frameworks)
cacheFrameworkJobs := &frameworkResolverCache{
resolverCache: cache,
frameworkJobsByMrn: make(map[string]*ReportingJob),
}
if err := s.jobsToFrameworks(cacheFrameworkJobs, resolvedFramework, collectorJob, bundleMrn, reportingJob); err != nil {
logCtx.Error().Err(err).
Str("bundle", bundleMrn).
Msg("resolver> phase 5: internal error, trying to attach framework to resolved policy")
return nil, err
}
if err := s.jobsToControls(cacheFrameworkJobs, resolvedFramework, collectorJob); err != nil {
logCtx.Error().
Err(err).
Str("bundle", bundleMrn).
Msg("resolver> phase 5: internal error, trying to attach controls to resolved policy [ok]")
}
logCtx.Debug().
Str("bundle", bundleMrn).
Msg("resolver> phase 5: resolve controls [ok]")
// phase 6: refresh all checksums
refreshChecksums(executionJob, collectorJob)
// the final phases are done in the DataLake
for _, rj := range collectorJob.ReportingJobs {
rj.RefreshChecksum()
}
resolvedPolicy := ResolvedPolicy{
GraphExecutionChecksum: resolvedPolicyExecutionChecksum,
Filters: matchingFilters,
FiltersChecksum: assetFiltersChecksum,
ExecutionJob: executionJob,
CollectorJob: collectorJob,
ReportingJobUuid: reportingJob.Uuid,
}
err = s.DataLake.SetResolvedPolicy(ctx, bundleMrn, &resolvedPolicy, V2Code, false)
if err != nil {
return nil, err
}
return &resolvedPolicy, nil
}
func refreshChecksums(executionJob *ExecutionJob, collectorJob *CollectorJob) {
// execution job
{
queryKeys := sortx.Keys(executionJob.Queries)
checksum := checksums.New
checksum = checksum.Add("v2")
for i := range queryKeys {
key := queryKeys[i]
checksum = checksum.Add(executionJob.Queries[key].Checksum)
}
executionJob.Checksum = checksum.String()
}
// collector job
{
checksum := checksums.New
{
reportingJobKeys := sortx.Keys(collectorJob.ReportingJobs)
for i := range reportingJobKeys {
key := reportingJobKeys[i]
checksum = checksum.Add(key)
checksum = checksum.Add(collectorJob.ReportingJobs[key].Checksum)
}
}
{
datapointsKeys := sortx.Keys(collectorJob.Datapoints)
for i := range datapointsKeys {
key := datapointsKeys[i]
info := collectorJob.Datapoints[key]
checksum = checksum.Add(key)
checksum = checksum.Add(info.Type)
notify := make([]string, len(info.Notify))
copy(notify, info.Notify)
sort.Strings(notify)
for j := range notify {
checksum = checksum.Add(notify[j])
}
}
}
scoringChecksumStr := checksum.String()
collectorJob.Checksum = scoringChecksumStr
}
}
func (s *LocalServices) collectRisks(ctx context.Context, cache *resolverCache, policyMrn string) error {
policyObj, ok := cache.bundleMap.Policies[policyMrn]
if !ok || policyObj == nil {
return errors.New("cannot find policy '" + policyMrn + "' while resolving")
}
for _, g := range policyObj.Groups {
for _, p := range g.Policies {
if err := s.collectRisks(ctx, cache, p.Mrn); err != nil {
return err
}
}
}
for _, rf := range policyObj.RiskFactors {
s.mergeRisk(cache, rf)
}
return nil
}
func (s *LocalServices) mergeRisk(cache *resolverCache, riskFactor *RiskFactor) {
if existing, ok := cache.riskFactors[riskFactor.Mrn]; ok {
if riskFactor.Magnitude != nil {
existing.Magnitude = riskFactor.Magnitude
}
if riskFactor.Action != explorer.Action_UNSPECIFIED {
existing.Action = riskFactor.Action
}
} else {
cache.riskFactors[riskFactor.Mrn] = riskFactor
}
}
func (s *LocalServices) policyToJobs(ctx context.Context, policyMrn string, ownerJob *ReportingJob,
parentCache *policyResolverCache, now time.Time,
) error {
ctx, span := tracer.Start(ctx, "resolver/policyToJobs")
defer span.End()
policyObj, ok := parentCache.global.bundleMap.Policies[policyMrn]
if !ok || policyObj == nil {
return errors.New("cannot find policy '" + policyMrn + "' while resolving")
}
if len(policyObj.Groups) == 0 && len(policyObj.RiskFactors) == 0 {
return nil
}
cache := parentCache.clone()
cache.parentPolicies[policyMrn] = struct{}{}
// properties to execution queries cache
parentCache.global.propsCache.Add(policyObj.Props...)
// get a list of matching specs
matchingGroups := []*PolicyGroup{}
for i := range policyObj.Groups {
group := policyObj.Groups[i]
// Filter out groups that are not active
if group.EndDate != 0 {
endDate := time.Unix(group.EndDate, 0)
if endDate.Before(now) {
continue
}
}
if group.Filters == nil || len(group.Filters.Items) == 0 {
matchingGroups = append(matchingGroups, group)
continue
}
for j := range group.Filters.Items {
filter := group.Filters.Items[j]
if _, ok := cache.global.assetFilters[filter.CodeId]; ok {
matchingGroups = append(matchingGroups, group)
break
}
}
}
// aggregate all removed policies and queries
for i := range matchingGroups {
group := matchingGroups[i]
for i := range group.Policies {
policy := group.Policies[i]
if policy.Action == explorer.Action_DEACTIVATE {
cache.removedPolicies[policy.Mrn] = struct{}{}
}
}
for i := range group.Checks {
check := group.Checks[i]
if check.Action == explorer.Action_DEACTIVATE || (group.Type == GroupType_DISABLE && group.ReviewStatus != ReviewStatus_REJECTED) {
cache.removedQueries[check.Mrn] = struct{}{}
}
}
for i := range group.Queries {
query := group.Queries[i]
if query.Action == explorer.Action_DEACTIVATE || (group.Type == GroupType_DISABLE && group.ReviewStatus != ReviewStatus_REJECTED) {
cache.removedQueries[query.Mrn] = struct{}{}
}
}
}
// resolve the rest
var err error
for i := range matchingGroups {
group := matchingGroups[i]
if err = s.policyGroupToJobs(ctx, group, ownerJob, cache, now); err != nil {
log.Error().Err(err).Msg("resolver> policyToJobs error")
return err
}
}
if err = s.risksToJobs(ctx, policyObj, ownerJob, cache); err != nil {
return err
}
// finalize
parentCache.addChildren(cache)
return nil
}
func (s *LocalServices) risksToJobs(ctx context.Context, policy *Policy, ownerJob *ReportingJob, cache *policyResolverCache) error {
matchingRisks := map[string]*RiskFactor{}
for _, policyRf := range policy.RiskFactors {
rf := cache.global.riskFactors[policyRf.Mrn]
if rf == nil {
return errors.New("cannot find risk factor '" + policyRf.Mrn + "' while resolving")
}
switch rf.Action {
case explorer.Action_DEACTIVATE, explorer.Action_OUT_OF_SCOPE:
continue
}
if rf.Filters != nil {
for j := range rf.Filters.Items {
filter := rf.Filters.Items[j]
if _, ok := cache.global.assetFilters[filter.CodeId]; ok {
matchingRisks[rf.Mrn] = rf
break
}
}
}
}
if len(matchingRisks) == 0 {
return nil
}
for _, risk := range matchingRisks {
magnitude := risk.Magnitude
cache.global.riskInfos[risk.Mrn] = &RiskFactor{
Scope: risk.Scope,
Magnitude: magnitude,
Resources: risk.Resources,
DeprecatedV11Magnitude: magnitude.GetValue(),
DeprecatedV11IsAbsolute: magnitude.GetIsToxic(),
}
rjUuid := cache.global.relativeChecksum(risk.Mrn)
if riskJob := cache.global.reportingJobsByUUID[rjUuid]; riskJob != nil {
ownerJob.ChildJobs[riskJob.Uuid] = &explorer.Impact{
Scoring: explorer.ScoringSystem_IGNORE_SCORE,
}
riskJob.Notify = append(riskJob.Notify, ownerJob.Uuid)
continue
}
riskJob := &ReportingJob{
QrId: risk.Mrn,
Uuid: rjUuid,
ChildJobs: map[string]*explorer.Impact{},
Type: ReportingJob_RISK_FACTOR,
Notify: []string{ownerJob.Uuid},
}
cache.global.reportingJobsByUUID[riskJob.Uuid] = riskJob
ownerJob.ChildJobs[riskJob.Uuid] = &explorer.Impact{
Scoring: explorer.ScoringSystem_IGNORE_SCORE,
}
for j := range risk.Checks {
check := risk.Checks[j]
if check.Checksum == "" {
return errors.New("invalid check encountered, missing checksum for: " + check.Mrn)
}
if !check.Filters.Supports(cache.global.assetFilters) {
continue
}
cache.addCheckJob(ctx, check, &explorer.Impact{
Scoring: explorer.ScoringSystem_IGNORE_SCORE,
}, riskJob)
cache.global.riskMrns[risk.Mrn] = check
}
for uuid := range riskJob.ChildJobs {
job := cache.global.reportingJobsByUUID[uuid]
job.Type = ReportingJob_RISK_FACTOR
}
}
return nil
}
func (s *LocalServices) policyGroupToJobs(ctx context.Context, group *PolicyGroup, ownerJob *ReportingJob, cache *policyResolverCache, now time.Time) error {
ctx, span := tracer.Start(ctx, "resolver/policyGroupToJobs")
defer span.End()
// include referenced policies
for i := range group.Policies {
policy := group.Policies[i]
impact := policy.Impact
if policy.Action == explorer.Action_IGNORE {
impact = &explorer.Impact{
Scoring: explorer.ScoringSystem_IGNORE_SCORE,
}
}
// ADD
if policy.Action == explorer.Action_UNSPECIFIED || policy.Action == explorer.Action_ACTIVATE || policy.Action == explorer.Action_IGNORE {
if _, ok := cache.parentPolicies[policy.Mrn]; ok {
return errors.New("trying to resolve policy spec twice, it is cyclical for MRN: " + policy.Mrn)
}
if _, ok := cache.removedPolicies[policy.Mrn]; ok {
continue
}
// before adding any reporting job, make sure this policy actually works for
// this set of asset filters
policyObj, ok := cache.global.bundleMap.Policies[policy.Mrn]
if !ok || policyObj == nil {
return errors.New("cannot find policy '" + policy.Mrn + "' while resolving")
}
scoringSystem := policyObj.ScoringSystem
if ss := policy.ScoringSystem; ss != explorer.ScoringSystem_SCORING_UNSPECIFIED {
scoringSystem = ss