public void ParseXACMLPolicy_IIIA030Policy()
        {
            XmlDocument policyDocument = new XmlDocument();

            policyDocument.Load(Path.Combine(GetConformanceTestPath(), "IIIA030Policy.xml"));

            XacmlPolicy result;

            using (XmlReader reader = XmlReader.Create(new StringReader(policyDocument.OuterXml)))
            {
                result = XacmlParser.ParseXacmlPolicy(reader);
            }

            Assert.NotNull(result);
            Assert.Equal(2, result.Rules.Count);

            XacmlRule firstRule = result.Rules.Where(r => r.RuleId.Equals("urn:oasis:names:tc:xacml:2.0:conformance-test:IIIA030:rule1")).FirstOrDefault();

            Assert.NotNull(firstRule);
            Assert.Equal(XacmlEffectType.Deny, firstRule.Effect);
            Assert.Equal("A subject whose name is J. Hibbert may not\n            read Bart Simpson's medical record.  NOTAPPLICABLE", firstRule.Description.Trim());
            Assert.NotNull(firstRule.Target);
            Assert.Equal(1, firstRule.Target.AnyOf.Count);

            XacmlRule secondRule = result.Rules.Where(r => r.RuleId.Equals("urn:oasis:names:tc:xacml:2.0:conformance-test:IIIA030:rule2")).FirstOrDefault();

            Assert.NotNull(secondRule);
            Assert.Equal(XacmlEffectType.Permit, secondRule.Effect);
            Assert.Equal("A subject who is at least 5 years older than Bart\n            Simpson may read Bart Simpson's medical record. PERMIT.", secondRule.Description.Trim());
            Assert.Null(secondRule.Target);
        }
Esempio n. 2
0
        public void ParseXACMLPolicy_Rule1()
        {
            XmlDocument policyDocument = new XmlDocument();

            policyDocument.Load(Path.Combine(GetSpecExamplesTestPath(), "Rule1.xml"));

            XacmlPolicy result;

            using (XmlReader reader = XmlReader.Create(new StringReader(policyDocument.OuterXml)))
            {
                result = XacmlParser.ParseXacmlPolicy(reader);
            }

            Assert.NotNull(result);
            Assert.Null(result.Description);
            Assert.Equal(1, result.Rules.Count);

            XacmlRule firstRule = result.Rules.Where(r => r.RuleId.Equals("urn:oasis:names:tc:xacml:3.0:example:ruleid:1")).FirstOrDefault();

            Assert.NotNull(firstRule);

            Assert.Equal(XacmlEffectType.Permit, firstRule.Effect);
            Assert.Equal("A person may read any medical record in the\n      http://www.med.example.com/schemas/record.xsd namespace\n      for which he or she is the designated patient", firstRule.Description.Trim());
            Assert.NotNull(firstRule.Target);

            Assert.Equal(2, firstRule.Target.AnyOf.Count);
        }
        public void ParseXACMLPolicy_IIA001Policy()
        {
            XmlDocument policyDocument = new XmlDocument();

            policyDocument.Load(Path.Combine(GetConformanceTestPath(), "IIA001Policy.xml"));

            XacmlPolicy result;

            using (XmlReader reader = XmlReader.Create(new StringReader(policyDocument.OuterXml)))
            {
                result = XacmlParser.ParseXacmlPolicy(reader);
            }

            Assert.NotNull(result);
            Assert.Equal("Policy for Conformance Test IIA001.", result.Description.Trim());
            Assert.Equal(1, result.Rules.Count);

            XacmlRule firstRule = result.Rules.Where(r => r.RuleId.Equals("urn:oasis:names:tc:xacml:2.0:conformance-test:IIA1:rule")).FirstOrDefault();

            Assert.NotNull(firstRule);

            Assert.Equal(XacmlEffectType.Permit, firstRule.Effect);
            Assert.Equal("Julius Hibbert can read or write Bart Simpson's medical record.", firstRule.Description.Trim());
            Assert.NotNull(firstRule.Target);

            Assert.Equal(3, firstRule.Target.AnyOf.Count);
        }
Esempio n. 4
0
        private static List <ResourceAction> GetActionsFromRule(XacmlRule rule, List <RoleGrant> roles)
        {
            List <ResourceAction> actions = new List <ResourceAction>();

            foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
            {
                foreach (XacmlAllOf allOf in anyOf.AllOf)
                {
                    AttributeMatch actionAttributeMatch = new AttributeMatch();
                    foreach (XacmlMatch xacmlMatch in allOf.Matches)
                    {
                        if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Action))
                        {
                            actionAttributeMatch.Id    = xacmlMatch.AttributeDesignator.AttributeId.OriginalString;
                            actionAttributeMatch.Value = xacmlMatch.AttributeValue.Value;
                            ResourceAction resourceAction = new ResourceAction
                            {
                                Match      = actionAttributeMatch,
                                RoleGrants = new List <RoleGrant>(),
                                Title      = xacmlMatch.AttributeValue.Value
                            };
                            resourceAction.RoleGrants.AddRange(roles);
                            if (!actions.Contains(resourceAction))
                            {
                                actions.Add(resourceAction);
                            }
                        }
                    }
                }
            }

            return(actions);
        }
Esempio n. 5
0
        /// <summary>
        /// protected virtual void WriteRule
        /// </summary>
        /// <param name="writer">XmlWriter writer</param>
        /// <param name="data">XacmlRule data</param>
        protected virtual void WriteRule(XmlWriter writer, XacmlRule data)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            writer.WriteStartElement(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.Rule, this.Version.NamespacePolicy);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.RuleId, data.RuleId);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.Effect, data.Effect.ToString());

            if (data.Description != null)
            {
                writer.WriteElementString(XacmlConstants.Prefixes.Policy, XacmlConstants.ElementNames.Description, this.Version.NamespacePolicy, data.Description);
            }

            if (data.Target != null)
            {
                this.WriteTarget(writer, data.Target);
            }

            if (data.Condition != null)
            {
                this.WriteCondition(writer, data.Condition);
            }

            writer.WriteEndElement();
        }
Esempio n. 6
0
        private static void AssertRuleEqual(XacmlRule expected, XacmlRule actual)
        {
            Assert.NotNull(actual);
            Assert.NotNull(expected);

            Assert.Equal(expected.RuleId, actual.RuleId);
            AssertTargetEqual(expected.Target, actual.Target);

            AssertCollections(expected.Obligations, actual.Obligations, AssertObligationExpressionEqual);
        }
Esempio n. 7
0
        /// <summary>
        /// Builds a XacmlRule <see cref="XacmlRule"/> representation based on the Rule input
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="app">Application identifier which is unique within an organisation.</param>
        /// <param name="offeredByPartyId">The party id of the entity offering the delegated the policy</param>
        /// <param name="coveredByPartyId">The party of the entity having received the delegated policy, if the receiving entity is an organization</param>
        /// <param name="coveredByUserId">The user id of the entity having received the delegated policy, if the receiving entity is a user</param>
        /// <param name="rule">The rule to be delegated</param>
        public static XacmlRule BuildDelegationRule(string org, string app, int offeredByPartyId, int?coveredByPartyId, int?coveredByUserId, Rule rule)
        {
            rule.RuleId = Guid.NewGuid().ToString();

            string    coveredBy      = coveredByPartyId.HasValue ? coveredByPartyId.Value.ToString() : coveredByUserId.Value.ToString();
            XacmlRule delegationRule = new XacmlRule(rule.RuleId, XacmlEffectType.Permit)
            {
                Description = $"Delegation of a right/action from {offeredByPartyId} to {coveredBy}, for a resource on the app; {org}/{app}, by user; {rule.DelegatedByUserId}",
                Target      = BuildDelegationRuleTarget(coveredByPartyId, coveredByUserId, rule)
            };

            return(delegationRule);
        }
        public void WritePolicy_11()
        {
            var subject = new XacmlSubject(
                new XacmlSubjectMatch[]
            {
                new XacmlSubjectMatch(
                    new Uri("http://www.MatchId.www"),
                    new XacmlAttributeValue(new Uri("http://www.DataType.www")),
                    new XacmlSubjectAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false, Category = new Uri("http://www.subjectCategory.www")
                })
            });

            var            target         = new XacmlTarget(subject, null, null);
            XacmlPolicySet xacmlPolicySet = new XacmlPolicySet(new Uri("http://www.PolicySetId.www"), new Uri("http://www.PolicyCombiningAlgId.www"), target);

            xacmlPolicySet.Description  = "description string";
            xacmlPolicySet.XPathVersion = Xacml10Constants.XPathVersions.Xpath10;

            XacmlPolicy xacmlPolicy = new XacmlPolicy(new Uri("http://www.PolicyId.www"), new Uri("http://www.RuleCombiningAlgId.www"), new XacmlTarget())
            {
                Description  = "description string",
                XPathVersion = Xacml10Constants.XPathVersions.Xpath10,
            };

            XacmlRule xacmlRule = new XacmlRule("http://www.RuleId.www", XacmlEffectType.Permit)
            {
                Description = "xacmlRule description"
            };

            xacmlPolicy.Rules.Add(xacmlRule);
            XacmlAttributeAssignment xacmlAttributeAssignment = new XacmlAttributeAssignment(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"));
            XacmlObligation          xacmlObligation          = new XacmlObligation(new Uri("http://www.ObligationId.www"), XacmlEffectType.Permit, new XacmlAttributeAssignment[] { xacmlAttributeAssignment });

            xacmlPolicy.Obligations.Add(xacmlObligation);

            xacmlPolicySet.Policies.Add(xacmlPolicy);

            StringBuilder builder = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(builder)) {
                var serializer = new Xacml10ProtocolSerializer();
                serializer.WritePolicySet(writer, xacmlPolicySet);
            }

            string xml = builder.ToString();

            ValidateMessage(xml, Path.Combine(TestCasePath, "cs-xacml-schema-context-01.xsd"));
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a Rule representation based on a search and a xacmlRule found in a XacmlPolicyFile based on the search
        /// </summary>
        /// <param name="search">The search used to find the correct rule</param>
        /// <param name="xacmlRule">XacmlRule found by the search param to enrich the result with Action and Resource</param>
        /// <returns>The created Rule</returns>
        public static Rule CreateRuleFromPolicyAndRuleMatch(RequestToDelete search, XacmlRule xacmlRule)
        {
            Rule rule = new Rule
            {
                RuleId = xacmlRule.RuleId,
                CreatedSuccessfully = true,
                DelegatedByUserId   = search.DeletedByUserId,
                OfferedByPartyId    = search.PolicyMatch.OfferedByPartyId,
                CoveredBy           = search.PolicyMatch.CoveredBy,
                Resource            = GetResourceFromXcamlRule(xacmlRule),
                Action = GetActionValueFromRule(xacmlRule)
            };

            return(rule);
        }
Esempio n. 10
0
        private static List <AttributeMatch> GetResourceFromXcamlRule(XacmlRule rule)
        {
            List <AttributeMatch> result = new List <AttributeMatch>();

            foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
            {
                foreach (XacmlAllOf allOf in anyOf.AllOf)
                {
                    foreach (XacmlMatch xacmlMatch in allOf.Matches.Where(m => m.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Resource)))
                    {
                        result.Add(new AttributeMatch {
                            Id = xacmlMatch.AttributeDesignator.AttributeId.OriginalString, Value = xacmlMatch.AttributeValue.Value
                        });
                    }
                }
            }

            return(result);
        }
Esempio n. 11
0
        private static AttributeMatch GetActionValueFromRule(XacmlRule rule)
        {
            foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
            {
                foreach (XacmlAllOf allOf in anyOf.AllOf)
                {
                    XacmlMatch action = allOf.Matches.FirstOrDefault(m => m.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Action));

                    if (action != null)
                    {
                        return(new AttributeMatch {
                            Id = action.AttributeDesignator.AttributeId.OriginalString, Value = action.AttributeValue.Value
                        });
                    }
                }
            }

            return(null);
        }
Esempio n. 12
0
        private static List <RoleGrant> GetRolesFromRule(XacmlRule rule)
        {
            List <RoleGrant> roles = new List <RoleGrant>();

            foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
            {
                foreach (XacmlAllOf allOf in anyOf.AllOf)
                {
                    foreach (XacmlMatch xacmlMatch in allOf.Matches)
                    {
                        if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Subject) && xacmlMatch.AttributeDesignator.AttributeId.Equals(XacmlRequestAttribute.RoleAttribute))
                        {
                            roles.Add(new RoleGrant {
                                RoleTypeCode = xacmlMatch.AttributeValue.Value, IsDelegable = true
                            });
                        }
                    }
                }
            }

            return(roles);
        }
Esempio n. 13
0
        private static void WriteRule(XmlWriter writer, XacmlRule xacmlRule)
        {
            Guard.ArgumentNotNull(writer, nameof(writer));
            Guard.ArgumentNotNull(xacmlRule, nameof(xacmlRule));

            writer.WriteStartElement(XacmlConstants.Prefixes.Xacml, XacmlConstants.ElementNames.Rule, Xacml30Constants.NameSpaces.Policy);

            writer.WriteAttributeString(XacmlConstants.AttributeNames.RuleId, xacmlRule.RuleId);
            writer.WriteAttributeString(XacmlConstants.AttributeNames.Effect, xacmlRule.Effect.ToString());

            if (xacmlRule.Description != null)
            {
                WriteDescription(writer, xacmlRule.Description);
            }

            if (xacmlRule.Target != null)
            {
                WriteTarget(writer, xacmlRule.Target);
            }

            if (xacmlRule.Condition != null)
            {
                throw new NotImplementedException($"XacmlSerializer: Serialization of type {xacmlRule.Condition.GetType().Name} currently not supported");
            }

            if (xacmlRule.Obligations != null && xacmlRule.Obligations.Count > 0)
            {
                WriteObligationExpressions(writer, xacmlRule.Obligations);
            }

            if (xacmlRule.Advices != null && xacmlRule.Advices.Count > 0)
            {
                WriteAdviceExpressions(writer, xacmlRule.Advices);
            }

            writer.WriteEndElement();
        }
        /// <summary>
        /// Reads the policy.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.Xml.XmlException">
        /// PolicyId IsNullOrEmpty
        /// or
        /// RuleCombiningAlgId IsNullOrEmpty
        /// </exception>
        public virtual XacmlPolicy ReadPolicy(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            IDictionary <string, string> nsMgr = new Dictionary <string, string>();

            for (int i = 0; i < reader.AttributeCount; i++)
            {
                reader.MoveToAttribute(i);
                if (reader.Prefix == "xmlns")
                {
                    nsMgr.Add(reader.LocalName, reader.Value);
                }
            }

            if (!this.CanRead(reader, XacmlConstants.ElementNames.Policy))
            {
                throw ThrowHelperXml(reader, "XML message is not valid.");
            }

            var gaPolicyId = reader.GetAttribute("PolicyId");

            if (string.IsNullOrEmpty(gaPolicyId))
            {
                throw ThrowHelperXml(reader, "PolicyId IsNullOrEmpty");
            }

            var gaRuleCombiningAlgId = reader.GetAttribute("RuleCombiningAlgId");

            if (string.IsNullOrEmpty(gaRuleCombiningAlgId))
            {
                throw ThrowHelperXml(reader, "RuleCombiningAlgId IsNullOrEmpty");
            }

            reader.ReadStartElement(XacmlConstants.ElementNames.Policy, this.Version.NamespacePolicy);

            string description = null;

            if (reader.IsStartElement(XacmlConstants.ElementNames.Description, this.Version.NamespacePolicy))
            {
                description = reader.ReadElementContentAsString(XacmlConstants.ElementNames.Description, this.Version.NamespacePolicy);
            }

            // PolicySetDefault
            string xpathVersion = null;

            if (reader.IsStartElement(XacmlConstants.ElementNames.PolicyDefaults, this.Version.NamespacePolicy))
            {
                reader.ReadStartElement(XacmlConstants.ElementNames.PolicyDefaults, this.Version.NamespacePolicy);

                if (!reader.IsStartElement(XacmlConstants.ElementNames.XPathVersion, this.Version.NamespacePolicy))
                {
                    throw ThrowHelperXml(reader, "XPathVerison NotStartElement");
                }

                xpathVersion = reader.ReadElementContentAsString(XacmlConstants.ElementNames.XPathVersion, this.Version.NamespacePolicy);

                reader.ReadEndElement();
            }

            XacmlTarget target = null;

            if (reader.IsStartElement(XacmlConstants.ElementNames.Target, this.Version.NamespacePolicy))
            {
                target = ReadTarget(reader);
            }

            XacmlPolicy policy = new XacmlPolicy(new Uri(gaPolicyId, UriKind.RelativeOrAbsolute), new Uri(gaRuleCombiningAlgId, UriKind.RelativeOrAbsolute), target)
            {
                Description  = description,
                XPathVersion = xpathVersion != null ? new Uri(xpathVersion) : null,
            };

            policy.Namespaces = nsMgr;

            XacmlRule rule = null;

            while (reader.IsStartElement(XacmlConstants.ElementNames.Rule, this.Version.NamespacePolicy))
            {
                rule = ReadRule(reader);
                policy.Rules.Add(rule);
            }

            if (reader.IsStartElement(XacmlConstants.ElementNames.Obligations, this.Version.NamespacePolicy))
            {
                reader.ReadStartElement(XacmlConstants.ElementNames.Obligations, this.Version.NamespacePolicy);

                this.ReadList(policy.Obligations, XacmlConstants.ElementNames.Obligation, this.Version.NamespacePolicy, ReadObligation, reader, isRequired: true);

                // end obligations
                reader.ReadEndElement();
            }

            // end policy
            reader.ReadEndElement();

            return(policy);
        }
        public void WritePolicy_20()
        {
            var subject = new XacmlSubject(
                new XacmlSubjectMatch[]
            {
                new XacmlSubjectMatch(
                    new Uri("http://www.MatchId.www"),
                    new XacmlAttributeValue(new Uri("http://www.DataType.www")),
                    new XacmlSubjectAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false, Category = new Uri("http://www.subjectCategory.www")
                }
                    )
            });

            var resource = new XacmlResource(
                new XacmlResourceMatch[]
            {
                new XacmlResourceMatch(
                    new Uri("http://www.MatchId.www"),
                    new XacmlAttributeValue(new Uri("http://www.DataType.www") /*, "xxxx" */),
                    new XacmlResourceAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false
                }
                    )
            });

            var action = new XacmlAction(
                new XacmlActionMatch[]
            {
                new XacmlActionMatch(
                    new Uri("http://www.MatchId.www"),
                    new XacmlAttributeValue(new Uri("http://www.DataType.www")),
                    new XacmlActionAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false
                }
                    )
            });

            var target = new XacmlTarget(subject, resource, action, null);

            // new Uri("http://www.PolicySetId.www")
            XacmlPolicySet xacmlPolicySet = new XacmlPolicySet(new Uri("http://www.PolicyCombiningAlgId.www"), target)
            {
                Description  = "description string",
                XPathVersion = Xacml10Constants.XPathVersions.Xpath10,
            };

            ////#region Policy
            XacmlEnvironment env = new XacmlEnvironment(
                new XacmlEnvironmentMatch[]
            {
                new XacmlEnvironmentMatch(
                    new Uri("http://www.EnvironmentMatchIdId.www"),
                    new XacmlAttributeValue(new Uri("http://www.AttributValue.www")),
                    new XacmlEnvironmentAttributeDesignator(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"))
                {
                    Issuer = "String", MustBePresent = false
                }
                    )
            });

            XacmlTarget targetWithEnvironment = new XacmlTarget(null, null, null, new XacmlEnvironment[] { env });

            XacmlPolicy xacmlPolicy = new XacmlPolicy(new Uri("http://www.PolicyId.www"), new Uri("http://www.RuleCombiningAlgId.www"), targetWithEnvironment)
            {
                Description  = "description string",
                XPathVersion = Xacml10Constants.XPathVersions.Xpath10,
            };

            XacmlRule xacmlRule = new XacmlRule("http://www.RuleId.www", XacmlEffectType.Permit)
            {
                Description = "xacmlRule description"
            };

            xacmlPolicy.Rules.Add(xacmlRule);

            XacmlAttributeAssignment xacmlAttributeAssignment = new XacmlAttributeAssignment(new Uri("http://www.AttributeId.www"), new Uri("http://www.DataType.www"));
            XacmlObligation          xacmlObligation          = new XacmlObligation(new Uri("http://www.ObligationId.www"), XacmlEffectType.Permit, new XacmlAttributeAssignment[] { xacmlAttributeAssignment });

            xacmlPolicy.Obligations.Add(xacmlObligation);

            xacmlPolicySet.Policies.Add(xacmlPolicy);

            StringBuilder builder = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(builder)) {
                var serializer = new Xacml20ProtocolSerializer();
                serializer.WritePolicySet(writer, xacmlPolicySet);
            }

            string xml = builder.ToString();

            ValidateMessage(xml, Path.Combine(TestCasePath, "access_control-xacml-2.0-policy-schema-os.xsd"));
        }
Esempio n. 16
0
        private static List <string> GetResourcePoliciesFromRule(Dictionary <string, ResourcePolicy> resourcePolicies, XacmlRule rule)
        {
            List <string> policyKeys = new List <string>();

            foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
            {
                foreach (XacmlAllOf allOf in anyOf.AllOf)
                {
                    StringBuilder         bld             = new StringBuilder();
                    string                resourceKey     = string.Empty;
                    List <AttributeMatch> resourceMatches = new List <AttributeMatch>();
                    foreach (XacmlMatch xacmlMatch in allOf.Matches)
                    {
                        if (xacmlMatch.AttributeDesignator.Category.Equals(XacmlConstants.MatchAttributeCategory.Resource))
                        {
                            bld.Append(xacmlMatch.AttributeDesignator.AttributeId);
                            bld.Append(xacmlMatch.AttributeValue.Value);
                            resourceKey = bld.ToString();
                            resourceMatches.Add(new AttributeMatch {
                                Id = xacmlMatch.AttributeDesignator.AttributeId.OriginalString, Value = xacmlMatch.AttributeValue.Value
                            });
                        }
                    }

                    CreateUniqueResourcePolicy(resourceKey, policyKeys, resourcePolicies, resourceMatches);
                }
            }

            return(policyKeys);
        }
Esempio n. 17
0
        private async Task <List <Rule> > ProcessPolicyFile(string policyPath, string org, string app, RequestToDelete deleteRequest)
        {
            List <Rule> currentRules = new List <Rule>();
            string      leaseId      = await _policyRepository.TryAcquireBlobLease(policyPath);

            if (leaseId == null)
            {
                _logger.LogError("Could not acquire blob lease lock on delegation policy at path: {policyPath}", policyPath);
                return(null);
            }

            try
            {
                bool             isAllRulesDeleted = false;
                string           coveredBy         = DelegationHelper.GetCoveredByFromMatch(deleteRequest.PolicyMatch.CoveredBy, out int?coveredByUserId, out int?coveredByPartyId);
                string           offeredBy         = deleteRequest.PolicyMatch.OfferedByPartyId.ToString();
                DelegationChange currentChange     = await _delegationRepository.GetCurrentDelegationChange($"{org}/{app}", deleteRequest.PolicyMatch.OfferedByPartyId, coveredByPartyId, coveredByUserId);

                XacmlPolicy existingDelegationPolicy = null;
                if (currentChange.DelegationChangeType == DelegationChangeType.RevokeLast)
                {
                    _logger.LogWarning("The policy is already deleted for App: {org}/{app} CoveredBy: {coveredBy} OfferedBy: {offeredBy}", org, app, coveredBy, offeredBy);
                    return(null);
                }

                existingDelegationPolicy = await _prp.GetPolicyVersionAsync(currentChange.BlobStoragePolicyPath, currentChange.BlobStorageVersionId);

                foreach (string ruleId in deleteRequest.RuleIds)
                {
                    XacmlRule xacmlRuleToRemove = existingDelegationPolicy.Rules.FirstOrDefault(r => r.RuleId == ruleId);
                    if (xacmlRuleToRemove == null)
                    {
                        _logger.LogWarning("The rule with id: {ruleId} does not exist in policy with path: {policyPath}", ruleId, policyPath);
                        continue;
                    }

                    existingDelegationPolicy.Rules.Remove(xacmlRuleToRemove);
                    Rule currentRule = PolicyHelper.CreateRuleFromPolicyAndRuleMatch(deleteRequest, xacmlRuleToRemove);
                    currentRules.Add(currentRule);
                }

                isAllRulesDeleted = existingDelegationPolicy.Rules.Count == 0;

                // if nothing is deleted no update has been done and policy and postgree update can be skipped
                if (currentRules.Count > 0)
                {
                    Response <BlobContentInfo> response;
                    try
                    {
                        // Write delegation policy to blob storage
                        MemoryStream dataStream = PolicyHelper.GetXmlMemoryStreamFromXacmlPolicy(existingDelegationPolicy);
                        response = await _policyRepository.WritePolicyConditionallyAsync(policyPath, dataStream, leaseId);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Writing of delegation policy at path: {policyPath} failed. Is delegation blob storage account alive and well?", policyPath);
                        return(null);
                    }

                    // Write delegation change to postgresql
                    DelegationChange change = new DelegationChange
                    {
                        DelegationChangeType  = isAllRulesDeleted ? DelegationChangeType.RevokeLast : DelegationChangeType.Revoke,
                        AltinnAppId           = $"{org}/{app}",
                        OfferedByPartyId      = deleteRequest.PolicyMatch.OfferedByPartyId,
                        CoveredByPartyId      = coveredByPartyId,
                        CoveredByUserId       = coveredByUserId,
                        PerformedByUserId     = deleteRequest.DeletedByUserId,
                        BlobStoragePolicyPath = policyPath,
                        BlobStorageVersionId  = response.Value.VersionId
                    };

                    change = await _delegationRepository.InsertDelegation(change);

                    if (change == null || change.DelegationChangeId <= 0)
                    {
                        // Comment:
                        // This means that the current version of the root blob is no longer in sync with changes in authorization postgresql delegation.delegatedpolicy table.
                        // The root blob is in effect orphaned/ignored as the delegation policies are always to be read by version, and will be overritten by the next delegation change.
                        _logger.LogError("Writing of delegation change to authorization postgresql database failed for changes to delegation policy at path: {policyPath}. is authorization postgresql database alive and well?", policyPath);
                        return(null);
                    }

                    try
                    {
                        await _eventQueue.Push(change);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogCritical(new EventId(delegationChangeEventQueueErrorId, "DelegationChangeEventQueue.Push.Error"), ex, "DeleteRules could not push DelegationChangeEvent to DelegationChangeEventQueue. DelegationChangeEvent must be retried for successful sync with SBL Authorization. DelegationChange: {change}", change);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An exception occured while processing rules to delete in policy: {policyPath}", policyPath);
                return(null);
            }
            finally
            {
                _policyRepository.ReleaseBlobLease(policyPath, leaseId);
            }

            return(currentRules);
        }