/// <summary> /// This method authorize access bases on context and requirement /// Is triggered by annotation on MVC action and setup in startup. /// </summary> /// <param name="context">The context</param> /// <param name="requirement">The requirement</param> /// <returns>A Task</returns> protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AppAccessRequirement requirement) { if (_pepSettings.DisablePEP) { context.Succeed(requirement); return; } XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(context, requirement, _httpContextAccessor.HttpContext.GetRouteData()); _logger.LogInformation($"// Altinn PEP // AppAccessHandler // Request sent: {JsonConvert.SerializeObject(request)}"); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { throw new ArgumentNullException("response"); } if (!DecisionHelper.ValidatePdpDecision(response.Response, context.User)) { context.Fail(); } context.Succeed(requirement); await Task.CompletedTask; }
public async Task <ActionResult> Post([FromBody] XacmlRequestApiModel model) { try { if (Request.ContentType.Contains("application/json")) { return(await AuthorizeJsonRequest(model)); } else { return(await AuthorizeXmlRequest(model)); } } catch (Exception ex) { _logger.LogError(ex, "// DecisionController // Decision // Unexpected Exception"); XacmlContextResult result = new XacmlContextResult(XacmlContextDecision.Indeterminate) { Status = new XacmlContextStatus(XacmlContextStatusCode.SyntaxError) }; XacmlContextResponse xacmlContextResponse = new XacmlContextResponse(result); if (Request.ContentType.Contains("application/json")) { XacmlJsonResponse jsonResult = XacmlJsonXmlConverter.ConvertResponse(xacmlContextResponse); return(Ok(jsonResult)); } else { return(CreateResponse(xacmlContextResponse)); } } }
/// <inheritdoc/> public async Task <XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest) { XacmlJsonResponse xacmlJsonResponse = null; string apiUrl = $"decision"; try { string requestJson = JsonConvert.SerializeObject(xacmlJsonRequest); StringContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); _authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = _authClient.PostAsync(apiUrl, httpContent).Result; if (response.StatusCode == HttpStatusCode.OK) { string responseData = response.Content.ReadAsStringAsync().Result; xacmlJsonResponse = JsonConvert.DeserializeObject <XacmlJsonResponse>(responseData); } } catch (Exception e) { _logger.LogError($"Unable to retrieve Xacml Json response. An error occured {e.Message}"); } return(xacmlJsonResponse); }
/// <summary> /// Authorizes a given action on an instance. /// </summary> /// <returns></returns> public async Task <bool> AuthorizeInstanceAction(ClaimsPrincipal user, Instance instance, string action) { string org = instance.Org; string app = instance.AppId.Split('/')[1]; int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); XacmlJsonRequestRoot request; if (instance.Id == null) { request = DecisionHelper.CreateDecisionRequest(org, app, user, action, instanceOwnerPartyId, null); } else { Guid instanceGuid = Guid.Parse(instance.Id.Split('/')[1]); request = DecisionHelper.CreateDecisionRequest(org, app, user, action, instanceOwnerPartyId, instanceGuid); } XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Authorization Helper // Authorize instance action failed for request: {JsonConvert.SerializeObject(request)}."); return(false); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, user); return(authorized); }
public void ValidateResponse_TC02() { // Arrange XacmlJsonResponse response = new XacmlJsonResponse(); response.Response = new List <XacmlJsonResult>(); XacmlJsonResult xacmlJsonResult = new XacmlJsonResult(); xacmlJsonResult.Decision = XacmlContextDecision.Permit.ToString(); response.Response.Add(xacmlJsonResult); // Add obligation to result with a minimum authentication level attribute XacmlJsonObligationOrAdvice obligation = new XacmlJsonObligationOrAdvice(); obligation.AttributeAssignment = new List <XacmlJsonAttributeAssignment>(); XacmlJsonAttributeAssignment authenticationAttribute = new XacmlJsonAttributeAssignment() { Category = "urn:altinn:minimum-authenticationlevel", Value = "2" }; obligation.AttributeAssignment.Add(authenticationAttribute); xacmlJsonResult.Obligations = new List <XacmlJsonObligationOrAdvice>(); xacmlJsonResult.Obligations.Add(obligation); // Act bool result = DecisionHelper.ValidateResponse(response.Response, CreateUserClaims(false)); // Assert Assert.True(result); }
private async Task <bool> AuthorizeAction(string currentTaskType, string org, string app, int instanceOwnerPartyId, Guid instanceGuid) { string actionType; switch (currentTaskType) { case "data": case "feedback": actionType = "write"; break; case "confirmation": actionType = "confirm"; break; default: actionType = currentTaskType; break; } XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(org, app, HttpContext.User, actionType, instanceOwnerPartyId, instanceGuid); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Process Controller // Authorization of moving process forward failed with request: {JsonConvert.SerializeObject(request)}."); return(false); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User); return(authorized); }
private async Task <bool> Authorize(string currentTaskType, Instance instance) { string actionType; if (string.IsNullOrEmpty(currentTaskType) || currentTaskType.Equals("data")) { actionType = "write"; } else { actionType = currentTaskType; } string org = instance.Org; string app = instance.AppId.Split("/")[1]; XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(org, app, HttpContext.User, actionType, null, instance.Id); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Instance Controller // Authorization to update Process failed: {JsonConvert.SerializeObject(request)}."); return(false); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User); return(authorized); }
public void ValidatePdpDecision_TC08() { // Arrange XacmlJsonResponse response = new XacmlJsonResponse(); response.Response = new List <XacmlJsonResult>(); XacmlJsonResult xacmlJsonResult = new XacmlJsonResult(); xacmlJsonResult.Decision = XacmlContextDecision.Permit.ToString(); response.Response.Add(xacmlJsonResult); // Add obligation to result with a minimum authentication level attribute XacmlJsonObligationOrAdvice obligation = new XacmlJsonObligationOrAdvice(); obligation.AttributeAssignment = new List <XacmlJsonAttributeAssignment>(); string minAuthLevel = "3"; XacmlJsonAttributeAssignment authenticationAttribute = new XacmlJsonAttributeAssignment() { Category = "urn:altinn:minimum-authenticationlevel", Value = minAuthLevel }; obligation.AttributeAssignment.Add(authenticationAttribute); xacmlJsonResult.Obligations = new List <XacmlJsonObligationOrAdvice>(); xacmlJsonResult.Obligations.Add(obligation); // Act EnforcementResult result = DecisionHelper.ValidatePdpDecisionDetailed(response.Response, CreateUserClaims(false)); // Assert Assert.False(result.Authorized); Assert.Contains(AltinnObligations.RequiredAuthenticationLevel, result.FailedObligations.Keys); Assert.Equal(minAuthLevel, result.FailedObligations[AltinnObligations.RequiredAuthenticationLevel]); }
/// <inheritdoc/> public async Task <XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest) { XacmlJsonResponse xacmlJsonResponse = null; if (_pepSettings.DisablePEP) { return(new XacmlJsonResponse { Response = new List <XacmlJsonResult>() { new XacmlJsonResult { Decision = XacmlContextDecision.Permit.ToString(), } }, }); } try { xacmlJsonResponse = await _authorizationApiClient.AuthorizeRequest(xacmlJsonRequest); } catch (Exception e) { _logger.LogError($"Unable to retrieve Xacml Json response. An error occured {e.Message}"); } return(xacmlJsonResponse); }
public async Task <ActionResult> Post([FromBody] XacmlRequestApiModel model) { try { if (Request.ContentType.Contains("application/json")) { return(await AuthorizeJsonRequest(model)); // lgtm [cs/user-controlled-bypass] } else { return(await AuthorizeXmlRequest(model)); // lgtm [cs/user-controlled-bypass] } } catch { XacmlContextResult result = new XacmlContextResult(XacmlContextDecision.Indeterminate) { Status = new XacmlContextStatus(XacmlContextStatusCode.SyntaxError) }; XacmlContextResponse xacmlContextResponse = new XacmlContextResponse(result); if (Request.ContentType.Contains("application/json")) { XacmlJsonResponse jsonResult = XacmlJsonXmlConverter.ConvertResponse(xacmlContextResponse); return(Ok(jsonResult)); } else { return(CreateResponse(xacmlContextResponse)); } } }
/// <summary> /// Method to authorize access to an Altinn App event /// </summary> public async Task <bool> AuthorizeConsumerForAltinnAppEvent(CloudEvent cloudEvent, string consumer) { XacmlJsonRequestRoot xacmlJsonRequest = CloudEventXacmlMapper.CreateDecisionRequest(cloudEvent, consumer); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(xacmlJsonRequest); return(ValidateResult(response)); }
public async Task <ActionResult <Instance> > Post(string appId, [FromBody] Instance instance) { (Application appInfo, ActionResult appInfoError) = await GetApplicationOrErrorAsync(appId); int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); if (appInfoError != null) { return(appInfoError); } if (string.IsNullOrWhiteSpace(instance.InstanceOwner.PartyId)) { return(BadRequest("Cannot create an instance without an instanceOwner.PartyId.")); } // Checking that user is authorized to instantiate. XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(appInfo.Org, appInfo.Id.Split('/')[1], HttpContext.User, "instantiate", instanceOwnerPartyId, null); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Instances Controller // Authorization of instantiation failed with request: {JsonConvert.SerializeObject(request)}."); return(Forbid()); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User); if (!authorized) { return(Forbid()); } Instance storedInstance = new Instance(); try { DateTime creationTime = DateTime.UtcNow; string userId = GetUserId(); Instance instanceToCreate = CreateInstanceFromTemplate(appInfo, instance, creationTime, userId); storedInstance = await _instanceRepository.Create(instanceToCreate); await DispatchEvent(InstanceEventType.Created, storedInstance); _logger.LogInformation($"Created instance: {storedInstance.Id}"); storedInstance.SetPlatformSelflink(_storageBaseAndHost); return(Created(storedInstance.SelfLinks.Platform, storedInstance)); } catch (Exception storageException) { _logger.LogError($"Unable to create {appId} instance for {instance.InstanceOwner.PartyId} due to {storageException}"); // compensating action - delete instance await _instanceRepository.Delete(storedInstance); _logger.LogError($"Deleted instance {storedInstance.Id}"); return(StatusCode(500, $"Unable to create {appId} instance for {instance.InstanceOwner.PartyId} due to {storageException.Message}")); } }
public async Task <XacmlJsonResponse> AuthorizeRequest(XacmlJsonRequestRoot xacmlJsonRequest) { XacmlJsonResponse xacmlJsonResponse = null; string apiUrl = $"decision"; string requestJson = JsonConvert.SerializeObject(xacmlJsonRequest); StringContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json"); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); HttpResponseMessage response = await _httpClient.PostAsync(apiUrl, httpContent); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; _logger.LogInformation("Authorization PDP time elapsed: " + ts.TotalMilliseconds); if (response.StatusCode == HttpStatusCode.OK) { string responseData = await response.Content.ReadAsStringAsync(); xacmlJsonResponse = JsonConvert.DeserializeObject <XacmlJsonResponse>(responseData); } else { _logger.LogInformation($"// PDPAppSI // GetDecisionForRequest // Non-zero status code: {response.StatusCode}"); _logger.LogInformation($"// PDPAppSI // GetDecisionForRequest // Response: {await response.Content.ReadAsStringAsync()}"); } return(xacmlJsonResponse); }
/// <summary> /// Authorizes and filters events based on authorization /// </summary> /// <param name="consumer">The event consumer</param> /// <param name="cloudEvents">The list of events</param> /// <returns>A list of authorized events</returns> public async Task <List <CloudEvent> > AuthorizeEvents(ClaimsPrincipal consumer, List <CloudEvent> cloudEvents) { XacmlJsonRequestRoot xacmlJsonRequest = CloudEventXacmlMapper.CreateMultiDecisionRequest(consumer, cloudEvents); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(xacmlJsonRequest); List <CloudEvent> authorizedEventsList = new List <CloudEvent>(); foreach (XacmlJsonResult result in response.Response) { if (DecisionHelper.ValidateDecisionResult(result, consumer)) { string eventId = string.Empty; // Loop through all attributes in Category from the response foreach (XacmlJsonCategory category in result.Category) { var attributes = category.Attribute; foreach (var attribute in attributes) { if (attribute.AttributeId.Equals(AltinnXacmlUrns.EventId)) { eventId = attribute.Value; } } } // Find the instance that has been validated to add it to the list of authorized instances. CloudEvent authorizedEvent = cloudEvents.First(i => i.Id == eventId); authorizedEventsList.Add(authorizedEvent); } } return(authorizedEventsList); }
private async Task <ActionResult> AuthorizeJsonRequest(XacmlRequestApiModel model) { XacmlJsonRequestRoot jsonRequest = (XacmlJsonRequestRoot)JsonConvert.DeserializeObject(model.BodyContent, typeof(XacmlJsonRequestRoot)); XacmlJsonResponse jsonResponse = await Authorize(jsonRequest.Request); return(Ok(jsonResponse)); }
private bool ValidateResult(XacmlJsonResponse response) { if (response.Response[0].Decision.Equals(XacmlContextDecision.Permit.ToString())) { return(true); } return(false); }
public static async Task <XacmlJsonResponse> GetXacmlJsonProfileContextResponseAsync(HttpClient client, HttpRequestMessage httpRequestMessage) { HttpResponseMessage response = await client.SendAsync(httpRequestMessage); string responseContent = await response.Content.ReadAsStringAsync(); XacmlJsonResponse xacmlJsonresponse = (XacmlJsonResponse)JsonConvert.DeserializeObject(responseContent, typeof(XacmlJsonResponse)); return(xacmlJsonresponse); }
public void ValidateResponse_TC07() { // Arrange XacmlJsonResponse response = new XacmlJsonResponse(); response.Response = new List <XacmlJsonResult>(); // Act & Assert Assert.Throws <ArgumentNullException>(() => DecisionHelper.ValidateResponse(response.Response, null)); }
public void ValidateResponse_TC06() { // Arrange XacmlJsonResponse response = new XacmlJsonResponse(); response.Response = null; // Act & Assert Assert.Throws <ArgumentNullException>(() => DecisionHelper.ValidateResponse(response.Response, CreateUserClaims(false))); }
public static void AssertEqual(XacmlJsonResponse expected, XacmlJsonResponse actual) { Assert.NotNull(actual); Assert.NotNull(expected); Assert.Equal(expected.Response.Count, actual.Response.Count); if (expected.Response.Count > 0) { AssertEqual(expected.Response.First(), actual.Response.First()); } }
public async Task <bool> GetDecisionForUnvalidateRequest(XacmlJsonRequestRoot xacmlJsonRequest, ClaimsPrincipal user) { if (_pepSettings.DisablePEP) { return(true); } XacmlJsonResponse response = await GetDecisionForRequest(xacmlJsonRequest); return(DecisionHelper.ValidatePdpDecision(response.Response, user)); }
public async Task PDP_Decision_DelegationPolicy_AltinnAppsOrg1App1_KeyRoleUnitDelegation_MainUnit_Permit() { string testCase = "AltinnAppsOrg1App1_KeyRoleUnitDelegation_MainUnit"; HttpClient client = GetTestClient(); HttpRequestMessage httpRequestMessage = TestSetupUtil.CreateJsonProfileXacmlRequest(testCase); XacmlJsonResponse expected = TestSetupUtil.ReadExpectedJsonProfileResponse(testCase); // Act XacmlJsonResponse contextResponse = await TestSetupUtil.GetXacmlJsonProfileContextResponseAsync(client, httpRequestMessage); // Assert AssertionUtil.AssertEqual(expected, contextResponse); }
public async Task HandleRequirementAsync_TC06Async() { // Arrange AuthorizationHandlerContext context = CreateAuthorizationHandlerContext(); _httpContextAccessorMock.Setup(h => h.HttpContext).Returns(CreateHttpContext()); XacmlJsonResponse response = null; _pdpMock.Setup(a => a.GetDecisionForRequest(It.IsAny <XacmlJsonRequestRoot>())).Returns(Task.FromResult(response)); // Act & Assert await Assert.ThrowsAsync <ArgumentNullException>(() => _aah.HandleAsync(context)); }
public async Task PDP_Decision_AltinnApps0007() { string testCase = "AltinnApps0007"; HttpClient client = GetTestClient(); HttpRequestMessage httpRequestMessage = TestSetupUtil.CreateJsonProfileXacmlRequest(testCase); XacmlJsonResponse expected = TestSetupUtil.ReadExpectedJsonProfileResponse(testCase); // Act XacmlJsonResponse contextResponse = await TestSetupUtil.GetXacmlJsonProfileContextResponseAsync(client, httpRequestMessage); // Assert AssertionUtil.AssertEqual(expected, contextResponse); }
/// <inheritdoc/> public async Task <bool> GetDecisionForUnvalidateRequest(XacmlJsonRequestRoot xacmlJsonRequest, ClaimsPrincipal user) { XacmlJsonResponse response = await GetDecisionForRequest(xacmlJsonRequest); if (response?.Response == null) { throw new ArgumentNullException("response"); } _logger.LogInformation($"// Altinn PEP // PDPAppSI // Request sent to platform authorization: {JsonConvert.SerializeObject(xacmlJsonRequest)}"); return(DecisionHelper.ValidatePdpDecision(response.Response, user)); }
/// <summary> /// Assert that two <see cref="XacmlJsonResponse"/> have the same property values. /// </summary> /// <param name="expected">An instance with the expected values.</param> /// <param name="actual">The instance to verify.</param> public static void AssertEqual(XacmlJsonResponse expected, XacmlJsonResponse actual) { Assert.NotNull(actual); Assert.NotNull(expected); Assert.Equal(expected.Response.Count, actual.Response.Count); if (expected.Response.Count > 0) { for (int i = 0; i < expected.Response.Count(); i++) { AssertEqual(expected.Response[i], actual.Response[i]); } } }
private XacmlJsonResponse CreateResponse(string decision) { // Create response XacmlJsonResponse response = new XacmlJsonResponse(); response.Response = new List <XacmlJsonResult>(); // Set result to premit XacmlJsonResult result = new XacmlJsonResult(); result.Decision = decision; response.Response.Add(result); return(response); }
private async Task <EnforcementResult> AuthorizeAction(string org, string app, int partyId, string action) { EnforcementResult enforcementResult = new EnforcementResult(); XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(org, app, HttpContext.User, action, partyId, null); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Instances Controller // Authorization of action {action} failed with request: {JsonConvert.SerializeObject(request)}."); return(enforcementResult); } enforcementResult = DecisionHelper.ValidatePdpDecisionDetailed(response.Response, HttpContext.User); return(enforcementResult); }
/// <inheritdoc/> public async Task <XacmlJsonResponse> GetDecisionForRequest(XacmlJsonRequestRoot xacmlJsonRequest) { XacmlJsonResponse xacmlJsonResponse = null; try { xacmlJsonResponse = await _authorizationApiClient.AuthorizeRequest(xacmlJsonRequest); } catch (Exception e) { _logger.LogError($"Unable to retrieve Xacml Json response. An error occured {e.Message}"); } return(xacmlJsonResponse); }
private async Task <bool> AuthorizeAction(string currenTaskType, string org, string app, string instanceId) { string actionType = currenTaskType.Equals("data") ? "write" : null; XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(org, app, HttpContext.User, actionType, null, instanceId); XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request); if (response?.Response == null) { _logger.LogInformation($"// Process Controller // Authorization of moving process forward failed with request: {JsonConvert.SerializeObject(request)}."); return(false); } bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User); return(authorized); }