-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphBuilder.cs
632 lines (558 loc) · 29.1 KB
/
GraphBuilder.cs
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
/*
This file is part of aws-access-graph.
aws-access-graph is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
aws-access-graph is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along with
aws-access-graph. If not, see <https://www.gnu.org/licenses/>.
*/
using System.IO.Compression;
using Amazon.IdentityManagement.Model;
using Amazon.IdentityStore.Model;
using Amazon.SSOAdmin.Model;
using AwsAccessGraph.AwsPolicies;
using AwsAccessGraph.OktaPolicies;
namespace AwsAccessGraph
{
public static class GraphBuilder
{
public static (List<Node> nodes, List<IEdge<Node>> edges) BuildAws(
IEnumerable<GroupDetail> awsGroups,
IEnumerable<ManagedPolicyDetail> awsPolicies,
IEnumerable<RoleDetail> awsRoles,
IEnumerable<UserDetail> awsUsers,
IEnumerable<SAMLProviderListEntry> awsSamlIdPs,
IEnumerable<PermissionSet> awsPermissionSets,
Dictionary<string, PolicyArn[]> awsPermissionSetManagedPolicies,
Dictionary<string, PermissionSetInlinePolicy[]> awsPermissionSetInlinePolicies,
List<Amazon.IdentityStore.Model.User> identityStoreUsers,
List<Amazon.IdentityStore.Model.Group> identityStoreGroups,
Dictionary<string, GroupMembership[]> identityStoreGroupMemberships,
List<AccountAssignment> permissionSetAssignments,
IEnumerable<OktaGroup> oktaGroups,
IEnumerable<OktaUser> oktaUsers,
Dictionary<OktaGroupId, OktaGroupMember[]> oktaGroupMembers,
bool verbose,
string[] limitToAwsServicePrefixes,
bool noPruneUnrelatedNodes
)
{
// Analyze policy documents
Console.Error.WriteLine("Analyzing managed policy contents... ");
var policyAnalyses = new Dictionary<PolicyArn, PolicyAnalyzerResult>();
foreach (var p in awsPolicies)
{
var result = PolicyAnalyzer.Analyze(p.Arn, Uri.UnescapeDataString(p.PolicyVersionList.Single(v => v.VersionId == p.DefaultVersionId).Document), awsRoles, limitToAwsServicePrefixes);
if (!policyAnalyses.TryAdd(p.Arn, result))
{
// This policy's could have broken across pagination.
var currentEntry = policyAnalyses[p.Arn];
currentEntry.AssumeRoleTargets.AddRange(result.AssumeRoleTargets);
currentEntry.Stanzas.AddRange(result.Stanzas);
policyAnalyses[p.Arn] = currentEntry;
};
}
Console.Error.WriteLine($"..Analyzed managed policy contents [\u2713] (count={policyAnalyses.Count})");
// Analyze role assume policy documents
var roleAnalyses = new Dictionary<RoleArn, RoleAnalyzerResult>();
Console.Error.WriteLine("Analyzing assume role policy document contents... ");
{
var roleArns = awsRoles.Select(r => r.Arn).ToHashSet();
foreach (var role in awsRoles)
{
var result = RoleAnalyzer.Analyze(role.AssumeRolePolicyDocument, awsPolicies);
roleAnalyses.Add(role.Arn, result);
}
}
Console.Error.WriteLine($"..Analyzed assume policy document contents... [\u2713] (count={roleAnalyses.Count})");
// ######################
// ### Generate graph ###
// ######################
var nodes = new List<Node>();
var edges = new List<IEdge<Node>>();
// Add AWS services to graph
foreach (var servicePrefix in policyAnalyses.SelectMany(s => s.Value.Stanzas.Select(t => t.Service.ToLowerInvariant())).Distinct())
{
if (servicePrefix == null)
continue;
nodes.Add(new Node
{
Name = servicePrefix,
Type = NodeType.AwsService,
Arn = servicePrefix,
});
}
// Add policies to graph
foreach (var p in policyAnalyses)
{
var policy = awsPolicies.Single(x => string.Compare(x.Arn, p.Key, StringComparison.OrdinalIgnoreCase) == 0);
if (policy == null)
continue;
var policyNode = new Node
{
Name = policy.PolicyName,
Type = NodeType.AwsPolicy,
Arn = policy.Arn,
};
// Add directed edges from this managed policy to applicable services.
var ct = PolicyVisitor.VisitAndAttachPolicyToServices(p.Value, policyNode, nodes, ref edges);
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(policyNode);
}
// Add permission sets to graph
foreach (var ps in awsPermissionSets)
{
var psNode = new Node
{
Name = ps.Name,
Type = NodeType.AwsPermissionSet,
Arn = ps.PermissionSetArn
};
// Add directed edges from this permission set to applicable managed policies.
var ct = 0;
foreach (var policyArn in awsPermissionSetManagedPolicies.TryGetValue(ps.PermissionSetArn, out string[]? value) ? value : [])
{
var managedPolicyNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsPolicy)
&& string.Compare(n.Arn, policyArn, StringComparison.OrdinalIgnoreCase) == 0);
if (managedPolicyNode != default)
{
edges.Add(new Edge<Node, string>(psNode, managedPolicyNode, "attachedTo"));
ct++;
}
}
// Add directed edges from this group to applicable inline policies.
foreach (var inlinePolicy in awsPermissionSetInlinePolicies.TryGetValue(ps.PermissionSetArn, out PermissionSetInlinePolicy[]? value) ? value : [])
{
var inlinePolicyNode = new Node
{
Name = $"{ps.Name}{inlinePolicy.Path}{inlinePolicy.Name}",
Type = NodeType.AwsInlinePolicy,
Arn = $"{ps.Name}{inlinePolicy.Path}{inlinePolicy.Name}",
};
var ct2 = 0;
if (!string.IsNullOrWhiteSpace(inlinePolicy.PolicyDocument)) // Permission sets can have empty policies
{
var result = PolicyAnalyzer.Analyze(inlinePolicyNode.Arn, Uri.UnescapeDataString(inlinePolicy.PolicyDocument), awsRoles, limitToAwsServicePrefixes);
// Add directed edges from this inline policy to applicable services.
ct2 = PolicyVisitor.VisitAndAttachPolicyToServices(result, inlinePolicyNode, nodes, ref edges);
}
if (noPruneUnrelatedNodes || ct2 > 0)
{
nodes.Add(inlinePolicyNode);
edges.Add(new Edge<Node, string>(psNode, inlinePolicyNode, "attachedTo"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(psNode);
}
// Add groups to graph
foreach (var g in awsGroups)
{
var groupNode = new Node
{
Name = g.GroupName,
Type = NodeType.AwsGroup,
Arn = g.Arn,
};
// Add directed edges from this group to applicable managed policies.
var ct = 0;
foreach (var policyArn in g.AttachedManagedPolicies.Select(p => p.PolicyArn))
{
var policyNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsPolicy)
&& string.Compare(n.Arn, policyArn, StringComparison.OrdinalIgnoreCase) == 0);
if (policyNode != default)
{
edges.Add(new Edge<Node, string>(groupNode, policyNode, "attachedTo"));
ct++;
}
}
// Add directed edges from this group to applicable inline policies.
foreach (var inlinePolicy in g.GroupPolicyList)
{
var inlinePolicyNode = new Node
{
Name = $"{g.GroupName}/{inlinePolicy.PolicyName}",
Type = NodeType.AwsInlinePolicy,
Arn = $"{g.GroupName}/{inlinePolicy.PolicyName}",
};
var result = PolicyAnalyzer.Analyze(inlinePolicyNode.Arn, Uri.UnescapeDataString(inlinePolicy.PolicyDocument), awsRoles, limitToAwsServicePrefixes);
// Add directed edges from this inline policy to applicable services.
var ct2 = PolicyVisitor.VisitAndAttachPolicyToServices(result, inlinePolicyNode, nodes, ref edges);
if (noPruneUnrelatedNodes || ct2 > 0)
{
nodes.Add(inlinePolicyNode);
edges.Add(new Edge<Node, string>(groupNode, inlinePolicyNode, "attachedTo"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(groupNode);
}
// Add Identity Store groups to graph
foreach (var g in identityStoreGroups)
{
var groupNode = new Node
{
Name = g.DisplayName,
Type = NodeType.AwsIdentityStoreGroup,
Arn = g.GroupId,
};
// Add directed edges from this IS Group to applicable permission sets.
var ct = 0;
foreach (var psArn in permissionSetAssignments
.Where(psa => psa.PrincipalType == Amazon.SSOAdmin.PrincipalType.GROUP
&& psa.PrincipalId == g.GroupId)
.Select(psa => psa.PermissionSetArn))
{
var permissionSetNode = nodes.Distinct().SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsPermissionSet)
&& string.Compare(n.Arn, psArn, StringComparison.OrdinalIgnoreCase) == 0);
if (permissionSetNode != default)
{
edges.Add(new Edge<Node, string>(groupNode, permissionSetNode, "attachedTo"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(groupNode);
}
// Add roles to graph
foreach (var r in awsRoles)
{
var roleNode = new Node
{
Name = r.RoleName,
Type = NodeType.AwsRole,
Arn = r.Arn,
};
// Add directed edges from this role to applicable stand-alone policies.
var ct = 0;
foreach (var policyArn in r.AttachedManagedPolicies.Select(p => p.PolicyArn))
{
var policyNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsPolicy)
&& string.Compare(n.Arn, policyArn, StringComparison.OrdinalIgnoreCase) == 0);
if (policyNode != default)
{
edges.Add(new Edge<Node, string>(roleNode, policyNode, "attachedTo"));
ct++;
}
}
// Add directed edges from this role to applicable inline policies.
foreach (var inlinePolicy in r.RolePolicyList)
{
var inlinePolicyNode = new Node
{
Name = $"{r.RoleName}/{inlinePolicy.PolicyName}",
Type = NodeType.AwsInlinePolicy,
Arn = $"{r.RoleName}/{inlinePolicy.PolicyName}",
};
var result = PolicyAnalyzer.Analyze(inlinePolicyNode.Arn, Uri.UnescapeDataString(inlinePolicy.PolicyDocument), awsRoles, limitToAwsServicePrefixes);
// Add directed edges from this inline policy to applicable services.
var ct2 = PolicyVisitor.VisitAndAttachPolicyToServices(result, inlinePolicyNode, nodes, ref edges);
if (noPruneUnrelatedNodes || ct2 > 0)
{
nodes.Add(inlinePolicyNode);
edges.Add(new Edge<Node, string>(roleNode, inlinePolicyNode, "attachedTo"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(roleNode);
}
// Add users to graph
foreach (var u in awsUsers)
{
var userNode = new Node
{
Name = u.UserName,
Type = NodeType.AwsUser,
Arn = u.Arn,
};
// Add directed edges from this user to groups in which the user is a member
var ct = 0;
foreach (var groupName in u.GroupList)
{
var groupNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsGroup)
&& string.Compare(n.Name, groupName, StringComparison.OrdinalIgnoreCase) == 0);
if (groupNode != default)
{
edges.Add(new Edge<Node, string>(userNode, groupNode, "memberOf"));
ct++;
}
}
// Add directed edges from this user to applicable stand-alone policies.
foreach (var policyArn in u.AttachedManagedPolicies.Select(p => p.PolicyArn))
{
var policyNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsPolicy)
&& string.Compare(n.Arn, policyArn, StringComparison.OrdinalIgnoreCase) == 0);
if (policyNode != default)
{
edges.Add(new Edge<Node, string>(userNode, policyNode, "attachedTo"));
ct++;
}
}
// Add directed edges from this user to applicable inline policies.
foreach (var inlinePolicy in u.UserPolicyList)
{
var inlinePolicyNode = new Node
{
Name = $"{u.UserName}/{inlinePolicy.PolicyName}",
Type = NodeType.AwsInlinePolicy,
Arn = $"{u.UserName}/{inlinePolicy.PolicyName}",
};
var result = PolicyAnalyzer.Analyze(inlinePolicyNode.Arn, Uri.UnescapeDataString(inlinePolicy.PolicyDocument), awsRoles, limitToAwsServicePrefixes);
// Add directed edges from this inline policy to applicable services.
var ct2 = PolicyVisitor.VisitAndAttachPolicyToServices(result, inlinePolicyNode, nodes, ref edges);
if (noPruneUnrelatedNodes || ct2 > 0)
{
nodes.Add(inlinePolicyNode);
edges.Add(new Edge<Node, string>(userNode, inlinePolicyNode, "attachedTo"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(userNode);
}
// Add Identity Store users to graph
foreach (var u in identityStoreUsers)
{
var userNode = new Node
{
Name = u.UserName,
Type = NodeType.AwsIdentityStoreUser,
Arn = u.UserId,
};
// Add directed edges from this user to groups in which the user is a member
var ct = 0;
foreach (var groupName in identityStoreGroupMemberships.Keys)
{
var groupNode = nodes.SingleOrDefault(n =>
n.Type.Equals(NodeType.AwsIdentityStoreGroup)
&& string.Compare(n.Name, groupName, StringComparison.OrdinalIgnoreCase) == 0);
if (groupNode != default)
{
edges.Add(new Edge<Node, string>(userNode, groupNode, "memberOf"));
ct++;
}
}
if (noPruneUnrelatedNodes || ct > 0)
nodes.Add(userNode);
}
// Add policy(attachedTo)role(targeting)role assumption edges to graph
var roleNodes = nodes.Where(n => n.Type.Equals(NodeType.AwsRole)).ToLookup(r => r.Arn);
{
var policyNodes = nodes.Where(n => n.Type.Equals(NodeType.AwsPolicy)).ToLookup(p => p.Arn);
foreach (var pn in policyNodes)
{
// What roles can this policy assume?
var pa = policyAnalyses[pn.Key!];
if (pa.AssumeRoleTargets.Count == 0)
continue;
if (verbose) Console.Error.WriteLine($"{Environment.NewLine}{Environment.NewLine}PolicyArn: {pn.Key}");
var rolesThatCanBeAssumed = roleNodes.SelectMany(r => pa.AssumeRoleTargets).Distinct();
foreach (var roleThatCanBeAssumed in rolesThatCanBeAssumed)
{
if (verbose) Console.Error.WriteLine($"\tCan assume: {roleThatCanBeAssumed}");
// Can these roles be assumed by principals attached to this policy, though? If so, they'd be provided for in the trust policy.
var rolesWithThisPolicyAttached = edges.FindRolesAttachedTo(pn.Single()).Select(x => x.source).ToArray();
if (rolesWithThisPolicyAttached.Length == 0)
{
if (verbose) Console.Error.WriteLine($"\t\tBut is not attached to any roles.");
continue;
}
foreach (var roleThatCanAssume in rolesWithThisPolicyAttached)
{
if (roleThatCanAssume.Arn == null)
throw new InvalidOperationException($"Arn is null on {roleThatCanAssume}");
if (verbose) Console.Error.WriteLine($"\t\tAnd is attached to role: {roleThatCanAssume.Arn}");
var ra = roleAnalyses[roleThatCanAssume.Arn];
if (ra.IamRootAllowed)
{
if (verbose) Console.Error.WriteLine($"\t\t\t...which can be assumed by anything with a policy that permits sts:AssumeRole to it");
// Because the role with this policy attached can be assumed by any entity that itself has a grant for sts:AssumeRole to this,
// (i.e. is controlled purely by its IAM policy and not a two-way allowance),
foreach (var roleArn in rolesThatCanBeAssumed)
{
var targetRole = roleNodes[roleArn].SingleOrDefault();
if (!default(Node).Equals(targetRole))
edges.Add(new Edge<Node, string>(roleThatCanAssume, targetRole, "canAssume"));
}
}
else
{
foreach (var trustedEntityThatCanAssume in ra.TrustedEntitiesThatCanAssume)
{
if (verbose) Console.Error.WriteLine($"\t\t\t...which can be assumed by trusted entity {trustedEntityThatCanAssume}");
var r = awsRoles.SingleOrDefault(r => string.Compare(r.Arn, trustedEntityThatCanAssume, StringComparison.OrdinalIgnoreCase) == 0);
if (r == default)
{
if (verbose) Console.Error.WriteLine($"\t\t\t...which is unresolved (skipping)");
continue;
}
var switch1 = false;
foreach (var policyOnTrustedEntity in r.AttachedManagedPolicies)
{
var ipar = policyAnalyses[policyOnTrustedEntity.PolicyArn];
if (ipar.AssumeRoleTargets.Any(art => string.CompareOrdinal(roleThatCanBeAssumed, art) == 0))
{
if (!switch1 && verbose)
Console.Error.WriteLine($"\t\t\t\t...which has attached policy {policyOnTrustedEntity.PolicyArn}");
switch1 = true;
if (verbose) Console.Error.WriteLine($"\t\t\t\t\t...which CAN assume {roleThatCanBeAssumed}");
edges.Add(new Edge<Node, string>(roleNodes[trustedEntityThatCanAssume].Single(), roleNodes[roleThatCanBeAssumed].Single(), "canAssume"));
}
else
{
//if (verbose) Console.Error.WriteLine($"\t\t\t\t\t...which CANNOT assume {roleThatCanBeAssumed}");
}
}
}
//throw new NotImplementedException();
}
}
}
}
}
// Add role(can-be-SAMLed-from-Okta-via-GroupMapping) Okta group nodes and related edges to graph
foreach (var og in oktaGroups.Where(g =>
!string.IsNullOrWhiteSpace(g.AwsRoleName)))
{
var matchingAwsRole = awsRoles.SingleOrDefault(r =>
string.Compare(r.RoleName, og.AwsRoleName, StringComparison.OrdinalIgnoreCase) == 0
&& roleAnalyses[r.Arn].TrustedEntitiesThatCanAssume.Any(te =>
awsSamlIdPs.Any(s =>
string.Compare(s.Arn, te, StringComparison.OrdinalIgnoreCase) == 0
&& string.Compare(og.AwsAccountId, Amazon.Arn.Parse(s.Arn).AccountId, StringComparison.OrdinalIgnoreCase) == 0
)
));
if (matchingAwsRole == null)
continue;
var roleNode = roleNodes[matchingAwsRole.Arn].SingleOrDefault();
if (roleNode == default)
continue;
// Add this Okta group as a node.
var oktaGroupNode = new Node
{
Name = og.Name!,
Type = NodeType.OktaGroup,
Arn = og.Id!,
};
nodes.Add(oktaGroupNode);
edges.Add(new Edge<Node, string>(oktaGroupNode, roleNode, "canAssume"));
}
// Add applicable Okta users and related edges to graph
var oktaUserNodes = nodes
.Where(n => n.Type.Equals(NodeType.OktaGroup))
.SelectMany(n => oktaGroupMembers[n.Arn!])
.Select(n => n.UserId)
.Distinct()
.Select(u => oktaUsers.SingleOrDefault(ou => string.Compare(ou.UserId, u, StringComparison.OrdinalIgnoreCase) == 0))
.Where(u => u.Login != null) // This is necessary b/c user could have been suspended/deactivated yet still assigned.
.Select(u => new Node
{
Name = u.Login ?? "?",
Type = NodeType.OktaUser,
Arn = u.UserId ?? "?"
})
.ToArray(); // Required so we can modify the collection in the following statement.
nodes.AddRange(oktaUserNodes);
// Now the Okta user-group edges.
{
var ounLookup = oktaUserNodes.ToLookup(oun => oun.Arn);
foreach (var oktaGroupNode in nodes.Where(n => n.Type.Equals(NodeType.OktaGroup)))
{
edges.AddRange(oktaGroupMembers[oktaGroupNode.Arn!]
.Where(ogm => ogm.UserId != null)
.Select(ogm => (ogm.UserId, ounLookup[ogm.UserId!].SingleOrDefault()))
.Where(t => t.Item2 != default)
.Select(ogm => new Edge<Node, string>(
ogm.Item2,
oktaGroupNode,
"memberOf"
))
.Select(x => (IEdge<Node>)x));
}
}
// Add applicable Identity Store users and related edges to graph
var identityStoreUserNodes = nodes
.Where(n => n.Type.Equals(NodeType.AwsIdentityStoreGroup))
.Distinct()
.SelectMany(n => identityStoreGroupMemberships[n.Arn!])
.Select(n => n.MemberId.UserId)
.Distinct()
.Select(u => identityStoreUsers
.Distinct()
.SingleOrDefault(isu => // TODO: Should be SingleOrDefault()
string.Compare(isu.UserId, u, StringComparison.OrdinalIgnoreCase) == 0
)
)
.Where(u => u != null)
.Select(u => new Node
{
Name = u!.UserName ?? "?",
Type = NodeType.AwsIdentityStoreUser,
Arn = u.UserId ?? "?"
})
.ToArray(); // Required so we can modify the collection in the following statement.
nodes.AddRange(identityStoreUserNodes);
// Now the Identity Store user-group edges.
{
var isuLookup = identityStoreUserNodes.ToLookup(isu => isu.Arn);
foreach (var identityStoreGroupNode in nodes.Where(n => n.Type.Equals(NodeType.AwsIdentityStoreGroup)))
{
edges.AddRange(identityStoreGroupMemberships[identityStoreGroupNode.Arn!]
.Select(gm => (gm.MemberId, isuLookup[gm.MemberId.UserId].SingleOrDefault()))
.Where(t => t.Item2 != default)
.Select(gm => new Edge<Node, string>(
gm.Item2,
identityStoreGroupNode,
"memberOf"
))
.Select(x => (IEdge<Node>)x));
}
}
// Finally, group AwsIamUser, OktaUsers, and IdentityStoreUsers
{
var awsUserNodes = nodes
.Where(n => n.Type.Equals(NodeType.AwsUser))
.ToArray();
var subIdentityNodesProto = oktaUserNodes
.Union(awsUserNodes)
.Union(identityStoreUserNodes)
.GroupBy(x => x.Name.Split('@')[0])
.ToDictionary(k => k.Key, v => v.ToArray());
var rootIdentityNodes = subIdentityNodesProto
.ToDictionary(k => new Node
{
Arn = k.Key,
Type = NodeType.IdentityPrincipal,
Name = k.Key
}, v => v.Value);
nodes.AddRange(rootIdentityNodes.Keys);
foreach (var kvp in rootIdentityNodes)
{
foreach (var sub in kvp.Value)
{
edges.Add(new Edge<Node, string>(
kvp.Key,
sub,
"is"));
}
}
}
var orphans = nodes
.Where(n => !edges.Any(e => e.Source == n || e.Destination == n));
return (nodes.Except(orphans).ToList(), edges);
}
}
}