-
Notifications
You must be signed in to change notification settings - Fork 4
/
ContextHandler.cs
535 lines (463 loc) · 24.3 KB
/
ContextHandler.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Altinn.Authorization.ABAC.Constants;
using Altinn.Authorization.ABAC.Interface;
using Altinn.Authorization.ABAC.Xacml;
using Altinn.Platform.Authorization.Configuration;
using Altinn.Platform.Authorization.Constants;
using Altinn.Platform.Authorization.Helpers;
using Altinn.Platform.Authorization.Models;
using Altinn.Platform.Authorization.Models.Oed;
using Altinn.Platform.Authorization.Repositories.Interface;
using Altinn.Platform.Authorization.Services.Interface;
using Altinn.Platform.Authorization.Services.Interfaces;
using Altinn.Platform.Profile.Models;
using Altinn.Platform.Register.Models;
using Altinn.Platform.Storage.Interface.Models;
using Authorization.Platform.Authorization.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace Altinn.Platform.Authorization.Services.Implementation
{
/// <summary>
/// The context handler is responsible for updating a context request
/// From XACML standard
///
/// Context Handler
/// The system entity that converts decision requests in the native request format to the XACML canonical form, coordinates with Policy
/// Information Points to add attribute values to the request context, and converts authorization decisions in the XACML canonical form to
/// the native response format
/// </summary>
public class ContextHandler : IContextHandler
{
private readonly IInstanceMetadataRepository _policyInformationRepository;
private readonly IRoles _rolesWrapper;
private readonly IOedRoleAssignmentWrapper _oedRolesWrapper;
private readonly IParties _partiesWrapper;
private readonly IProfile _profileWrapper;
private readonly IMemoryCache _memoryCache;
private readonly GeneralSettings _generalSettings;
private readonly IRegisterService _registerService;
private readonly IPolicyRetrievalPoint _prp;
/// <summary>
/// Initializes a new instance of the <see cref="ContextHandler"/> class
/// </summary>
/// <param name="policyInformationRepository">the policy information repository handler</param>
/// <param name="rolesWrapper">the roles handler</param>
/// <param name="oedRolesWrapper">service handling oed role retireval</param>
/// <param name="partiesWrapper">the party information handler</param>
/// <param name="profileWrapper">the user profile information handler</param>
/// <param name="memoryCache">The cache handler </param>
/// <param name="settings">The app settings</param>
/// <param name="registerService">Register service</param>
/// <param name="prp">service handling policy retireval</param>
public ContextHandler(
IInstanceMetadataRepository policyInformationRepository, IRoles rolesWrapper, IOedRoleAssignmentWrapper oedRolesWrapper, IParties partiesWrapper, IProfile profileWrapper, IMemoryCache memoryCache, IOptions<GeneralSettings> settings, IRegisterService registerService, IPolicyRetrievalPoint prp)
{
_policyInformationRepository = policyInformationRepository;
_rolesWrapper = rolesWrapper;
_oedRolesWrapper = oedRolesWrapper;
_partiesWrapper = partiesWrapper;
_profileWrapper = profileWrapper;
_memoryCache = memoryCache;
_generalSettings = settings.Value;
_registerService = registerService;
_prp = prp;
}
/// <summary>
/// Ads needed information to the Context Request.
/// </summary>
/// <param name="request">The original Xacml Context Request</param>
/// <returns>The enriched XacmlContextRequest</returns>
public async Task<XacmlContextRequest> Enrich(XacmlContextRequest request)
{
await EnrichResourceAttributes(request);
return await Task.FromResult(request);
}
/// <summary>
/// Enriches the resource attribute collection with additional attributes retrieved based on the instance on the request
/// </summary>
/// <param name="request">The original Xacml Context Request</param>
protected async Task EnrichResourceAttributes(XacmlContextRequest request)
{
XacmlContextAttributes resourceContextAttributes = request.GetResourceAttributes();
XacmlResourceAttributes resourceAttributes = GetResourceAttributeValues(resourceContextAttributes);
await EnrichResourceParty(resourceAttributes);
bool resourceAttributeComplete = IsResourceComplete(resourceAttributes);
if (!resourceAttributeComplete && !string.IsNullOrEmpty(resourceAttributes.InstanceValue))
{
Instance instanceData = null;
if (!_generalSettings.UseStorageApiForInstanceAuthInfo)
{
instanceData = await _policyInformationRepository.GetInstance(resourceAttributes.InstanceValue);
}
else
{
instanceData = new();
AuthInfo authInfo = await _policyInformationRepository.GetAuthInfo(resourceAttributes.InstanceValue);
instanceData.Process = authInfo.Process;
instanceData.AppId = authInfo.AppId;
instanceData.Org = instanceData.AppId.Split('/')[0];
}
if (instanceData != null)
{
AddIfValueDoesNotExist(resourceContextAttributes, XacmlRequestAttribute.OrgAttribute, resourceAttributes.OrgValue, instanceData.Org);
string app = instanceData.AppId.Split("/")[1];
AddIfValueDoesNotExist(resourceContextAttributes, XacmlRequestAttribute.AppAttribute, resourceAttributes.AppValue, app);
if (instanceData.Process?.CurrentTask != null)
{
AddIfValueDoesNotExist(resourceContextAttributes, XacmlRequestAttribute.TaskAttribute, resourceAttributes.TaskValue, instanceData.Process.CurrentTask.ElementId);
}
else if (instanceData.Process?.EndEvent != null)
{
AddIfValueDoesNotExist(resourceContextAttributes, XacmlRequestAttribute.EndEventAttribute, null, instanceData.Process.EndEvent);
}
string partyId = resourceAttributes.InstanceValue.Split('/')[0];
AddIfValueDoesNotExist(resourceContextAttributes, XacmlRequestAttribute.PartyAttribute, resourceAttributes.ResourcePartyValue, partyId);
resourceAttributes.ResourcePartyValue = partyId;
}
}
await EnrichSubjectAttributes(request, resourceAttributes.ResourcePartyValue);
}
private static bool IsResourceComplete(XacmlResourceAttributes resourceAttributes)
{
bool resourceAttributeComplete = false;
if (!string.IsNullOrEmpty(resourceAttributes.OrgValue) &&
!string.IsNullOrEmpty(resourceAttributes.AppValue) &&
!string.IsNullOrEmpty(resourceAttributes.InstanceValue) &&
!string.IsNullOrEmpty(resourceAttributes.ResourcePartyValue) &&
!string.IsNullOrEmpty(resourceAttributes.TaskValue))
{
// The resource attributes are complete
resourceAttributeComplete = true;
}
else if (!string.IsNullOrEmpty(resourceAttributes.OrgValue) &&
!string.IsNullOrEmpty(resourceAttributes.AppValue) &&
string.IsNullOrEmpty(resourceAttributes.InstanceValue) &&
!string.IsNullOrEmpty(resourceAttributes.ResourcePartyValue) &&
string.IsNullOrEmpty(resourceAttributes.TaskValue))
{
// The resource attributes are complete
resourceAttributeComplete = true;
}
else if (!string.IsNullOrEmpty(resourceAttributes.OrgValue) &&
!string.IsNullOrEmpty(resourceAttributes.AppValue) &&
!string.IsNullOrEmpty(resourceAttributes.InstanceValue) &&
!string.IsNullOrEmpty(resourceAttributes.ResourcePartyValue) &&
!string.IsNullOrEmpty(resourceAttributes.AppResourceValue) &&
resourceAttributes.AppResourceValue.Equals("events"))
{
// The resource attributes are complete
resourceAttributeComplete = true;
}
else if (!string.IsNullOrEmpty(resourceAttributes.ResourceRegistryId) &&
!string.IsNullOrEmpty(resourceAttributes.ResourcePartyValue))
{
// The resource attributes are complete
resourceAttributeComplete = true;
}
return resourceAttributeComplete;
}
/// <summary>
/// Method that adds information about the resource party
/// </summary>
/// <returns></returns>
protected async Task EnrichResourceParty(XacmlResourceAttributes resourceAttributes)
{
if (string.IsNullOrEmpty(resourceAttributes.ResourcePartyValue) && !string.IsNullOrEmpty(resourceAttributes.OrganizationNumber))
{
int partyId = await _registerService.PartyLookup(resourceAttributes.OrganizationNumber, null);
if (partyId != 0)
{
resourceAttributes.ResourcePartyValue = partyId.ToString();
}
}
}
/// <summary>
/// Maps the XacmlContextAttributes for the Xacml Resource category to the Altinn XacmlResourceAttributes model
/// </summary>
/// <param name="resourceContextAttributes">XacmlContextAttributes for mapping of resource attribute values</param>
/// <returns>XacmlResourceAttributes</returns>
protected XacmlResourceAttributes GetResourceAttributeValues(XacmlContextAttributes resourceContextAttributes)
{
XacmlResourceAttributes resourceAttributes = new XacmlResourceAttributes();
foreach (XacmlAttribute attribute in resourceContextAttributes.Attributes)
{
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.OrgAttribute))
{
resourceAttributes.OrgValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.AppAttribute))
{
resourceAttributes.AppValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.InstanceAttribute))
{
resourceAttributes.InstanceValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.PartyAttribute))
{
resourceAttributes.ResourcePartyValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.TaskAttribute))
{
resourceAttributes.TaskValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.AppResourceAttribute))
{
resourceAttributes.AppResourceValue = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.ResourceRegistryAttribute))
{
resourceAttributes.ResourceRegistryId = attribute.AttributeValues.First().Value;
}
if (attribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.OrganizationNumberAttribute))
{
resourceAttributes.OrganizationNumber = attribute.AttributeValues.First().Value;
}
}
return resourceAttributes;
}
/// <summary>
/// Add a XacmlAttribute to the resourceAttributes collection, if the existing value is empty
/// </summary>
/// <param name="resourceAttributes">The collection of resource attribues</param>
/// <param name="attributeId">The attribute id</param>
/// <param name="attributeValue">The existing attribute value</param>
/// <param name="newAttributeValue">The new attribute value</param>
protected void AddIfValueDoesNotExist(XacmlContextAttributes resourceAttributes, string attributeId, string attributeValue, string newAttributeValue)
{
if (string.IsNullOrEmpty(attributeValue))
{
resourceAttributes.Attributes.Add(GetAttribute(attributeId, newAttributeValue));
}
}
/// <summary>
/// Gets a XacmlAttribute model for the specified attribute id and value
/// </summary>
/// <param name="attributeId">The attribute id</param>
/// <param name="attributeValue">The attribute value</param>
/// <returns>XacmlAttribute</returns>
protected XacmlAttribute GetAttribute(string attributeId, string attributeValue)
{
XacmlAttribute attribute = new XacmlAttribute(new Uri(attributeId), false);
if (attributeId.Equals(XacmlRequestAttribute.PartyAttribute))
{
// When Party attribute is missing from input it is good to return it so PEP can get this information
attribute.IncludeInResult = true;
}
attribute.AttributeValues.Add(new XacmlAttributeValue(new Uri(XacmlConstants.DataTypes.XMLString), attributeValue));
return attribute;
}
/// <summary>
/// Enriches the XacmlContextRequest with the Roles the subject user has for the resource reportee
/// </summary>
/// <param name="request">The original Xacml Context Request</param>
/// <param name="resourceParty">The resource reportee party id</param>
protected async Task EnrichSubjectAttributes(XacmlContextRequest request, string resourceParty)
{
// If there is no resource party then it is impossible to enrich roles
if (string.IsNullOrEmpty(resourceParty))
{
return;
}
XacmlContextAttributes subjectContextAttributes = request.GetSubjectAttributes();
int subjectUserId = 0;
int resourcePartyId = Convert.ToInt32(resourceParty);
foreach (XacmlAttribute xacmlAttribute in subjectContextAttributes.Attributes)
{
if (xacmlAttribute.AttributeId.OriginalString.Equals(XacmlRequestAttribute.UserAttribute))
{
subjectUserId = Convert.ToInt32(xacmlAttribute.AttributeValues.First().Value);
}
}
if (subjectUserId == 0)
{
return;
}
XacmlPolicy xacmlPolicy = await _prp.GetPolicyAsync(request);
if (xacmlPolicy == null)
{
return;
}
IDictionary<string, ICollection<string>> subjectAttributes = xacmlPolicy.GetAttributeDictionaryByCategory(XacmlConstants.MatchAttributeCategory.Subject);
if (subjectAttributes.ContainsKey(AltinnXacmlConstants.MatchAttributeIdentifiers.OedRoleAttribute))
{
string subjectSsn = await GetSsnForUser(subjectUserId);
string resourceSsn = await GetSSnForParty(resourcePartyId);
if (!string.IsNullOrWhiteSpace(subjectSsn) && !string.IsNullOrWhiteSpace(resourceSsn))
{
List<OedRoleAssignment> oedRoleAssignments = await GetOedRoleAssignments(resourceSsn, subjectSsn);
if (oedRoleAssignments.Count != 0)
{
subjectContextAttributes.Attributes.Add(GetOedRoleAttributes(oedRoleAssignments));
}
}
}
if (subjectAttributes.ContainsKey(AltinnXacmlConstants.MatchAttributeIdentifiers.RoleAttribute))
{
List<Role> roleList = await GetRoles(subjectUserId, resourcePartyId);
if (roleList.Count != 0)
{
subjectContextAttributes.Attributes.Add(GetRoleAttribute(roleList));
}
}
}
/// <summary>
/// Gets a XacmlAttribute model for the list of roletype codes
/// </summary>
/// <param name="roles">The list of roletype codes</param>
/// <returns>XacmlAttribute</returns>
protected XacmlAttribute GetRoleAttribute(List<Role> roles)
{
XacmlAttribute attribute = new XacmlAttribute(new Uri(XacmlRequestAttribute.RoleAttribute), false);
foreach (Role role in roles)
{
attribute.AttributeValues.Add(new XacmlAttributeValue(new Uri(XacmlConstants.DataTypes.XMLString), role.Value));
}
return attribute;
}
/// <summary>
/// Gets a XacmlAttribute model for the list of oed role attributes
/// </summary>
/// <param name="oedRoleAssignments">The list of oedRoleAssignments</param>
/// <returns>XacmlAttribute</returns>
protected XacmlAttribute GetOedRoleAttributes(List<OedRoleAssignment> oedRoleAssignments)
{
XacmlAttribute attribute = new XacmlAttribute(new Uri(XacmlRequestAttribute.OedRoleAttribute), false);
foreach (OedRoleAssignment oedRoleAssignment in oedRoleAssignments)
{
attribute.AttributeValues.Add(new XacmlAttributeValue(new Uri(XacmlConstants.DataTypes.XMLString), oedRoleAssignment.OedRoleCode));
}
return attribute;
}
/// <summary>
/// Gets a XacmlAttribute model for a list of party ids
/// </summary>
/// <param name="partyIds">The list of party ids</param>
/// <returns>XacmlAttribute</returns>
protected XacmlAttribute GetPartyIdsAttribute(List<int> partyIds)
{
XacmlAttribute attribute = new XacmlAttribute(new Uri(XacmlRequestAttribute.PartyAttribute), false);
foreach (int partyId in partyIds)
{
attribute.AttributeValues.Add(new XacmlAttributeValue(new Uri(XacmlConstants.DataTypes.XMLString), partyId.ToString()));
}
return attribute;
}
/// <summary>
/// Gets the list of roletype codes the subject user has for the resource reportee
/// </summary>
/// <param name="subjectUserId">The user id of the subject</param>
/// <param name="resourcePartyId">The party id of the reportee</param>
/// <returns>List of roles</returns>
protected async Task<List<Role>> GetRoles(int subjectUserId, int resourcePartyId)
{
string cacheKey = GetCacheKey(subjectUserId, resourcePartyId);
if (!_memoryCache.TryGetValue(cacheKey, out List<Role> roles))
{
// Key not in cache, so get data.
roles = await _rolesWrapper.GetDecisionPointRolesForUser(subjectUserId, resourcePartyId) ?? new List<Role>();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.RoleCacheTimeout, 0));
_memoryCache.Set(cacheKey, roles, cacheEntryOptions);
}
return roles;
}
/// <summary>
/// Gets the list of mainunits for a subunit
/// </summary>
/// <param name="subUnitPartyId">The subunit partyId to check and retrieve mainunits for</param>
/// <returns>List of mainunits</returns>
protected async Task<List<MainUnit>> GetMainUnits(int subUnitPartyId)
{
string cacheKey = $"GetMainUnitsFor:{subUnitPartyId}";
if (!_memoryCache.TryGetValue(cacheKey, out List<MainUnit> mainUnits))
{
// Key not in cache, so get data.
mainUnits = await _partiesWrapper.GetMainUnits(new MainUnitQuery { PartyIds = new List<int> { subUnitPartyId } });
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.MainUnitCacheTimeout, 0));
_memoryCache.Set(cacheKey, mainUnits, cacheEntryOptions);
}
return mainUnits;
}
/// <summary>
/// Gets the list of keyrole unit partyIds for a user
/// </summary>
/// <param name="subjectUserId">The userid to retrieve keyrole unit for</param>
/// <returns>List of partyIds for units where user has keyrole</returns>
protected async Task<List<int>> GetKeyRolePartyIds(int subjectUserId)
{
string cacheKey = $"GetKeyRolePartyIdsFor:{subjectUserId}";
if (!_memoryCache.TryGetValue(cacheKey, out List<int> keyrolePartyIds))
{
// Key not in cache, so get data.
keyrolePartyIds = await _partiesWrapper.GetKeyRoleParties(subjectUserId);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.MainUnitCacheTimeout, 0));
_memoryCache.Set(cacheKey, keyrolePartyIds, cacheEntryOptions);
}
return keyrolePartyIds;
}
/// <summary>
/// Gets a list of role assignments between to persons (if exists) from the OED Authz PIP API
/// </summary>
/// <param name="from">the party which the role assignment provides access on behalf of</param>
/// <param name="to">the role assignment recipient party</param>
/// <returns>list of OED/Digitalt dødsbo Role Assignments</returns>
protected async Task<List<OedRoleAssignment>> GetOedRoleAssignments(string from, string to)
{
string cacheKey = GetOedRoleassignmentCacheKey(from, to);
if (!_memoryCache.TryGetValue(cacheKey, out List<OedRoleAssignment> oedRoles))
{
oedRoles = await _oedRolesWrapper.GetOedRoleAssignments(from, to);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.RoleCacheTimeout, 0));
_memoryCache.Set(cacheKey, oedRoles, cacheEntryOptions);
}
return oedRoles;
}
private string GetCacheKey(int userId, int partyId)
{
return "rolelist_" + userId + "_" + partyId;
}
private string GetOedRoleassignmentCacheKey(string from, string to)
{
return $"oed{from}_{to}";
}
private async Task<string> GetSsnForUser(int userId)
{
string cacheKey = $"uid:{userId}";
if (!_memoryCache.TryGetValue(cacheKey, out UserProfile userProfile))
{
userProfile = await _profileWrapper.GetUserProfile(userId);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.RoleCacheTimeout, 0));
_memoryCache.Set(cacheKey, userProfile, cacheEntryOptions);
}
return userProfile?.Party?.SSN;
}
private async Task<string> GetSSnForParty(int partyId)
{
string cacheKey = $"p:{partyId}";
if (!_memoryCache.TryGetValue(cacheKey, out Party party))
{
party = await _partiesWrapper.GetParty(partyId);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.High)
.SetAbsoluteExpiration(new TimeSpan(0, _generalSettings.RoleCacheTimeout, 0));
_memoryCache.Set(cacheKey, party, cacheEntryOptions);
}
return party?.SSN;
}
}
}