コード例 #1
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Ticket ticket = db.Tickets.Find(id);

            if (ticket == null)
            {
                return(HttpNotFound());
            }

            if (DecisionHelper.TicketEditable(ticket))
            {
                ViewBag.AssignedToUserId = new SelectList(db.Users, "Id", "FirstName", ticket.AssignedToUserId);
                //TODO project id should be limited to admin in case a ticket goes to the wrong project
                ViewBag.ProjectId        = new SelectList(db.Projects, "Id", "Name", ticket.ProjectId);
                ViewBag.TicketPriorityId = new SelectList(db.TicketPriorities, "Id", "Name", ticket.TicketPriorityId);
                ViewBag.TicketStatusId   = new SelectList(db.TicketStatuses, "Id", "Name", ticket.TicketStatusId);
                ViewBag.TicketTypeId     = new SelectList(db.TicketTypes, "Id", "Name", ticket.TicketTypeId);
                return(View(ticket));
            }
            else
            {
                return(RedirectToAction("AccessViolation", "Admin"));
            }
        }
コード例 #2
0
        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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        /// <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);
        }
コード例 #5
0
        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);
        }
コード例 #6
0
        private static XacmlJsonCategory CreateEventsResourceCategory(string org, string app, string instanceOwnerPartyId, string instanceGuid, bool includeResult = false)
        {
            XacmlJsonCategory resourceCategory = new XacmlJsonCategory();

            resourceCategory.Attribute = new List <XacmlJsonAttribute>();

            if (!string.IsNullOrWhiteSpace(instanceOwnerPartyId))
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.PartyId, instanceOwnerPartyId, DefaultType, DefaultIssuer, includeResult));
            }

            if (!string.IsNullOrWhiteSpace(instanceGuid) && !string.IsNullOrWhiteSpace(instanceOwnerPartyId))
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.InstanceId, instanceOwnerPartyId + "/" + instanceGuid, DefaultType, DefaultIssuer, includeResult));
            }

            if (!string.IsNullOrWhiteSpace(org))
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.OrgId, org, DefaultType, DefaultIssuer));
            }

            if (!string.IsNullOrWhiteSpace(app))
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppId, app, DefaultType, DefaultIssuer));
            }

            resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppResource, "events", DefaultType, DefaultIssuer));

            return(resourceCategory);
        }
コード例 #7
0
        /// <summary>
        /// Replaces Resource attributes with data from instance. Add all relevant values so PDP have it all
        /// </summary>
        /// <param name="jsonRequest">The JSON Request</param>
        /// <param name="instance">The instance</param>
        public static void EnrichXacmlJsonRequest(XacmlJsonRequestRoot jsonRequest, Instance instance)
        {
            XacmlJsonCategory resourceCategory = new XacmlJsonCategory {
                Attribute = new List <XacmlJsonAttribute>()
            };

            string instanceId           = instance.Id;
            string task                 = instance.Process?.CurrentTask?.ElementId;
            string instanceOwnerPartyId = instance.InstanceOwner.PartyId;
            string org = instance.Org;
            string app = instance.AppId.Split("/")[1];

            if (task != null)
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(XacmlResourceTaskId, task, DefaultType, DefaultIssuer));
            }
            else if (instance.Process?.EndEvent != null)
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(XacmlResourceEndId, instance.Process.EndEvent, DefaultType, DefaultIssuer));
            }

            if (!string.IsNullOrWhiteSpace(instanceId))
            {
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.InstanceId, instanceId, DefaultType, DefaultIssuer, true));
            }

            resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.PartyId, instanceOwnerPartyId, DefaultType, DefaultIssuer));
            resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.OrgId, org, DefaultType, DefaultIssuer));
            resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppId, app, DefaultType, DefaultIssuer));

            // Replaces the current Resource attributes
            jsonRequest.Request.Resource = new List <XacmlJsonCategory> {
                resourceCategory
            };
        }
コード例 #8
0
        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]);
        }
コード例 #9
0
        /// <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)
        {
            XacmlJsonRequestRoot request = DecisionHelper.CreateDecisionRequest(context, requirement, _httpContextAccessor.HttpContext.GetRouteData());

            _logger.LogInformation($"// Storage PEP // AppAccessHandler // Request sent: {JsonConvert.SerializeObject(request)}");

            XacmlJsonResponse response;

            // Get The instance to enrich the request
            Instance instance = await GetInstance(request);

            if (instance != null)
            {
                AuthorizationHelper.EnrichXacmlJsonRequest(request, instance);
                response = await GetDecisionForRequest(request);
            }
            else
            {
                response = await _pdp.GetDecisionForRequest(request);
            }

            if (response?.Response == null)
            {
                throw new Exception("Response is null from PDP");
            }

            if (!DecisionHelper.ValidatePdpDecision(response.Response, context.User))
            {
                context.Fail();
            }

            context.Succeed(requirement);
            await Task.CompletedTask;
        }
コード例 #10
0
        /// <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);
        }
コード例 #11
0
        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}"));
            }
        }
コード例 #12
0
        /// <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;
        }
コード例 #13
0
        private static XacmlJsonCategory CreateMultipleSubjectCategory(IEnumerable <Claim> claims)
        {
            XacmlJsonCategory subjectAttributes = DecisionHelper.CreateSubjectCategory(claims);

            subjectAttributes.Id = SubjectId + "1";

            return(subjectAttributes);
        }
コード例 #14
0
        private static XacmlJsonCategory CreateActionCategory(string actionType, bool includeResult = false)
        {
            XacmlJsonCategory actionAttributes = new XacmlJsonCategory();

            actionAttributes.Attribute = new List <XacmlJsonAttribute>();
            actionAttributes.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(MatchAttributeIdentifiers.ActionId, actionType, DefaultType, DefaultIssuer, includeResult));
            return(actionAttributes);
        }
コード例 #15
0
        public void ValidateResponse_TC07()
        {
            // Arrange
            XacmlJsonResponse response = new XacmlJsonResponse();

            response.Response = new List <XacmlJsonResult>();

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => DecisionHelper.ValidateResponse(response.Response, null));
        }
コード例 #16
0
        public void ValidateResponse_TC06()
        {
            // Arrange
            XacmlJsonResponse response = new XacmlJsonResponse();

            response.Response = null;

            // Act & Assert
            Assert.Throws <ArgumentNullException>(() => DecisionHelper.ValidateResponse(response.Response, CreateUserClaims(false)));
        }
コード例 #17
0
        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));
        }
コード例 #18
0
        public void CreateXacmlJsonRequest_TC02()
        {
            // Arrange & Act
            XacmlJsonRequestRoot requestRoot = DecisionHelper.CreateXacmlJsonRequest(org, app, CreateUserClaims(true), actionType, partyId, null);
            XacmlJsonRequest     request     = requestRoot.Request;

            // Assert
            Assert.Equal(2, request.AccessSubject[0].Attribute.Count);
            Assert.Single(request.Action[0].Attribute);
            Assert.Equal(3, request.Resource[0].Attribute.Count);
        }
コード例 #19
0
        /// <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));
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        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);
        }
コード例 #22
0
        private async Task <bool> AuthorizeInstatiation(string org, string app, Party party)
        {
            bool authorized = false;
            XacmlJsonRequestRoot request  = DecisionHelper.CreateDecisionRequest(org, app, HttpContext.User, "instantiate", party.PartyId.ToString(), 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(authorized);
            }

            authorized = DecisionHelper.ValidatePdpDecision(response.Response, HttpContext.User);
            return(authorized);
        }
コード例 #23
0
        private static List <XacmlJsonCategory> CreateMultipleActionCategory(List <string> actionTypes)
        {
            List <XacmlJsonCategory> actionCategories = new List <XacmlJsonCategory>();
            int counter = 1;

            foreach (string actionType in actionTypes)
            {
                XacmlJsonCategory actionCategory;
                actionCategory    = DecisionHelper.CreateActionCategory(actionType, true);
                actionCategory.Id = ActionId + counter.ToString();
                actionCategories.Add(actionCategory);
                counter++;
            }

            return(actionCategories);
        }
コード例 #24
0
        public void ValidatePdpDecision_TC10()
        {
            // 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 = "4";
            XacmlJsonAttributeAssignment authenticationAttribute = new XacmlJsonAttributeAssignment()
            {
                Category = "urn:altinn:minimum-authenticationlevel",
                Value    = minAuthLevel
            };

            obligation.AttributeAssignment.Add(authenticationAttribute);

            XacmlJsonObligationOrAdvice obligationOrg = new XacmlJsonObligationOrAdvice();

            obligationOrg.AttributeAssignment = new List <XacmlJsonAttributeAssignment>();
            string minAuthLevelOrg = "2";
            XacmlJsonAttributeAssignment authenticationAttributeOrg = new XacmlJsonAttributeAssignment()
            {
                Category = "urn:altinn:minimum-authenticationlevel-org",
                Value    = minAuthLevelOrg
            };

            obligationOrg.AttributeAssignment.Add(authenticationAttributeOrg);

            xacmlJsonResult.Obligations = new List <XacmlJsonObligationOrAdvice>();
            xacmlJsonResult.Obligations.Add(obligationOrg);
            xacmlJsonResult.Obligations.Add(obligation);

            // Act
            EnforcementResult result = DecisionHelper.ValidatePdpDecisionDetailed(response.Response, CreateUserClaims(false, "ttd"));

            // Assert
            Assert.True(result.Authorized);
            Assert.Null(result.FailedObligations);
        }
コード例 #25
0
        public void ValidateResponse_TC01()
        {
            // Arrange
            XacmlJsonResponse response = new XacmlJsonResponse();

            response.Response = new List <XacmlJsonResult>();
            XacmlJsonResult xacmlJsonResult = new XacmlJsonResult();

            xacmlJsonResult.Decision = XacmlContextDecision.Permit.ToString();
            response.Response.Add(xacmlJsonResult);

            // Act
            bool result = DecisionHelper.ValidateResponse(response.Response, CreateUserClaims(false));

            // Assert
            Assert.True(result);
        }
コード例 #26
0
        private static List <XacmlJsonCategory> CreateMultipleResourceCategory(List <CloudEvent> events)
        {
            List <XacmlJsonCategory> resourcesCategories = new List <XacmlJsonCategory>();
            int counter = 1;

            foreach (CloudEvent cloudEvent in events)
            {
                XacmlJsonCategory resourceCategory = new XacmlJsonCategory {
                    Attribute = new List <XacmlJsonAttribute>()
                };

                Uri source = cloudEvent.Source;

                string path = source.PathAndQuery;

                string[] paths = path.Split("/");

                if (paths.Length == 6)
                {
                    // This is the scenario for events related to a given instance
                    string instanceId           = paths[4] + "/" + paths[5];
                    string instanceOwnerPartyId = cloudEvent.Subject.Split("/")[2];
                    string org     = paths[1];
                    string app     = paths[2];
                    string eventId = cloudEvent.Id;

                    if (!string.IsNullOrWhiteSpace(instanceId))
                    {
                        resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.InstanceId, instanceId, DefaultType, DefaultIssuer, true));
                    }

                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppResource, "events", DefaultType, DefaultIssuer));
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.EventId, eventId, DefaultType, DefaultIssuer, true));
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.PartyId, instanceOwnerPartyId, DefaultType, DefaultIssuer));
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.OrgId, org, DefaultType, DefaultIssuer));
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppId, app, DefaultType, DefaultIssuer));
                    resourceCategory.Id = ResourceId + counter.ToString();
                    resourcesCategories.Add(resourceCategory);
                    counter++;
                }
            }

            return(resourcesCategories);
        }
コード例 #27
0
        /// <summary>
        /// Authorize instances, and returns a list of instances that the user has the right to read.
        /// </summary>
        public async Task <List <Instance> > AuthorizeInstances(ClaimsPrincipal user, List <Instance> instances)
        {
            if (instances.Count <= 0)
            {
                return(instances);
            }

            List <Instance> authorizedInstanceList = new List <Instance>();
            List <string>   actionTypes            = new List <string> {
                "read"
            };

            XacmlJsonRequestRoot xacmlJsonRequest = CreateMultiDecisionRequest(user, instances, actionTypes);
            XacmlJsonResponse    response         = await _pdp.GetDecisionForRequest(xacmlJsonRequest);

            foreach (XacmlJsonResult result in response.Response)
            {
                if (DecisionHelper.ValidateDecisionResult(result, user))
                {
                    string instanceId = 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.InstanceId))
                            {
                                instanceId = attribute.Value;
                            }
                        }
                    }

                    Instance instance = instances.FirstOrDefault(i => i.Id == instanceId);
                    authorizedInstanceList.Add(instance);
                }
            }

            return(authorizedInstanceList);
        }
コード例 #28
0
        private static List <XacmlJsonCategory> CreateMultipleResourceCategory(List <Instance> instances)
        {
            List <XacmlJsonCategory> resourcesCategories = new List <XacmlJsonCategory>();
            int counter = 1;

            foreach (Instance instance in instances)
            {
                XacmlJsonCategory resourceCategory = new XacmlJsonCategory {
                    Attribute = new List <XacmlJsonAttribute>()
                };

                string instanceId           = instance.Id.Split("/")[1];
                string task                 = instance.Process?.CurrentTask?.ElementId;
                string instanceOwnerPartyId = instance.InstanceOwner.PartyId;
                string org = instance.Org;
                string app = instance.AppId.Split("/")[1];

                if (task != null)
                {
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(XacmlResourceTaskId, task, DefaultType, DefaultIssuer));
                }
                else if (instance.Process?.EndEvent != null)
                {
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(XacmlResourceEndId, instance.Process.EndEvent, DefaultType, DefaultIssuer));
                }

                if (!string.IsNullOrWhiteSpace(instanceId))
                {
                    resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.InstanceId, instanceOwnerPartyId + "/" + instanceId, DefaultType, DefaultIssuer, true));
                }

                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.PartyId, instanceOwnerPartyId, DefaultType, DefaultIssuer));
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.OrgId, org, DefaultType, DefaultIssuer));
                resourceCategory.Attribute.Add(DecisionHelper.CreateXacmlJsonAttribute(AltinnXacmlUrns.AppId, app, DefaultType, DefaultIssuer));
                resourceCategory.Id = ResourceId + counter.ToString();
                resourcesCategories.Add(resourceCategory);
                counter++;
            }

            return(resourcesCategories);
        }
コード例 #29
0
        public ActionResult Edit(int?id)
        {
            var userId = User.Identity.GetUserId();

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Project project = db.Projects.Find(id);

            if (project == null)
            {
                return(HttpNotFound());
            }
            if (DecisionHelper.ProjectIsEditableByUser(project))
            {
                return(View(project));
            }

            return(RedirectToAction("AccessViolation, Admin"));
        }
コード例 #30
0
        public static PestDetectedResult Generate(List <Pest> pests)
        {
            if (pests == null || pests.Count == 0)
            {
                return(null);
            }

            if (!DecisionHelper.ShouldDoAction(50))
            {
                return(null);
            }

            var rand       = new Random();
            var pestNumber = rand.Next(0, pests.Count);
            var count      = rand.Next(10, 200);

            return(new PestDetectedResult()
            {
                PestId = pests[pestNumber].Id,
                CountOnSquareMeter = count
            });
        }