-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathalzlib.go
More file actions
1895 lines (1577 loc) · 52.9 KB
/
alzlib.go
File metadata and controls
1895 lines (1577 loc) · 52.9 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
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) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package alzlib
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"sync"
"github.com/Azure/alzlib/assets"
"github.com/Azure/alzlib/cache"
"github.com/Azure/alzlib/internal/processor"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armpolicy"
"github.com/brunoga/deep"
mapset "github.com/deckarep/golang-set/v2"
"github.com/hashicorp/go-multierror"
)
const (
defaultParallelism = 10 // default number of parallel requests to make to Azure APIs
defaultOverwrite = false
defaultUniqueRoleDefinitions = true // default to unique role definitions per management group
// InitialMetadataSliceCapacity is the initial capacity for the metadata slice.
InitialMetadataSliceCapacity = 10
// MaxRecursionDepth is the maximum depth for recursive operations.
MaxRecursionDepth = 5
// PolicySetDefinitionsType is the lowercase type for policy set definitions, without the resource provider.
PolicySetDefinitionsType = "policysetdefinitions"
// PolicyDefinitionsType is the lowercase type for policy definitions, without the resource provider.
PolicyDefinitionsType = "policydefinitions"
)
// AlzLib is the structure that gets built from the the library files
// do not create this directly, use NewAlzLib instead.
type AlzLib struct {
Options *Options
archetypes map[string]*Archetype
architectures map[string]*Architecture
policyAssignments map[string]*assets.PolicyAssignment
policyDefinitions map[string]*assets.PolicyDefinitionVersions
policySetDefinitions map[string]*assets.PolicySetDefinitionVersions
roleDefinitions map[string]*assets.RoleDefinition
defaultPolicyAssignmentValues DefaultPolicyAssignmentValues
metadata []*Metadata
cache BuiltInCache
clients *azureClients
mu sync.RWMutex // mu is a mutex to concurrency protect the AlzLib maps
}
type azureClients struct {
policyClient *armpolicy.ClientFactory
}
// Options are options for the AlzLib.
type Options struct {
// AllowOverwrite allows overwriting of existing policy assignments when processing additional libraries
// with AlzLib.Init().
AllowOverwrite bool
// Parallelism is the number of parallel requests to make to Azure APIs when getting policy definitions
// and policy set definitions.
Parallelism int
// UniqueRoleDefinitions indicates whether to update the role definitions to be unique per management group.
// If this is not set, you may end up with conflicting role definition names.
UniqueRoleDefinitions bool
}
// NewAlzLib returns a new instance of the alzlib library, optionally using the supplied directory
// for additional policy (set) definitions.
// To customize the options for the AlzLib, pass in an AlzLibOptions struct, otherwise the default
// options will be used.
func NewAlzLib(opts *Options) *AlzLib {
if opts == nil {
opts = defaultAlzLibOptions()
}
az := &AlzLib{
Options: opts,
archetypes: make(map[string]*Archetype),
architectures: make(map[string]*Architecture),
policyAssignments: make(map[string]*assets.PolicyAssignment),
policyDefinitions: make(map[string]*assets.PolicyDefinitionVersions),
policySetDefinitions: make(map[string]*assets.PolicySetDefinitionVersions),
roleDefinitions: make(map[string]*assets.RoleDefinition),
metadata: make([]*Metadata, 0, InitialMetadataSliceCapacity),
defaultPolicyAssignmentValues: make(DefaultPolicyAssignmentValues),
clients: new(azureClients),
mu: sync.RWMutex{},
}
return az
}
func defaultAlzLibOptions() *Options {
return &Options{
Parallelism: defaultParallelism,
AllowOverwrite: defaultOverwrite,
UniqueRoleDefinitions: defaultUniqueRoleDefinitions,
}
}
// Metadata returns all the registered metadata in the AlzLib struct.
func (az *AlzLib) Metadata() []*Metadata {
az.mu.RLock()
defer az.mu.RUnlock()
return deep.MustCopy(az.metadata)
}
// AddPolicyAssignments adds policy assignments to the AlzLib struct.
func (az *AlzLib) AddPolicyAssignments(pas ...*assets.PolicyAssignment) error {
az.mu.Lock()
defer az.mu.Unlock()
for _, pa := range pas {
if pa == nil || pa.Name == nil || *pa.Name == "" {
continue
}
if _, exists := az.policyAssignments[*pa.Name]; exists && !az.Options.AllowOverwrite {
return fmt.Errorf(
"Alzlib.AddPolicyAssignments: policy assignment with name %s already exists and allow overwrite not set",
*pa.Name,
)
}
cpy, err := deep.Copy(pa)
if err != nil {
return fmt.Errorf(
"Alzlib.AddPolicyAssignments: error making deep copy of policy assignment %s: %w",
*pa.Name,
err,
)
}
az.policyAssignments[*pa.Name] = cpy
}
return nil
}
// AddPolicyDefinitions adds policy definitions to the AlzLib struct.
func (az *AlzLib) AddPolicyDefinitions(pds ...*assets.PolicyDefinition) error {
az.mu.Lock()
defer az.mu.Unlock()
var merr error
for _, pd := range pds {
if pd == nil || pd.Name == nil || *pd.Name == "" {
continue
}
if pdvc, exists := az.policyDefinitions[*pd.Name]; exists {
if err := pdvc.Add(pd, az.Options.AllowOverwrite); err != nil {
merr = multierror.Append(merr, pdvc.Upsert(pdvc, az.Options.AllowOverwrite))
}
continue
}
cpy := deep.MustCopy(pd)
pdvc := assets.NewPolicyDefinitionVersions()
pdvc.Add(cpy, az.Options.AllowOverwrite) // nolint:errcheck
az.policyDefinitions[*pd.Name] = pdvc
}
return merr
}
// AddPolicySetDefinitions adds policy set definitions to the AlzLib struct.
func (az *AlzLib) AddPolicySetDefinitions(psds ...*assets.PolicySetDefinition) error {
az.mu.Lock()
defer az.mu.Unlock()
var merr error
for _, psd := range psds {
if psd == nil || psd.Name == nil || *psd.Name == "" {
continue
}
if psdvc, exists := az.policySetDefinitions[*psd.Name]; exists {
if err := psdvc.Add(psd, az.Options.AllowOverwrite); err != nil {
merr = multierror.Append(merr, err)
}
continue
}
cpy := deep.MustCopy(psd)
psdvc := assets.NewPolicySetDefinitionVersions()
psdvc.Add(cpy, az.Options.AllowOverwrite) // nolint:errcheck
az.policySetDefinitions[*psd.Name] = psdvc
}
return merr
}
// AddRoleDefinitions adds role definitions to the AlzLib struct.
func (az *AlzLib) AddRoleDefinitions(rds ...*assets.RoleDefinition) error {
az.mu.Lock()
defer az.mu.Unlock()
for _, rd := range rds {
if rd == nil || rd.Name == nil || *rd.Name == "" {
continue
}
if _, exists := az.roleDefinitions[*rd.Name]; exists && !az.Options.AllowOverwrite {
return fmt.Errorf(
"Alzlib.AddRoleDefinitions: role definition with name %s already exists and allow overwrite not set",
*rd.Name,
)
}
cpy, err := deep.Copy(rd)
if err != nil {
return fmt.Errorf(
"Alzlib.AddRoleDefinitions: error making deep copy of role definition %s: %w",
*rd.Name,
err,
)
}
az.roleDefinitions[*rd.Name] = cpy
}
return nil
}
// PolicyAssignments returns a slice of all the policy assignment names in the library.
func (az *AlzLib) PolicyAssignments() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.policyAssignments))
for k := range az.policyAssignments {
result = append(result, k)
}
slices.Sort(result)
return result
}
// PolicyDefinitions returns a slice of all the policy definition names in the library.
func (az *AlzLib) PolicyDefinitions() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.policyDefinitions))
for k := range az.policyDefinitions {
result = append(result, k)
}
slices.Sort(result)
return result
}
// PolicySetDefinitions returns a slice of all the policy set definition names in the library.
func (az *AlzLib) PolicySetDefinitions() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.policySetDefinitions))
for k := range az.policySetDefinitions {
result = append(result, k)
}
slices.Sort(result)
return result
}
// RoleDefinitions returns a slice of all the role definition names in the library.
func (az *AlzLib) RoleDefinitions() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.roleDefinitions))
for k := range az.roleDefinitions {
result = append(result, k)
}
slices.Sort(result)
return result
}
// Archetypes returns a list of the archetypes in the AlzLib struct.
func (az *AlzLib) Archetypes() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.archetypes))
for k := range az.archetypes {
result = append(result, k)
}
slices.Sort(result)
return result
}
// Archetype returns a copy of the requested archetype by name.
func (az *AlzLib) Archetype(name string) *Archetype {
az.mu.RLock()
defer az.mu.RUnlock()
arch, ok := az.archetypes[name]
if !ok {
return nil
}
return arch.copy()
}
// Architectures returns a list of the architecture names in the AlzLib struct.
func (az *AlzLib) Architectures() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.architectures))
for k := range az.architectures {
result = append(result, k)
}
slices.Sort(result)
return result
}
// PolicyDefaultValues returns a sorted list of the default policy assignment default values in the
// AlzLib struct.
func (az *AlzLib) PolicyDefaultValues() []string {
az.mu.RLock()
defer az.mu.RUnlock()
result := make([]string, 0, len(az.defaultPolicyAssignmentValues))
for k := range az.defaultPolicyAssignmentValues {
result = append(result, k)
}
slices.Sort(result)
return result
}
// PolicyDefaultValue returns a copy of the requested default policy assignment default values by name.
func (az *AlzLib) PolicyDefaultValue(name string) *DefaultPolicyAssignmentValuesValue {
az.mu.RLock()
defer az.mu.RUnlock()
val, ok := az.defaultPolicyAssignmentValues[name]
if !ok {
return nil
}
ret := val.copy()
return &ret
}
// Architecture returns the requested architecture.
func (az *AlzLib) Architecture(name string) *Architecture {
az.mu.RLock()
defer az.mu.RUnlock()
arch, ok := az.architectures[name]
if !ok {
return nil
}
return arch
}
// PolicyDefinitionExists returns true if the policy definition name exists in the AlzLib struct.
func (az *AlzLib) PolicyDefinitionExists(name string, version *string) bool {
az.mu.RLock()
defer az.mu.RUnlock()
pdvc, exists := az.policyDefinitions[name]
if !exists {
return false
}
pdv, err := pdvc.GetVersion(version)
if err != nil {
return false
}
return pdv != nil
}
// PolicySetDefinitionExists returns true if the policy set definition name and version exists in the AlzLib
// struct.
func (az *AlzLib) PolicySetDefinitionExists(name string, version *string) bool {
az.mu.RLock()
defer az.mu.RUnlock()
psdvc, exists := az.policySetDefinitions[name]
if !exists {
return false
}
psdv, err := psdvc.GetVersion(version)
if err != nil {
return false
}
return psdv != nil
}
// PolicyAssignmentExists returns true if the policy assignment exists name in the AlzLib struct.
func (az *AlzLib) PolicyAssignmentExists(name string) bool {
az.mu.RLock()
defer az.mu.RUnlock()
_, exists := az.policyAssignments[name]
return exists
}
// RoleDefinitionExists returns true if the role definition name exists in the AlzLib struct.
func (az *AlzLib) RoleDefinitionExists(name string) bool {
az.mu.RLock()
defer az.mu.RUnlock()
_, exists := az.roleDefinitions[name]
return exists
}
// PolicyDefinition returns a deep copy of the requested policy definition version.
// This is safe to modify without affecting the original.
func (az *AlzLib) PolicyDefinition(name string, version *string) *assets.PolicyDefinition {
az.mu.RLock()
defer az.mu.RUnlock()
pd, ok := az.policyDefinitions[name]
if !ok {
return nil
}
pdv, err := pd.GetVersion(version)
if err != nil {
return nil
}
return deep.MustCopy(pdv)
}
// SetAssignPermissionsOnDefinitionParameter sets the AssignPermissions metadata field to true for
// for the definition (all versions) and parameter with the given name.
func (az *AlzLib) SetAssignPermissionsOnDefinitionParameter(
definitionName string, parameterName string,
) {
az.mu.Lock()
defer az.mu.Unlock()
definition, ok := az.policyDefinitions[definitionName]
if !ok {
return
}
for def := range definition.AllVersions() {
def.SetAssignPermissionsOnParameter(parameterName)
}
}
// UnsetAssignPermissionsOnDefinitionParameter removes the AssignPermissions metadata field to true
// for the definition (all versions) and parameter with the given name.
func (az *AlzLib) UnsetAssignPermissionsOnDefinitionParameter(
definitionName string, parameterName string,
) {
az.mu.Lock()
defer az.mu.Unlock()
definition, ok := az.policyDefinitions[definitionName]
if !ok {
return
}
for def := range definition.AllVersions() {
def.UnsetAssignPermissionsOnParameter(parameterName)
}
}
// PolicyAssignment returns a deep copy of the requested policy assignment.
// This is safe to modify without affecting the original.
func (az *AlzLib) PolicyAssignment(name string) *assets.PolicyAssignment {
az.mu.RLock()
defer az.mu.RUnlock()
pa, ok := az.policyAssignments[name]
if !ok {
return nil
}
return deep.MustCopy(pa)
}
// PolicySetDefinition returns a deep copy of the requested policy set definition.
// This is safe to modify without affecting the original.
func (az *AlzLib) PolicySetDefinition(name string, version *string) *assets.PolicySetDefinition {
az.mu.RLock()
defer az.mu.RUnlock()
psd, ok := az.policySetDefinitions[name]
if !ok {
return nil
}
psdv, err := psd.GetVersion(version)
if err != nil {
return nil
}
return deep.MustCopy(psdv)
}
// RoleDefinition returns a deep copy of the requested role definition.
// This is safe to modify without affecting the original.
func (az *AlzLib) RoleDefinition(name string) *assets.RoleDefinition {
az.mu.RLock()
defer az.mu.RUnlock()
rd, ok := az.roleDefinitions[name]
if !ok {
return nil
}
return deep.MustCopy(rd)
}
// BuiltInCache is an interface for providing cached built-in Azure policy definitions
// and policy set definitions. When a complete cache is supplied via [AlzLib.AddCache],
// the policy client ([AlzLib.AddPolicyClient]) is not required because
// [AlzLib.GetDefinitionsFromAzure] will find every definition in the cache and skip
// all Azure API calls.
type BuiltInCache interface {
PolicyDefinitions() map[string]*assets.PolicyDefinitionVersions
PolicySetDefinitions() map[string]*assets.PolicySetDefinitionVersions
// PolicyDefinitionVersionsByName returns the policy definition versions for the given name,
// or nil if not found.
PolicyDefinitionVersionsByName(name string) *assets.PolicyDefinitionVersions
// PolicySetDefinitionVersionsByName returns the policy set definition versions for the given name,
// or nil if not found.
PolicySetDefinitionVersionsByName(name string) *assets.PolicySetDefinitionVersions
}
// AddCache stores a [BuiltInCache] for lazy lookup during [AlzLib.GetDefinitionsFromAzure].
// Definitions are fetched from the cache on demand rather than being loaded eagerly.
// The cache is retained for the lifetime of AlzLib; call AddCache(nil) to release it
// explicitly and allow the garbage collector to reclaim the memory.
// A previously stored cache is replaced by the new one.
func (az *AlzLib) AddCache(c BuiltInCache) {
az.mu.Lock()
defer az.mu.Unlock()
az.cache = c
}
// ExportBuiltInCache creates a [cache.Cache] from the built-in policy definitions and policy
// set definitions that are currently loaded in AlzLib. Definitions are included when their
// policy type is [armpolicy.PolicyTypeBuiltIn], [armpolicy.PolicyTypeStatic], or is
// unspecified/nil (which is treated as built-in); custom definitions (loaded from library
// files) are excluded.
//
// This is useful when callers want to persist a minimal cache covering only the definitions
// referenced by their specific library — rather than using alzlibtool to cache everything.
// The returned cache can be saved with [cache.Cache.Save] and reloaded later with
// [cache.NewCache], then re-injected via [AlzLib.AddCache] to skip Azure API calls on
// subsequent runs.
func (az *AlzLib) ExportBuiltInCache() *cache.Cache {
az.mu.RLock()
defer az.mu.RUnlock()
pds := make(map[string]*assets.PolicyDefinitionVersions)
psds := make(map[string]*assets.PolicySetDefinitionVersions)
for name, pdvs := range az.policyDefinitions {
if !isBuiltInPolicyDefinitionVersions(pdvs) {
continue
}
pds[name] = deep.MustCopy(pdvs)
}
for name, psdvs := range az.policySetDefinitions {
if !isBuiltInPolicySetDefinitionVersions(psdvs) {
continue
}
psds[name] = deep.MustCopy(psdvs)
}
return cache.NewCacheFromDefinitions(pds, psds)
}
// isBuiltInPolicyDefinitionVersions returns true if any version in the collection has a
// built-in or static policy type. Collections with no type set are treated as built-in to
// ensure definitions fetched from Azure (which always set PolicyType) are never excluded.
func isBuiltInPolicyDefinitionVersions(pdvs *assets.PolicyDefinitionVersions) bool {
for def := range pdvs.AllVersions() {
if def.Properties == nil || def.Properties.PolicyType == nil {
return true
}
switch *def.Properties.PolicyType {
case armpolicy.PolicyTypeBuiltIn, armpolicy.PolicyTypeStatic:
return true
}
}
return false
}
// isBuiltInPolicySetDefinitionVersions returns true if any version in the collection has a
// built-in or static policy type. Collections with no type set are treated as built-in.
func isBuiltInPolicySetDefinitionVersions(psdvs *assets.PolicySetDefinitionVersions) bool {
for def := range psdvs.AllVersions() {
if def.Properties == nil || def.Properties.PolicyType == nil {
return true
}
switch *def.Properties.PolicyType {
case armpolicy.PolicyTypeBuiltIn, armpolicy.PolicyTypeStatic:
return true
}
}
return false
}
// AddPolicyClient adds an authenticated *armpolicy.ClientFactory to the AlzLib struct.
// This is needed to get policy objects from Azure.
func (az *AlzLib) AddPolicyClient(client *armpolicy.ClientFactory) {
az.mu.Lock()
defer az.mu.Unlock()
az.clients.policyClient = client
}
// Init processes ALZ libraries, supplied as `LibraryReference` interfaces.
// Use FetchAzureLandingZonesLibraryMember/FetchLibraryByGetterString to get the library from
// GitHub.
// It populates the struct with the results of the processing.
func (az *AlzLib) Init(ctx context.Context, libs ...LibraryReference) error {
az.mu.Lock()
defer az.mu.Unlock()
if az.Options == nil || az.Options.Parallelism == 0 {
return errors.New("Alzlib.Init: alzlib Options not set or parallelism is `0`")
}
// Process the libraries
for _, ref := range libs {
if ref == nil {
return errors.New("Alzlib.Init: library is nil")
}
if ref.FS() == nil {
if _, err := ref.Fetch(ctx, hash(ref)); err != nil {
return fmt.Errorf("Alzlib.Init: error fetching library %s: %w", ref, err)
}
}
res := processor.NewResult()
pc := processor.NewClient(ref.FS())
if err := pc.Process(res); err != nil {
return fmt.Errorf("Alzlib.Init: error processing library %v: %w", ref, err)
}
if res.Metadata != nil {
az.metadata = append(az.metadata, NewMetadata(res.Metadata, ref))
}
// Put results into the AlzLib.
if err := az.addPolicyAndRoleAssets(res); err != nil {
return fmt.Errorf("Alzlib.Init: error adding processed result to AlzLib: %w", err)
}
// Add default policy values
if err := az.addDefaultPolicyAssignmentValues(res); err != nil {
return fmt.Errorf(
"Alzlib.Init: error adding default policy assignment values to AlzLib: %w",
err,
)
}
// Generate archetypes
if err := az.generateArchetypes(res); err != nil {
return fmt.Errorf("Alzlib.Init: error generating archetypes: %w", err)
}
// Generate override archetypes
if err := az.generateOverrideArchetypes(res); err != nil {
return fmt.Errorf("Alzlib.Init: error generating override archetypes: %w", err)
}
// Generate architectures
if err := az.generateArchitectures(res); err != nil {
return fmt.Errorf("Alzlib.Init: error generating architectures: %w", err)
}
}
return nil
}
// GetDefinitionsFromAzure takes a slice of requests for built-in definitions.
// It fetches requested definitions from Azure only when they do not already exist in AlzLib
// (determined by the last segment of the resource ID). For policy set definitions, existing
// sets in AlzLib are inspected to discover referenced built-in definitions, and any missing
// referenced definitions are then fetched as needed.
// If a cache has been set via [AlzLib.AddCache], definitions are looked up from the cache
// before falling back to Azure API calls.
// The cache is retained for the lifetime of AlzLib; callers can explicitly clear it by calling
// AddCache(nil) when they no longer need it.
func (az *AlzLib) GetDefinitionsFromAzure(ctx context.Context, reqs []BuiltInRequest) error {
policyDefsToGet := make([]BuiltInRequest, 0, len(reqs))
policySetDefsToGet := make([]BuiltInRequest, 0, len(reqs))
for _, req := range reqs {
if req.ResourceID == nil {
return fmt.Errorf("Alzlib.GetDefinitionsFromAzure: resource ID is nil in BuiltInRequest")
}
switch strings.ToLower(req.ResourceID.ResourceType.Type) {
case PolicyDefinitionsType:
if !az.PolicyDefinitionExists(req.ResourceID.Name, req.Version) {
policyDefsToGet = append(policyDefsToGet, req)
}
case PolicySetDefinitionsType:
// If the set is not present, OR if the set contains referenced definitions that are not
// present add it to the list of set defs to get.
exists := az.PolicySetDefinitionExists(req.ResourceID.Name, req.Version)
if !exists {
policySetDefsToGet = append(policySetDefsToGet, req)
continue
}
psd := az.PolicySetDefinition(req.ResourceID.Name, req.Version)
if psd == nil {
version := "<nil>"
if req.Version != nil {
version = *req.Version
}
return fmt.Errorf(
"Alzlib.GetDefinitionsFromAzure: error getting policy set definition %s@%s",
req.ResourceID,
version,
)
}
// This is already made safe to access by the constructor.
pdrefs := psd.Properties.PolicyDefinitions
for _, ref := range pdrefs {
subResID, err := arm.ParseResourceID(*ref.PolicyDefinitionID)
if err != nil {
return fmt.Errorf(
"Alzlib.GetDefinitionsFromAzure: policy set definition %s error parsing referenced definition resource id: %w",
*psd.Name,
err,
)
}
if !az.PolicyDefinitionExists(subResID.Name, ref.DefinitionVersion) {
subReq := BuiltInRequest{
ResourceID: subResID,
Version: ref.DefinitionVersion,
}
policyDefsToGet = append(policyDefsToGet, subReq)
}
}
default:
return fmt.Errorf(
"Alzlib.GetDefinitionsFromAzure: unexpected policy definition type when processing assignments: %s",
req,
)
}
}
// Add the referenced built-in definitions and set definitions to the AlzLib struct
// so that we can use the data to determine the correct role assignments at scope.
if len(policyDefsToGet) != 0 {
if err := az.getBuiltInPolicies(ctx, policyDefsToGet); err != nil {
return fmt.Errorf(
"Alzlib.GetDefinitionsFromAzure: error getting built-in policy definitions: %w",
err,
)
}
}
if len(policySetDefsToGet) != 0 {
if err := az.getBuiltInPolicySets(ctx, policySetDefsToGet); err != nil {
return fmt.Errorf(
"Alzlib.GetDefinitionsFromAzure: error getting built-in policy set definitions: %w",
err,
)
}
}
return nil
}
// AssignmentReferencedDefinitionHasParameter checks if the referenced definition of an assignment
// has a specific parameter. It takes a resource ID and a parameter name as input and returns a
// boolean indicating whether the parameter exists or not.
func (az *AlzLib) AssignmentReferencedDefinitionHasParameter(
res *arm.ResourceID,
definitionVersion *string,
param string,
) bool {
switch strings.ToLower(res.ResourceType.Type) {
case PolicyDefinitionsType:
pd := az.PolicyDefinition(res.Name, definitionVersion)
if pd == nil {
// If we don't have the definition, return true as this won't cause an issue.
// We might be checking that a policy default value exists for a definition that isn't assigned.
return true
}
if pd.Parameter(param) != nil {
return true
}
case PolicySetDefinitionsType:
psd := az.PolicySetDefinition(res.Name, definitionVersion)
if psd == nil {
// If we don't have the definition, return true as this won't cause an issue.
// We might be checking that a policy default value exists for a definition that isn't assigned.
return true
}
if psd.Parameter(param) != nil {
return true
}
}
return false
}
// policyDefinitionVersionsPager exposes the subset of pager behaviour needed for testing.
type policyDefinitionVersionsPager interface {
More() bool
NextPage(context.Context) (armpolicy.DefinitionVersionsClientListBuiltInResponse, error)
}
// policySetDefinitionVersionsPager exposes the subset of pager behaviour needed for testing.
type policySetDefinitionVersionsPager interface {
More() bool
NextPage(context.Context) (armpolicy.SetDefinitionVersionsClientListBuiltInResponse, error)
}
// policyDefinitionFromCache returns the policy definition for the given name and version
// from the cache, or nil if the cache is unset or does not contain a matching entry.
func (az *AlzLib) policyDefinitionFromCache(name string, version *string) (*assets.PolicyDefinition, error) {
az.mu.RLock()
c := az.cache
az.mu.RUnlock()
if c == nil {
return nil, nil
}
pdvs := c.PolicyDefinitionVersionsByName(name)
if pdvs == nil {
return nil, nil
}
pd, err := pdvs.GetVersion(version)
if err != nil {
if errors.Is(err, assets.ErrNoVersionFound) {
return nil, nil
}
return nil, fmt.Errorf("getting policy definition %s from cache: %w", JoinNameAndVersion(name, version), err)
}
return pd, nil
}
// policySetDefinitionFromCache returns the policy set definition for the given name and version
// from the cache, or nil if the cache is unset or does not contain a matching entry.
func (az *AlzLib) policySetDefinitionFromCache(name string, version *string) (*assets.PolicySetDefinition, error) {
az.mu.RLock()
c := az.cache
az.mu.RUnlock()
if c == nil {
return nil, nil
}
psdvs := c.PolicySetDefinitionVersionsByName(name)
if psdvs == nil {
return nil, nil
}
psd, err := psdvs.GetVersion(version)
if err != nil {
if errors.Is(err, assets.ErrNoVersionFound) {
return nil, nil
}
return nil, fmt.Errorf("getting policy set definition %s from cache: %w", JoinNameAndVersion(name, version), err)
}
return psd, nil
}
// getBuiltInPolicies retrieves the built-in policy definitions with the given names
// and adds them to the AlzLib struct.
func (az *AlzLib) getBuiltInPolicies(ctx context.Context, reqs []BuiltInRequest) error {
var (
versionedClient *armpolicy.DefinitionVersionsClient
client *armpolicy.DefinitionsClient
)
for _, req := range reqs {
if az.PolicyDefinitionExists(req.ResourceID.Name, req.Version) {
continue
}
// Check cache before calling Azure.
pdv, cacheErr := az.policyDefinitionFromCache(req.ResourceID.Name, req.Version)
if cacheErr != nil {
return fmt.Errorf(
"Alzlib.getBuiltInPolicies: looking up cached built-in policy definition %s: %w",
JoinNameAndVersion(req.ResourceID.Name, req.Version),
cacheErr,
)
}
if pdv != nil {
if err := az.AddPolicyDefinitions(pdv); err != nil {
return fmt.Errorf(
"Alzlib.getBuiltInPolicies: adding cached built-in policy definition %s: %w",
JoinNameAndVersion(req.ResourceID.Name, req.Version),
err,
)
}
continue
}
// Fall back to Azure.
az.mu.RLock()
policyClient := az.clients.policyClient
az.mu.RUnlock()
if policyClient == nil {
return errors.New("Alzlib.getBuiltInPolicies: policy client not set")
}
// Lazily initialise clients on first Azure call.
if client == nil {
versionedClient = policyClient.NewDefinitionVersionsClient()
client = policyClient.NewDefinitionsClient()
}
var err error
switch req.Version {
case nil:
err = az.addLatestPolicyDefinition(ctx, client, req)
default:
err = az.addVersionedPolicyDefinition(ctx, versionedClient, req)
}
if err != nil {
return err
}
}
return nil
}
// getBuiltInPolicySets retrieves the built-in policy set definitions with the given names
// and adds them to the AlzLib struct.
func (az *AlzLib) getBuiltInPolicySets(ctx context.Context, reqs []BuiltInRequest) error {
processedRequests := make([]*assets.PolicySetDefinition, 0, len(reqs))
var (
versionedClient *armpolicy.SetDefinitionVersionsClient
client *armpolicy.SetDefinitionsClient
)
for _, req := range reqs {