-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfn.go
More file actions
1522 lines (1282 loc) · 50.8 KB
/
fn.go
File metadata and controls
1522 lines (1282 loc) · 50.8 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
package main
import (
"context"
"encoding/json"
"fmt"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
azauth "github.com/microsoft/kiota-authentication-azure-go"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
"github.com/microsoftgraph/msgraph-sdk-go/groups"
"github.com/microsoftgraph/msgraph-sdk-go/models"
"github.com/microsoftgraph/msgraph-sdk-go/serviceprincipals"
"github.com/microsoftgraph/msgraph-sdk-go/users"
"github.com/upbound/function-msgraph/input/v1beta1"
"google.golang.org/protobuf/types/known/structpb"
"k8s.io/utils/ptr"
"github.com/crossplane/function-sdk-go/errors"
"github.com/crossplane/function-sdk-go/logging"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/request"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/resource/composed"
"github.com/crossplane/function-sdk-go/resource/composite"
"github.com/crossplane/function-sdk-go/response"
)
var (
// MSGraphScopes defines the default MS Graph scopes
MSGraphScopes = []string{"https://graph.microsoft.com/.default"}
)
const (
// TenantID defines the azure credentials key for tenant id
TenantID = "tenantId"
// ClientID defines the azure credentials key for client id
ClientID = "clientId"
// ClientSecret defines the azure credentials key for client secret
ClientSecret = "clientSecret"
// WorkloadIdentityCredentialPath defines the azure credentials key for federated token file path
WorkloadIdentityCredentialPath = "federatedTokenFile"
)
const (
// LastExecutionAnnotation notifies the user when was the last time that Operation has run the query
LastExecutionAnnotation = "function-msgraph/last-execution"
// LastExecutionQueryDriftDetectedAnnotation notifies the user that the drift was detected after Operation has run the query
LastExecutionQueryDriftDetectedAnnotation = "function-msgraph/last-execution-query-drift-detected"
)
// GraphQueryInterface defines the methods required for querying Microsoft Graph API.
type GraphQueryInterface interface {
graphQuery(ctx context.Context, azureCreds map[string]string, in *v1beta1.Input) (interface{}, error)
}
// TimerInterface defines the methods required to generate the current timestamp
type TimerInterface interface {
now() string
}
// Function returns whatever response you ask it to.
type Function struct {
fnv1.UnimplementedFunctionRunnerServiceServer
graphQuery GraphQueryInterface
log logging.Logger
timer TimerInterface
}
// RunFunction runs the Function.
func (f *Function) RunFunction(ctx context.Context, req *fnv1.RunFunctionRequest) (*fnv1.RunFunctionResponse, error) {
f.log.Info("Running function", "tag", req.GetMeta().GetTag())
rsp := response.To(req, response.DefaultTTL)
// Check if pipeline runs as Composition or Operation
inOperation := (req.GetObserved().GetComposite() == nil)
// Initialize response with desired XR and preserve context
if err := f.initializeResponse(req, rsp, inOperation); err != nil {
return rsp, nil //nolint:nilerr // errors are handled in rsp
}
// Parse input and get credentials
in, azureCreds, err := f.parseInputAndCredentials(req, rsp)
if err != nil {
return rsp, nil //nolint:nilerr // errors are handled in rsp
}
// Validate and prepare input
if !f.validateAndPrepareInput(ctx, req, in, rsp, inOperation) {
return rsp, nil // Early return if validation failed or query should be skipped
}
// Execute the query and process results
if !f.executeAndProcessQuery(ctx, req, in, azureCreds, rsp, inOperation) {
return rsp, nil // Error already handled in response
}
// Set success condition
response.ConditionTrue(rsp, "FunctionSuccess", "Success").
TargetCompositeAndClaim()
return rsp, nil
}
// parseInputAndCredentials parses the input and gets the credentials.
func (f *Function) parseInputAndCredentials(req *fnv1.RunFunctionRequest, rsp *fnv1.RunFunctionResponse) (*v1beta1.Input, map[string]string, error) {
in := &v1beta1.Input{}
if err := request.GetInput(req, in); err != nil {
response.ConditionFalse(rsp, "FunctionSuccess", "InternalError").
WithMessage("Something went wrong.").
TargetCompositeAndClaim()
response.Warning(rsp, errors.New("something went wrong")).
TargetCompositeAndClaim()
response.Fatal(rsp, errors.Wrapf(err, "cannot get Function input from %T", req))
return nil, nil, err
}
azureCreds, err := getCreds(req)
if err != nil {
response.Fatal(rsp, err)
return nil, nil, err
}
if f.graphQuery == nil {
f.graphQuery = &GraphQuery{}
}
return in, azureCreds, nil
}
// getDXRAndStatus retrieves status and desired XR, handling initialization if needed
func (f *Function) getDXRAndStatus(req *fnv1.RunFunctionRequest, inOperation bool) (map[string]interface{}, *resource.Composite, error) {
// Get composite resources
oxr, dxr, err := f.getObservedAndDesired(req, inOperation)
if err != nil {
return nil, nil, err
}
// Initialize and copy data
f.initializeAndCopyData(oxr, dxr, inOperation)
// Get status
xrStatus := f.getStatusFromResources(oxr, dxr)
return xrStatus, dxr, nil
}
// getDXRAndStatus retrieves status and desired XR, handling initialization if needed
func (f *Function) getOXRAndStatus(req *fnv1.RunFunctionRequest, inOperation bool) (map[string]interface{}, *resource.Composite, error) {
// Get composite resources
oxr, dxr, err := f.getObservedAndDesired(req, inOperation)
if err != nil {
return nil, nil, err
}
// Initialize and copy data
f.initializeAndCopyData(oxr, dxr, inOperation)
// Get status
xrStatus := f.getStatusFromResources(oxr, dxr)
return xrStatus, oxr, nil
}
// getObservedAndDesired gets both observed and desired XR resources
func (f *Function) getObservedAndDesired(req *fnv1.RunFunctionRequest, inOperation bool) (*resource.Composite, *resource.Composite, error) {
if !inOperation {
f.log.Debug("triggered by composite resource")
return getObservedAndDesiredInComposition(req)
}
f.log.Debug("triggered by operation")
return getObservedAndDesiredInOperation(req)
}
func getObservedAndDesiredInComposition(req *fnv1.RunFunctionRequest) (*resource.Composite, *resource.Composite, error) {
oxr, err := request.GetObservedCompositeResource(req)
if err != nil {
return nil, nil, errors.Wrap(err, "cannot get observed composite resource")
}
dxr, err := request.GetDesiredCompositeResource(req)
if err != nil {
return nil, nil, errors.Wrap(err, "cannot get desired composite resource")
}
return oxr, dxr, nil
}
func getObservedAndDesiredInOperation(req *fnv1.RunFunctionRequest) (*resource.Composite, *resource.Composite, error) {
rr, err := request.GetRequiredResources(req)
if err != nil {
return nil, nil, errors.Wrap(err, "operation: cannot get required resources")
}
rs, found := rr["ops.crossplane.io/watched-resource"]
if !found {
return nil, nil, fmt.Errorf("operation: no resource to process with name %s", "ops.crossplane.io/watched-resource")
}
if len(rs) != 1 {
return nil, nil, fmt.Errorf("operation: incorrect number of resources sent to the function. expected 1, got %d", len(rs))
}
r := rs[0]
if r.Resource == nil {
return nil, nil, errors.New("operation: Resource property in operation resource can not be nil")
}
if len(r.Resource.Object) == 0 {
return nil, nil, errors.New("operation: Resource.Object property in operation resource can not be empty")
}
if !slices.Contains(r.Resource.GetFinalizers(), "composite.apiextensions.crossplane.io") {
return nil, nil, errors.New("operation: function-msgraph support only operations on composite resources")
}
oxr := &resource.Composite{
Resource: composite.New(),
}
dxr := &resource.Composite{
Resource: composite.New(),
}
oxr.Resource.Object = r.Resource.Object
// Preserve only apiVersion, kind and metadata.name, metadata.annotations from OXR
dxr.Resource.SetAPIVersion(oxr.Resource.GetAPIVersion())
dxr.Resource.SetKind(oxr.Resource.GetKind())
dxr.Resource.SetName(oxr.Resource.GetName())
if oxrNs := oxr.Resource.GetNamespace(); oxrNs != "" {
dxr.Resource.SetNamespace(oxrNs)
}
if oxrAnnotations := oxr.Resource.GetAnnotations(); oxrAnnotations != nil {
dxr.Resource.SetAnnotations(oxrAnnotations)
}
return oxr, dxr, nil
}
// initializeAndCopyData initializes metadata and copies spec
func (f *Function) initializeAndCopyData(oxr, dxr *resource.Composite, inOperation bool) {
// Initialize dxr from oxr if needed
if dxr.Resource.GetKind() == "" {
dxr.Resource.SetAPIVersion(oxr.Resource.GetAPIVersion())
dxr.Resource.SetKind(oxr.Resource.GetKind())
dxr.Resource.SetName(oxr.Resource.GetName())
}
if !inOperation {
// Copy spec from observed to desired XR to preserve it in Composition pipeline
xrSpec := make(map[string]interface{})
if err := oxr.Resource.GetValueInto("spec", &xrSpec); err == nil && len(xrSpec) > 0 {
if err := dxr.Resource.SetValue("spec", xrSpec); err != nil {
f.log.Debug("Cannot set spec in desired XR", "error", err)
}
}
}
}
// getStatusFromResources gets status from desired or observed XR
func (f *Function) getStatusFromResources(oxr, dxr *resource.Composite) map[string]interface{} {
xrStatus := make(map[string]interface{})
// First try to get status from desired XR (pipeline changes)
if dxr.Resource.GetKind() != "" {
err := dxr.Resource.GetValueInto("status", &xrStatus)
if err == nil && len(xrStatus) > 0 {
return xrStatus
}
f.log.Debug("Cannot get status from Desired XR or it's empty")
}
// Fallback to observed XR status
err := oxr.Resource.GetValueInto("status", &xrStatus)
if err != nil {
f.log.Debug("Cannot get status from Observed XR")
}
return xrStatus
}
// checkStatusTargetHasData checks if the status target has data.
func (f *Function) checkStatusTargetHasData(req *fnv1.RunFunctionRequest, in *v1beta1.Input, rsp *fnv1.RunFunctionResponse, inOperation bool) bool {
xrStatus, _, err := f.getOXRAndStatus(req, inOperation)
if err != nil {
response.Fatal(rsp, err)
return true
}
statusField := strings.TrimPrefix(in.Target, "status.")
if hasData, _ := targetHasData(xrStatus, statusField); hasData {
f.log.Info("Target already has data, skipping query", "target", in.Target)
response.ConditionTrue(rsp, "FunctionSkip", "SkippedQuery").
WithMessage("Target already has data, skipped query to avoid throttling").
TargetCompositeAndClaim()
return true
}
return false
}
// executeQuery executes the query.
func (f *Function) executeQuery(ctx context.Context, azureCreds map[string]string, in *v1beta1.Input, rsp *fnv1.RunFunctionResponse) (interface{}, error) {
// Initialize GraphQuery with logger if needed
if gq, ok := f.graphQuery.(*GraphQuery); ok {
gq.log = f.log
}
results, err := f.graphQuery.graphQuery(ctx, azureCreds, in)
if err != nil {
response.Fatal(rsp, err)
f.log.Info("FAILURE: ", "failure", fmt.Sprint(err))
return nil, err
}
// Print the obtained query results
f.log.Info("Query Type:", "queryType", in.QueryType)
f.log.Info("Results:", "results", fmt.Sprint(results))
response.Normalf(rsp, "QueryType: %q", in.QueryType)
return results, nil
}
// processResults processes the query results.
func (f *Function) processResults(req *fnv1.RunFunctionRequest, in *v1beta1.Input, results interface{}, rsp *fnv1.RunFunctionResponse, inOperation bool) error {
if inOperation {
hasDrifted := f.hasQueryResultDriftedFromTarget(req, in.Target, results)
err := f.putQueryResultToAnnotations(req, rsp, hasDrifted)
if err != nil {
response.Fatal(rsp, err)
return err
}
return nil
}
switch {
case strings.HasPrefix(in.Target, "status."):
err := f.putQueryResultToStatus(req, rsp, in, results)
if err != nil {
response.Fatal(rsp, err)
return err
}
case strings.HasPrefix(in.Target, "context."):
err := putQueryResultToContext(req, rsp, in, results, f)
if err != nil {
response.Fatal(rsp, err)
return err
}
default:
// This should never happen because we check for valid targets earlier
response.Fatal(rsp, errors.Errorf("Unrecognized target field: %s", in.Target))
return errors.New("unrecognized target field")
}
return nil
}
func getCreds(req *fnv1.RunFunctionRequest) (map[string]string, error) {
var azureCreds map[string]string
rawCreds := req.GetCredentials()
if credsData, ok := rawCreds["azure-creds"]; ok {
credsData := credsData.GetCredentialData().GetData()
if credsJSON, ok := credsData["credentials"]; ok {
err := json.Unmarshal(credsJSON, &azureCreds)
if err != nil {
return nil, errors.Wrap(err, "cannot parse json credentials")
}
}
} else {
return nil, errors.New("failed to get azure-creds credentials")
}
return azureCreds, nil
}
// GraphQuery is a concrete implementation of the GraphQueryInterface
// that interacts with Microsoft Graph API.
type GraphQuery struct {
log logging.Logger
}
// createGraphClient initializes a Microsoft Graph client using the provided credentials
func (g *GraphQuery) createGraphClient(azureCreds map[string]string, identityType v1beta1.IdentityType) (client *msgraphsdk.GraphServiceClient, err error) {
authProvider := &azauth.AzureIdentityAuthenticationProvider{}
switch identityType {
case v1beta1.IdentityTypeAzureWorkloadIdentityCredentials:
authProvider, err = g.initializeWorkloadIdentityProvider(azureCreds)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize workload identity provider")
}
case v1beta1.IdentityTypeAzureServicePrincipalCredentials:
authProvider, err = g.initializeClientSecretProvider(azureCreds)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize service principal provider")
}
}
// Create adapter
adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
if err != nil {
return nil, errors.Wrap(err, "failed to create graph adapter")
}
// Initialize Microsoft Graph client
return msgraphsdk.NewGraphServiceClient(adapter), nil
}
func (g *GraphQuery) initializeClientSecretProvider(azureCreds map[string]string) (*azauth.AzureIdentityAuthenticationProvider, error) {
tenantID := azureCreds[TenantID]
clientID := azureCreds[ClientID]
clientSecret := azureCreds[ClientSecret]
// Create Azure credential for Microsoft Graph
cred, err := azidentity.NewClientSecretCredential(tenantID, clientID, clientSecret, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain clientsecret credentials")
}
// Create authentication provider
authProvider, err := azauth.NewAzureIdentityAuthenticationProviderWithScopes(cred, MSGraphScopes)
if err != nil {
return nil, errors.Wrap(err, "failed to create auth provider")
}
return authProvider, nil
}
func (g *GraphQuery) initializeWorkloadIdentityProvider(azureCreds map[string]string) (*azauth.AzureIdentityAuthenticationProvider, error) {
options := &azidentity.WorkloadIdentityCredentialOptions{
TokenFilePath: azureCreds[WorkloadIdentityCredentialPath],
}
// Defaults to the value of the environment variable AZURE_TENANT_ID
tenantID, found := azureCreds[TenantID]
if found {
options.TenantID = tenantID
}
// Defaults to the value of the environment variable AZURE_CLIENT_ID
clientID, found := azureCreds[ClientID]
if found {
options.ClientID = clientID
}
// Create Azure credential for Microsoft Graph
cred, err := azidentity.NewWorkloadIdentityCredential(options)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain workloadidentity credentials")
}
// Create authentication provider
authProvider, err := azauth.NewAzureIdentityAuthenticationProviderWithScopes(cred, MSGraphScopes)
if err != nil {
return nil, errors.Wrap(err, "failed to create auth provider")
}
return authProvider, nil
}
// graphQuery is a concrete implementation that interacts with Microsoft Graph API.
func (g *GraphQuery) graphQuery(ctx context.Context, azureCreds map[string]string, in *v1beta1.Input) (interface{}, error) {
identityType := v1beta1.IdentityTypeAzureServicePrincipalCredentials
if in.Identity != nil && in.Identity.Type != "" {
identityType = in.Identity.Type
}
// Create the Microsoft Graph client
client, err := g.createGraphClient(azureCreds, identityType)
if err != nil {
return nil, err
}
// Route based on query type
switch in.QueryType {
case "UserValidation":
return g.validateUsers(ctx, client, in)
case "GroupMembership":
return g.getGroupMembers(ctx, client, in)
case "GroupObjectIDs":
return g.getGroupObjectIDs(ctx, client, in)
case "ServicePrincipalDetails":
return g.getServicePrincipalDetails(ctx, client, in)
default:
return nil, errors.Errorf("unsupported query type: %s", in.QueryType)
}
}
// validateUsers validates if the provided user principal names (emails) exist
func (g *GraphQuery) validateUsers(ctx context.Context, client *msgraphsdk.GraphServiceClient, in *v1beta1.Input) (interface{}, error) {
if in.FailOnEmpty != nil && *in.FailOnEmpty && len(in.Users) == 0 {
return nil, errors.New("no users provided for validation")
}
results := make([]interface{}, 0)
for _, userPrincipalName := range in.Users {
if userPrincipalName == nil {
continue
}
// Create request configuration
requestConfig := &users.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: &users.UsersRequestBuilderGetQueryParameters{},
}
// Build filter expression
filterValue := fmt.Sprintf("userPrincipalName eq '%s'", *userPrincipalName)
requestConfig.QueryParameters.Filter = &filterValue
// Use standard fields for user validation
requestConfig.QueryParameters.Select = []string{"id", "displayName", "userPrincipalName", "mail"}
// Execute the query
result, err := client.Users().Get(ctx, requestConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to validate user %s", *userPrincipalName)
}
// Process results
if result.GetValue() != nil {
for _, user := range result.GetValue() {
userMap := map[string]interface{}{
"id": ptr.Deref(user.GetId(), ""),
"displayName": ptr.Deref(user.GetDisplayName(), ""),
"userPrincipalName": ptr.Deref(user.GetUserPrincipalName(), ""),
"mail": ptr.Deref(user.GetMail(), ""),
}
results = append(results, userMap)
}
}
}
return results, nil
}
// findGroupByName finds a group by its display name and returns its ID
func (g *GraphQuery) findGroupByName(ctx context.Context, client *msgraphsdk.GraphServiceClient, groupName string) (*string, error) {
// Create filter by displayName
filterValue := fmt.Sprintf("displayName eq '%s'", groupName)
groupRequestConfig := &groups.GroupsRequestBuilderGetRequestConfiguration{
QueryParameters: &groups.GroupsRequestBuilderGetQueryParameters{
Filter: &filterValue,
},
}
// Query for the group
groupResult, err := client.Groups().Get(ctx, groupRequestConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to find group")
}
// Verify we found a group
if groupResult.GetValue() == nil || len(groupResult.GetValue()) == 0 {
return nil, errors.Errorf("group not found: %s", groupName)
}
// Return the group ID
return groupResult.GetValue()[0].GetId(), nil
}
// fetchGroupMembers fetches all members of a group by group ID
func (g *GraphQuery) fetchGroupMembers(ctx context.Context, client *msgraphsdk.GraphServiceClient, groupID string, groupName string) ([]models.DirectoryObjectable, error) {
// Create a request configuration that expands members
// This is the workaround for the known issue where service principals
// are not listed as group members in v1.0
// See: https://developer.microsoft.com/en-us/graph/known-issues/?search=25984
requestConfig := &groups.GroupItemRequestBuilderGetRequestConfiguration{
QueryParameters: &groups.GroupItemRequestBuilderGetQueryParameters{
Expand: []string{"members"},
},
}
// Get the group with expanded members using the workaround
// mentioned in the Microsoft documentation
group, err := client.Groups().ByGroupId(groupID).Get(ctx, requestConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to get members for group %s", groupName)
}
// Extract the members from the expanded result
var members []models.DirectoryObjectable
if group.GetMembers() != nil {
members = group.GetMembers()
}
// Log basic information about the membership
if g.log != nil {
g.log.Debug("Retrieved group members", "groupName", groupName, "groupID", groupID, "memberCount", len(members))
}
return members, nil
}
// extractDisplayName attempts to extract the display name from a directory object
func (g *GraphQuery) extractDisplayName(member models.DirectoryObjectable, memberID string) string {
additionalData := member.GetAdditionalData()
// Try to get from additional data first
if displayNameVal, exists := additionalData["displayName"]; exists && displayNameVal != nil {
if displayName, ok := displayNameVal.(string); ok {
return displayName
}
}
// Try to use reflection to call GetDisplayName if it exists
memberValue := reflect.ValueOf(member)
displayNameMethod := memberValue.MethodByName("GetDisplayName")
if displayNameMethod.IsValid() && displayNameMethod.Type().NumIn() == 0 {
results := displayNameMethod.Call(nil)
if len(results) > 0 && !results[0].IsNil() {
// Check if the result is a *string
if displayNamePtr, ok := results[0].Interface().(*string); ok && displayNamePtr != nil {
return *displayNamePtr
}
}
}
// Use fallback display name
return fmt.Sprintf("Member %s", memberID)
}
// extractStringProperty safely extracts a string property from additionalData
func (g *GraphQuery) extractStringProperty(additionalData map[string]interface{}, key string) (string, bool) {
if val, exists := additionalData[key]; exists && val != nil {
if strVal, ok := val.(string); ok {
return strVal, true
}
}
return "", false
}
// extractUserProperties extracts user-specific properties from additionalData
func (g *GraphQuery) extractUserProperties(additionalData map[string]interface{}, memberMap map[string]interface{}) {
// Extract mail property
if mail, ok := g.extractStringProperty(additionalData, "mail"); ok {
memberMap["mail"] = mail
}
// Extract userPrincipalName property
if upn, ok := g.extractStringProperty(additionalData, "userPrincipalName"); ok {
memberMap["userPrincipalName"] = upn
}
}
// extractServicePrincipalProperties extracts service principal specific properties
func (g *GraphQuery) extractServicePrincipalProperties(additionalData map[string]interface{}, memberMap map[string]interface{}) {
// Extract appId property
if appID, ok := g.extractStringProperty(additionalData, "appId"); ok {
memberMap["appId"] = appID
}
}
// processMember extracts member information into a map
func (g *GraphQuery) processMember(member models.DirectoryObjectable) map[string]interface{} {
// Define constants for member types
const (
userType = "user"
servicePrincipalType = "servicePrincipal"
unknownType = "unknown"
)
memberID := ptr.Deref(member.GetId(), "")
additionalData := member.GetAdditionalData()
// Create basic member info
memberMap := map[string]interface{}{
"id": memberID,
}
// Determine member type
memberType := unknownType
// Check properties that indicate user type
_, hasUserPrincipalName := g.extractStringProperty(additionalData, "userPrincipalName")
_, hasMail := g.extractStringProperty(additionalData, "mail")
if hasUserPrincipalName || hasMail {
memberType = userType
}
// Check properties that indicate service principal type
_, hasAppID := g.extractStringProperty(additionalData, "appId")
if hasAppID {
memberType = servicePrincipalType
}
// Try interface type checking for more accuracy
if _, ok := member.(models.Userable); ok {
memberType = userType
}
if _, ok := member.(models.ServicePrincipalable); ok {
memberType = servicePrincipalType
}
// Add type to member info
memberMap["type"] = memberType
// Extract display name
memberMap["displayName"] = g.extractDisplayName(member, memberID)
// Extract type-specific properties
switch memberType {
case userType:
g.extractUserProperties(additionalData, memberMap)
case servicePrincipalType:
g.extractServicePrincipalProperties(additionalData, memberMap)
}
return memberMap
}
// getGroupMembers retrieves all members of the specified group
func (g *GraphQuery) getGroupMembers(ctx context.Context, client *msgraphsdk.GraphServiceClient, in *v1beta1.Input) (interface{}, error) {
// Determine the group name to use
var groupName string
// Check if we have a group name (either directly or resolved from GroupRef)
if in.Group != nil && *in.Group != "" {
groupName = *in.Group
} else {
return nil, errors.New("no group name provided")
}
// Find the group
groupID, err := g.findGroupByName(ctx, client, groupName)
if err != nil {
return nil, err
}
// Fetch the members
memberObjects, err := g.fetchGroupMembers(ctx, client, *groupID, groupName)
if err != nil {
return nil, err
}
// Process the members
members := make([]interface{}, 0, len(memberObjects))
for _, member := range memberObjects {
memberMap := g.processMember(member)
members = append(members, memberMap)
}
return members, nil
}
// getGroupObjectIDs retrieves object IDs for the specified group names
func (g *GraphQuery) getGroupObjectIDs(ctx context.Context, client *msgraphsdk.GraphServiceClient, in *v1beta1.Input) (interface{}, error) {
if in.FailOnEmpty != nil && *in.FailOnEmpty && len(in.Groups) == 0 {
return nil, errors.New("no group names provided")
}
results := make([]interface{}, 0)
for _, groupName := range in.Groups {
if groupName == nil {
continue
}
// Create request configuration
requestConfig := &groups.GroupsRequestBuilderGetRequestConfiguration{
QueryParameters: &groups.GroupsRequestBuilderGetQueryParameters{},
}
// Find the group by displayName
filterValue := fmt.Sprintf("displayName eq '%s'", *groupName)
requestConfig.QueryParameters.Filter = &filterValue
// Use standard fields for group object IDs
requestConfig.QueryParameters.Select = []string{"id", "displayName", "description"}
groupResult, err := client.Groups().Get(ctx, requestConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to find group %s", *groupName)
}
if groupResult.GetValue() != nil && len(groupResult.GetValue()) > 0 {
for _, group := range groupResult.GetValue() {
groupMap := map[string]interface{}{
"id": ptr.Deref(group.GetId(), ""),
"displayName": ptr.Deref(group.GetDisplayName(), ""),
"description": ptr.Deref(group.GetDescription(), ""),
}
results = append(results, groupMap)
}
}
}
return results, nil
}
// getServicePrincipalDetails retrieves details about service principals by name
func (g *GraphQuery) getServicePrincipalDetails(ctx context.Context, client *msgraphsdk.GraphServiceClient, in *v1beta1.Input) (interface{}, error) {
if in.FailOnEmpty != nil && *in.FailOnEmpty && len(in.ServicePrincipals) == 0 {
return nil, errors.New("no service principal names provided")
}
results := make([]interface{}, 0)
for _, spName := range in.ServicePrincipals {
if spName == nil {
continue
}
// Create request configuration
requestConfig := &serviceprincipals.ServicePrincipalsRequestBuilderGetRequestConfiguration{
QueryParameters: &serviceprincipals.ServicePrincipalsRequestBuilderGetQueryParameters{},
}
// Find service principal by displayName
filterValue := fmt.Sprintf("displayName eq '%s'", *spName)
requestConfig.QueryParameters.Filter = &filterValue
// Use standard fields for service principals
requestConfig.QueryParameters.Select = []string{"id", "appId", "displayName", "description"}
spResult, err := client.ServicePrincipals().Get(ctx, requestConfig)
if err != nil {
return nil, errors.Wrapf(err, "failed to find service principal %s", *spName)
}
if spResult.GetValue() != nil && len(spResult.GetValue()) > 0 {
for _, sp := range spResult.GetValue() {
spMap := map[string]interface{}{
"id": ptr.Deref(sp.GetId(), ""),
"appId": ptr.Deref(sp.GetAppId(), ""),
"displayName": ptr.Deref(sp.GetDisplayName(), ""),
"description": ptr.Deref(sp.GetDescription(), ""),
}
results = append(results, spMap)
}
}
}
return results, nil
}
// ParseNestedKey enables the bracket and dot notation to key reference
func ParseNestedKey(key string) ([]string, error) {
var parts []string
// Regular expression to extract keys, supporting both dot and bracket notation
regex := regexp.MustCompile(`\[([^\[\]]+)\]|([^.\[\]]+)`)
matches := regex.FindAllStringSubmatch(key, -1)
for _, match := range matches {
if match[1] != "" {
parts = append(parts, match[1]) // Bracket notation
} else if match[2] != "" {
parts = append(parts, match[2]) // Dot notation
}
}
if len(parts) == 0 {
return nil, errors.New("invalid key")
}
return parts, nil
}
// GetNestedKey retrieves a nested string value from a map using dot notation keys.
func GetNestedKey(context map[string]interface{}, key string) (string, bool) {
parts, err := ParseNestedKey(key)
if err != nil {
return "", false
}
currentValue := interface{}(context)
for _, k := range parts {
// Check if the current value is a map
if nestedMap, ok := currentValue.(map[string]interface{}); ok {
// Get the next value in the nested map
if nextValue, exists := nestedMap[k]; exists {
currentValue = nextValue
} else {
return "", false
}
} else {
return "", false
}
}
// Convert the final value to a string
if result, ok := currentValue.(string); ok {
return result, true
}
return "", false
}
// SetNestedKey sets a value to a nested key from a map using dot notation keys.
func SetNestedKey(root map[string]interface{}, key string, value interface{}) error {
parts, err := ParseNestedKey(key)
if err != nil {
return err
}
current := root
for i, part := range parts {
if i == len(parts)-1 {
// Set the value at the final key
current[part] = value
return nil
}
// Traverse into nested maps or create them if they don't exist
if next, exists := current[part]; exists {
if nextMap, ok := next.(map[string]interface{}); ok {
current = nextMap
} else {
return fmt.Errorf("key %q exists but is not a map", part)
}
} else {
// Create a new map if the path doesn't exist
newMap := make(map[string]interface{})
current[part] = newMap
current = newMap
}
}
return nil
}
// Timer is a concrete implementation of the TimerInterface
// that generates current timestamp
type Timer struct{}
func (Timer) now() string {
return time.Now().Format(time.RFC3339)
}
// putQueryResultToAnnotations process the query results to annotations (only in Operation mode)
func (f *Function) putQueryResultToAnnotations(req *fnv1.RunFunctionRequest, rsp *fnv1.RunFunctionResponse, driftDetected bool) error {
_, dxr, err := f.getDXRAndStatus(req, true)
if err != nil {
return err
}
annotations := dxr.Resource.GetAnnotations()
if annotations == nil {
// If annotations are nil initialize map which can hold both operation annotations
annotations = make(map[string]string, 2)
}
// Update the timestamp annotation
annotations[LastExecutionAnnotation] = f.timer.now()
// Set information about the drift
annotations[LastExecutionQueryDriftDetectedAnnotation] = strconv.FormatBool(driftDetected)
if err := dxr.Resource.SetValue("metadata.annotations", annotations); err != nil {
return errors.Wrap(err, "cannot update composite resource annotations")
}
// Save the updated desired composite resource
dcds := map[resource.Name]*resource.DesiredComposed{
"xr": {
Resource: (*composed.Unstructured)(dxr.Resource),
},
}
if err := response.SetDesiredComposedResources(rsp, dcds); err != nil {
return errors.Wrapf(err, "cannot set desired composite resource in %T", rsp)
}
// In Operation only set rsp.Desired.Resources and not rsp.Desired.Composite
rsp.Desired.Composite = nil
return nil
}
// hasQueryResultDriftedFromTarget
func (f *Function) hasQueryResultDriftedFromTarget(req *fnv1.RunFunctionRequest, target string, results interface{}) bool {
_, oxr, err := f.getOXRAndStatus(req, true)
if err != nil {
f.log.Info("cannot get observed XR to check drift between results and target")
return true
}
observedValue, err := oxr.Resource.GetValue(target)
if err != nil {
f.log.Info("could not get value from observed XR to check drift between results and target")
return true
}
return !reflect.DeepEqual(observedValue, results)
}
// putQueryResultToStatus processes the query results to status (only in Composition mode)
func (f *Function) putQueryResultToStatus(req *fnv1.RunFunctionRequest, rsp *fnv1.RunFunctionResponse, in *v1beta1.Input, results interface{}) error {
xrStatus, dxr, err := f.getDXRAndStatus(req, false)
if err != nil {
return err
}
// Update the specific status field
statusField := strings.TrimPrefix(in.Target, "status.")
err = SetNestedKey(xrStatus, statusField, results)
if err != nil {
return errors.Wrapf(err, "cannot set status field %s to %v", statusField, results)