Esempio n. 1
0
        public void IIIF003()
        {
            string[] files = new string[] { "2.IIIF003Policy.xml", "2.IIIF003Request.xml", "2.IIIF003Response.xml" };
            Assert.AreEqual(files.Length, 3); FileInfo policyFile = new FileInfo(Consts.Path + files[0]);
            FileInfo requestFile  = new FileInfo(Consts.Path + files[1]);
            FileInfo responseFile = new FileInfo(Consts.Path + files[2]);

            using (FileStream fs = new FileStream(policyFile.FullName, FileMode.Open, FileAccess.Read))
                using (FileStream fs1 = new FileStream(requestFile.FullName, FileMode.Open, FileAccess.Read))
                    using (FileStream fs2 = new FileStream(responseFile.FullName, FileMode.Open, FileAccess.Read))
                    {
                        // Load Policy
                        PolicyDocument policyDocument = (PolicyDocument)PolicyLoader.LoadPolicyDocument(fs, XacmlVersion.Version20, DocumentAccess.ReadOnly);
                        // Load Request
                        ContextDocumentReadWrite requestDocument = ContextLoader.LoadContextDocument(fs1, XacmlVersion.Version20);
                        // Load ResponseElement
                        ContextDocumentReadWrite responseDocument = ContextLoader.LoadContextDocument(fs2, XacmlVersion.Version20);
                        EvaluationEngine         engine           = new EvaluationEngine();

                        ResponseElement res = engine.Evaluate(policyDocument, (ContextDocument)requestDocument);
                        Assert.AreEqual(((ResultElement)res.Results[0]).Obligations.Count, ((ResultElement)responseDocument.Response.Results[0]).Obligations.Count);
                        Assert.AreEqual(responseDocument.Response.Results.Count, res.Results.Count);
                        Assert.IsTrue(((ResultElement)res.Results[0]).Decision.ToString() == ((ResultElement)responseDocument.Response.Results[0]).Decision.ToString(), string.Format("Decission incorrect Expected:{0} Returned:{1}", ((ResultElement)responseDocument.Response.Results[0]).Decision.ToString(), ((ResultElement)res.Results[0]).Decision.ToString()));
                        Assert.IsTrue(((ResultElement)res.Results[0]).Status.StatusCode.Value == ((ResultElement)responseDocument.Response.Results[0]).Status.StatusCode.Value, String.Format("Status incorrect Expected:{0} Returned:{1}", ((ResultElement)responseDocument.Response.Results[0]).Status.StatusCode.Value, ((ResultElement)res.Results[0]).Status.StatusCode.Value));
                    }
        }
        public void ConformanceTestIIE_30(XmlDocument policy, XmlDocument request, XmlDocument response, XmlDocument aPolicy, XmlDocument aPolicySet)
        {
            var serialize = new Xacml30ProtocolSerializer();
            XacmlContextRequest  requestData;
            XacmlContextResponse responseData;
            XacmlPolicy          aPolicyData;
            XacmlPolicySet       aPolicySetData;

            using (XmlReader reader = XmlReader.Create(new StringReader(request.OuterXml))) {
                requestData = serialize.ReadContextRequest(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(response.OuterXml))) {
                responseData = serialize.ReadContextResponse(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(aPolicy.OuterXml))) {
                aPolicyData = serialize.ReadPolicy(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(aPolicySet.OuterXml))) {
                aPolicySetData = serialize.ReadPolicySet(reader);
            }

            var policyRepositoryMock = Substitute.For <IXacmlPolicyRepository>();

            policyRepositoryMock.RequestPolicy(Arg.Is(aPolicyData.PolicyId)).Returns(aPolicyData);
            policyRepositoryMock.RequestPolicySet(Arg.Is(aPolicySetData.PolicySetId)).Returns(aPolicySetData);

            EvaluationEngine engine = EvaluationEngineFactory.Create(policy, policyRepositoryMock);

            XacmlContextResponse evaluatedResponse = engine.Evaluate(requestData, request);

            XacmlResponseAssert(responseData, evaluatedResponse);
        }
Esempio n. 3
0
        public void IID002()
        {
            string[] files = new string[] { "2.IID002Policy.xml", "2.IID002Request.xml", "2.IID002Response.xml" };
            Assert.AreEqual(files.Length, 3); FileInfo policyFile = new FileInfo(Consts.Path + files[0]);
            FileInfo requestFile = new FileInfo(Consts.Path + files[1]);
            FileInfo ResponseElementFile = new FileInfo(Consts.Path + files[2]);
            using (FileStream fs = new FileStream(policyFile.FullName, FileMode.Open, FileAccess.Read))
            using (FileStream fs1 = new FileStream(requestFile.FullName, FileMode.Open, FileAccess.Read))
            using (FileStream fs2 = new FileStream(ResponseElementFile.FullName, FileMode.Open, FileAccess.Read))
            {
                // Load Policy
                PolicyDocument policyDocument = (PolicyDocument)PolicyLoader.LoadPolicyDocument(fs, XacmlVersion.Version20, DocumentAccess.ReadOnly);
                // Load Request
                ContextDocumentReadWrite requestDocument = ContextLoader.LoadContextDocument(fs1, XacmlVersion.Version20);
                // Load ResponseElement
                ContextDocumentReadWrite ResponseElementDocument = ContextLoader.LoadContextDocument(fs2, XacmlVersion.Version20);
                EvaluationEngine engine = new EvaluationEngine();

                ResponseElement res = engine.Evaluate(policyDocument, (ContextDocument)requestDocument);
                Assert.AreEqual(((ResultElement)res.Results[0]).Obligations.Count, ((ResultElement)ResponseElementDocument.Response.Results[0]).Obligations.Count);
                Assert.AreEqual(ResponseElementDocument.Response.Results.Count, res.Results.Count);
                Assert.IsTrue(((ResultElement)res.Results[0]).Decision.ToString() == ((ResultElement)ResponseElementDocument.Response.Results[0]).Decision.ToString(), string.Format("Decission incorrect Expected:{0} Returned:{1}", ((ResultElement)ResponseElementDocument.Response.Results[0]).Decision.ToString(), ((ResultElement)res.Results[0]).Decision.ToString()));
                Assert.IsTrue(((ResultElement)res.Results[0]).Status.StatusCode.Value == ((ResultElement)ResponseElementDocument.Response.Results[0]).Status.StatusCode.Value, String.Format("Status incorrect Expected:{0} Returned:{1}", ((ResultElement)ResponseElementDocument.Response.Results[0]).Status.StatusCode.Value, ((ResultElement)res.Results[0]).Status.StatusCode.Value));

            }
        }
        private static async Task Main()
        {
            var client = new HttpClient();
            HttpResponseMessage ruleSetResponse = await client.GetAsync(IpMaturityMatrixRuleset.RuleSetDefinitionsUrl).ConfigureAwait(false);

            ruleSetResponse.EnsureSuccessStatusCode();
            string yamlRuleText = await ruleSetResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            var yamlRules       = IpMaturityMatrixRuleset.FromYaml(yamlRuleText);
            var immProjectScore = IpMaturityMatrix.FromYaml(File.ReadAllText("imm-default.yaml"));

            var evaluationEngine = new EvaluationEngine(new RuleDefinitionRepository(yamlRules));

            var col1 = new StringBuilder();
            var col2 = new StringBuilder();

            ImmEvaluation evalutionResult = evaluationEngine.Evaluate(immProjectScore);

            foreach (var result in evalutionResult.RuleEvaluations)
            {
                Console.WriteLine($"{result.RuleAssertion.Name} {result.Percentage}% Score: {result.Score}");

#pragma warning disable RCS1197 // Optimize StringBuilder.Append/AppendLine call.
                col1.AppendLine($"<tspan x='30' dy='1.5em'>{WebUtility.HtmlEncode(result.RuleAssertion.Name)}</tspan>");
                col2.AppendLine($"<tspan x='310' dy='1.5em'>{result.Percentage}%</tspan>");
#pragma warning restore RCS1197 // Optimize StringBuilder.Append/AppendLine call.

                File.WriteAllText($"imm-{result.RuleAssertion.Id}.svg", BadgePainter.DrawSVG(WebUtility.HtmlEncode(result.RuleAssertion.Name !), $"{result.Percentage}%", ColorScheme.Red, Style.FlatSquare));
            }

            Console.WriteLine($"{evalutionResult.TotalScore} / {evalutionResult.MaximumPossibleTotalScore}");

            File.WriteAllText("imm.svg", BadgePainter.DrawSVG("IMM", $"{evalutionResult.TotalScore} / {evalutionResult.MaximumPossibleTotalScore}", ColorScheme.Red, Style.Flat));
            File.WriteAllText("imm-table.svg", string.Format(Resources.Table, col1.ToString(), col2.ToString()));
        }
        public void ConformanceTest_30(XmlDocument policy, XmlDocument request, XmlDocument response, Type expectedException)
        {
            var serialize = new Xacml30ProtocolSerializer();
            XacmlContextRequest  requestData;
            XacmlContextResponse responseData;

            Action action = () => {
                using (XmlReader reader = XmlReader.Create(new StringReader(request.OuterXml))) {
                    requestData = serialize.ReadContextRequest(reader);
                }

                using (XmlReader reader = XmlReader.Create(new StringReader(response.OuterXml))) {
                    responseData = serialize.ReadContextResponse(reader);
                }

                EvaluationEngine     engine            = EvaluationEngineFactory.Create(policy, null);
                XacmlContextResponse evaluatedResponse = engine.Evaluate(requestData, request);
                XacmlResponseAssert(responseData, evaluatedResponse);
            };

            if (expectedException != null)
            {
                Assert.That(() => action(), Throws.TypeOf(expectedException));
            }
            else
            {
                action();
            }
        }
        public void IIE003_20()
        {
            XmlDocument policy   = new XmlDocument();
            XmlDocument request  = new XmlDocument();
            XmlDocument response = new XmlDocument();

            XmlDocument policy1 = new XmlDocument();
            XmlDocument policy2 = new XmlDocument();

            policy.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IIE003Policy.xml"));
            request.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IIE003Request.xml"));
            response.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IIE003Response.xml"));
            policy1.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IIE003PolicyId1.xml"));
            policy2.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IIE003PolicyId2.xml"));

            var serialize = new Xacml20ProtocolSerializer();
            XacmlContextRequest  requestData;
            XacmlContextResponse responseData;

            XacmlPolicy policy1Data;
            XacmlPolicy policy2Data;

            using (XmlReader reader = XmlReader.Create(new StringReader(request.OuterXml))) {
                requestData = serialize.ReadContextRequest(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(response.OuterXml))) {
                responseData = serialize.ReadContextResponse(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(policy1.OuterXml))) {
                policy1Data = serialize.ReadPolicy(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(policy2.OuterXml))) {
                policy2Data = serialize.ReadPolicy(reader);
            }

            var policyRepositoryMock = Substitute.For <IXacmlPolicyRepository>();

            policyRepositoryMock.RequestPolicy(Arg.Is(policy1Data.PolicyId)).Returns(policy1Data);
            policyRepositoryMock.RequestPolicy(Arg.Is(policy2Data.PolicyId)).Returns(policy2Data);
            policyRepositoryMock.RequestPolicySet(Arg.Any <Uri>()).Returns((XacmlPolicySet)null);

            EvaluationEngine engine = EvaluationEngineFactory.Create(policy, policyRepositoryMock);

            XacmlContextResponse evaluatedResponse = engine.Evaluate(requestData, request);

            XacmlResponseAssert(responseData, evaluatedResponse);
        }
        public void IID030_20()
        {
            XmlDocument request  = new XmlDocument();
            XmlDocument response = new XmlDocument();

            XmlDocument policy1 = new XmlDocument();
            XmlDocument policy2 = new XmlDocument();

            request.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IID030Request.xml"));
            response.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IID030Response.xml"));
            policy1.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IID030Policy1.xml"));
            policy2.Load(Path.Combine(Xacml20TestsCases.TestCasePath, "IID030Policy2.xml"));

            var serialize = new Xacml20ProtocolSerializer();
            XacmlContextRequest  requestData;
            XacmlContextResponse responseData;

            XacmlPolicy policy1Data;
            XacmlPolicy policy2Data;

            using (XmlReader reader = XmlReader.Create(new StringReader(request.OuterXml))) {
                requestData = serialize.ReadContextRequest(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(response.OuterXml))) {
                responseData = serialize.ReadContextResponse(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(policy1.OuterXml))) {
                policy1Data = serialize.ReadPolicy(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(policy2.OuterXml))) {
                policy2Data = serialize.ReadPolicy(reader);
            }

            var policySet = new XacmlPolicySet(Xacml10Constants.PolicyCombiningAlgorithms.OnlyOneApplicable, new XacmlTarget()); // TODO: PolicyCombiningAlgorithms

            policySet.Policies.Add(policy1Data);
            policySet.Policies.Add(policy2Data);

            EvaluationEngine engine = new EvaluationEngine(policySet);

            XacmlContextResponse evaluatedResponse = engine.Evaluate(requestData, request);

            XacmlResponseAssert(responseData, evaluatedResponse);
        }
Esempio n. 8
0
        public async Task <HttpResponseMessage> GitHubImmByRule(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "imm/github/{org}/{project}/rule/{ruleId}")] HttpRequest request,
            string org,
            string project,
            string ruleId)
        {
            var ruleIdAsGuid = Guid.Parse(ruleId);

            (string rulesObjectName, string projectObjectName) = this.GetGitHubBranchOrObjectNames(request);
            (IRuleDefinitionRepository ruleDefinitions, IpMaturityMatrix imm) =
                await this.GetImmRulesFromGitHubAsync(org, project, rulesObjectName, projectObjectName).ConfigureAwait(false);

            var            evaluationEngine = new EvaluationEngine(ruleDefinitions);
            RuleEvaluation result           = evaluationEngine.Evaluate(imm).RuleEvaluations.First(x => x.RuleAssertion.Id == ruleIdAsGuid);

            return(this.CreateUncacheResponse(new ByteArrayContent(Encoding.ASCII.GetBytes(BadgePainter.DrawSVG(WebUtility.HtmlEncode(result.RuleAssertion.Name !), $"{result.Percentage}%", GetColourSchemeForPercentage(result.Percentage), Style.Flat))), "image/svg+xml"));
        }
Esempio n. 9
0
        public void RunOfficialTestsCheckResult_Geo(XmlDocument policy, XmlDocument request, XmlDocument response)
        {
            var serialize = new Xacml30ProtocolSerializer();
            XacmlContextRequest  requestData;
            XacmlContextResponse responseData;

            using (XmlReader reader = XmlReader.Create(new StringReader(request.OuterXml))) {
                requestData = serialize.ReadContextRequest(reader);
            }

            using (XmlReader reader = XmlReader.Create(new StringReader(response.OuterXml))) {
                responseData = serialize.ReadContextResponse(reader);
            }

            EvaluationEngine engine = EvaluationEngineFactory.Create(policy, null);

            XacmlContextResponse evaluatedResponse = engine.Evaluate(requestData, request);

            Assert.AreEqual(responseData.Results.First().Decision, evaluatedResponse.Results.First().Decision, evaluatedResponse.Results.First().Status.StatusMessage);
            Assert.True(evaluatedResponse.Results.First().Obligations.Count ==
                        responseData.Results.First().Obligations.Count);
        }
Esempio n. 10
0
        public async Task <HttpResponseMessage> GitHubImmTotalScore(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "imm/github/{org}/{project}/total")] HttpRequest request,
            string org,
            string project)
        {
            (string rulesObjectName, string projectObjectName) = this.GetGitHubBranchOrObjectNames(request);
            (IRuleDefinitionRepository ruleSet, IpMaturityMatrix ruleAssertions) =
                await this.GetImmRulesFromGitHubAsync(org, project, rulesObjectName, projectObjectName).ConfigureAwait(false);

            var evaluationEngine = new EvaluationEngine(ruleSet);

            ImmEvaluation evaluationResult = evaluationEngine.Evaluate(ruleAssertions);

            string svg = BadgePainter.DrawSVG(
                "IMM",
                $"{evaluationResult.TotalScore} / {evaluationResult.MaximumPossibleTotalScore}",
                GetColourSchemeForPercentage(100M * evaluationResult.TotalScore / evaluationResult.MaximumPossibleTotalScore),
                Style.Flat);

            return(this.CreateUncacheResponse(
                       new ByteArrayContent(Encoding.ASCII.GetBytes(svg)),
                       "image/svg+xml"));
        }
Esempio n. 11
0
        public async Task <HttpResponseMessage> GitHubImmAllBadges(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "imm/github/{org}/{project}/showbadges")] HttpRequest request,
            string org,
            string project)
        {
            (string rulesObjectName, string projectObjectName) = this.GetGitHubBranchOrObjectNames(request);
            (IRuleDefinitionRepository ruleSet, IpMaturityMatrix ruleAssertions) =
                await this.GetImmRulesFromGitHubAsync(org, project, rulesObjectName, projectObjectName).ConfigureAwait(false);

            var evaluationEngine = new EvaluationEngine(ruleSet);

            ImmEvaluation evaluationResult = evaluationEngine.Evaluate(ruleAssertions);

            string encodedRulesObjectName   = WebUtility.UrlEncode(rulesObjectName);
            string encodedProjectObjectName = WebUtility.UrlEncode(projectObjectName);

            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                sw.WriteLine("<!DOCTYPE html>");
                sw.WriteLine("<html>");
                sw.WriteLine("<head>");
                sw.WriteLine("    <meta charset=\"utf-8\" />");
                sw.Write("    <title>IP Maturity Matrix for");
                sw.Write(org);
                sw.Write("/");
                sw.Write(org);
                sw.Write(" (");
                sw.Write(projectObjectName);
                if (rulesObjectName != "master")
                {
                    sw.Write(", rules: ");
                    sw.Write(WebUtility.HtmlEncode(rulesObjectName));
                }
                sw.WriteLine(")</title>");
                sw.WriteLine("<body>");

                sw.WriteLine("  <div>");
                sw.WriteLine("  <p>Total score</p>");

                sw.Write("    <img src=\"/api/imm/github/");
                sw.Write(org);
                sw.Write("/");
                sw.Write(project);
                sw.Write("/total");
                sw.Write("?cache=false&definitionsBranch=");
                sw.Write(encodedRulesObjectName);
                sw.Write("&projectBranch=");
                sw.Write(encodedProjectObjectName);
                sw.WriteLine("\" />");

                sw.WriteLine("  </div>");

                sw.WriteLine("  <div>");
                sw.WriteLine("  <p>Rules</p>");

                sw.WriteLine("  <table>");
                sw.WriteLine("    <tbody>");

                foreach (var evaluation in evaluationResult.RuleEvaluations)
                {
                    sw.WriteLine("      <tr>");
                    sw.WriteLine("        <td>");
                    sw.Write("          <img src=\"/api/imm/github/");
                    sw.Write(org);
                    sw.Write("/");
                    sw.Write(project);
                    sw.Write("/rule/");
                    sw.Write(evaluation.RuleAssertion.Id);
                    sw.Write("?cache=false&definitionsBranch=");
                    sw.Write(encodedRulesObjectName);
                    sw.Write("&projectBranch=");
                    sw.Write(encodedProjectObjectName);
                    sw.WriteLine("\" />");
                    sw.WriteLine("        </td>");
                    sw.WriteLine("      </tr>");
                }

                sw.WriteLine("    </tbody>");
                sw.WriteLine("  </table>");
                sw.WriteLine("  </div>");
                sw.WriteLine("</body>");
                sw.WriteLine("</html>");
            }

            //string svg = BadgePainter.DrawSVG("IMM", $"{evaluationResult.TotalScore} / {evaluationResult.MaximumPossibleTotalScore}", ColorScheme.Red, Style.Flat);
            return(this.CreateUncacheResponse(
                       new StringContent(sb.ToString(), Encoding.UTF8),
                       "text/html"));
        }
Esempio n. 12
0
 public void Can_Handle_Basic_Integers()
 {
     Assert.AreEqual(3, _engine.Evaluate <int>("2 + 1"));
     Assert.AreEqual(-1, _engine.Evaluate <int>("4 - 5"));
     Assert.AreEqual(30, _engine.Evaluate <int>("3 * 10"));
     Assert.AreEqual(3, _engine.Evaluate <int>("6/2"));
 }