Exemple #1
0
        // Process the artifact resolve request received from the identity provider in response
        // to the artifact sent by the service provider.
        private void ProcessArtifactResolve()
        {
            Trace.Write("IdP", "Processing artifact resolve request");

            // Receive the artifact resolve request.
            XmlElement      artifactResolveXml = ArtifactResolver.ReceiveArtifactResolve(Request);
            ArtifactResolve artifactResolve    = new ArtifactResolve(artifactResolveXml);

            // Get the artifact.
            HTTPArtifactType4 httpArtifact = new HTTPArtifactType4(artifactResolve.Artifact.ArtifactValue);

            // Remove the artifact state from the cache.
            HTTPArtifactState httpArtifactState = HTTPArtifactStateCache.Remove(httpArtifact);

            if (httpArtifactState == null)
            {
                throw new ArgumentException("Invalid artifact.");
            }

            // Create an artifact response containing the cached SAML message.
            ArtifactResponse artifactResponse = new ArtifactResponse();

            artifactResponse.Issuer      = new Issuer(CreateAbsoluteURL("~/"));
            artifactResponse.SAMLMessage = httpArtifactState.SAMLMessage;

            XmlElement artifactResponseXml = artifactResponse.ToXml();

            // Send the artifact response.
            ArtifactResolver.SendArtifactResponse(Response, artifactResponseXml);

            Trace.Write("IdP", "Processed artifact resolve request");
        }
Exemple #2
0
        // Receive the SAML response from the identity provider.
        private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the identity provider to service provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("SP", "Receiving SAML response over binding " + bindingType);

            // Receive the SAML response over the specified binding.
            XmlElement samlResponseXml = null;

            switch (bindingType)
            {
            case BindingTypes.Post:
                ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState);
                break;

            case BindingTypes.Artifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                samlResponseXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Unknown binding type");
            }

            // Verify the response's signature.
            if (SAMLMessageSignature.IsSigned(samlResponseXml))
            {
                Trace.Write("SP", "Verifying response signature");
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate];

                if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate))
                {
                    throw new ArgumentException("The SAML response signature failed to verify.");
                }
            }

            // Deserialize the XML.
            samlResponse = new SAMLResponse(samlResponseXml);

            Trace.Write("SP", "Received SAML response");
        }
Exemple #3
0
        private static void generateSnapshotAndCompare(StructureDefinition original, ArtifactResolver source)
        {
            var generator = new SnapshotGenerator(source, markChanges: false);

            var expanded = (StructureDefinition)original.DeepCopy();

            Assert.IsTrue(original.IsExactly(expanded));

            generator.Generate(expanded);

            // Simulate bug in Grahame's expander
            if (original.Snapshot.Element.Count == expanded.Snapshot.Element.Count)
            {
                for (var ix = 0; ix < expanded.Snapshot.Element.Count; ix++)
                {
                    if (original.Snapshot.Element[ix].Path == expanded.Snapshot.Element[ix].Path)
                    {
                        expanded.Snapshot.Element[ix].Min         = original.Snapshot.Element[ix].Min;
                        expanded.Snapshot.Element[ix].MustSupport = original.Snapshot.Element[ix].MustSupport;
                    }
                }
            }

            var areEqual = original.IsExactly(expanded);

            if (!areEqual)
            {
                File.WriteAllText("c:\\temp\\snapshotgen-source.xml", FhirSerializer.SerializeResourceToXml(original));
                File.WriteAllText("c:\\temp\\snapshotgen-dest.xml", FhirSerializer.SerializeResourceToXml(expanded));
            }

            Assert.IsTrue(areEqual);
        }
        public void TestSourceCaching()
        {
            var src = new CachedArtifactSource(ArtifactResolver.CreateDefault());

            src.Prepare();

            Stopwatch sw1 = new Stopwatch();

            // Ensure looking up a failed endpoint repeatedly does not cost much time
            sw1.Start();
            src.ReadResourceArtifact(new Uri("http://some.none.existant.address.nl"));
            sw1.Stop();

            var sw2 = new Stopwatch();

            sw2.Start();
            src.ReadResourceArtifact(new Uri("http://some.none.existant.address.nl"));
            sw2.Stop();

            Assert.IsTrue(sw2.ElapsedMilliseconds < sw1.ElapsedMilliseconds && sw2.ElapsedMilliseconds < 100);

            // Now try an existing artifact
            sw1.Restart();
            src.ReadResourceArtifact(new Uri("http://hl7.org/fhir/v2/vs/0292"));
            sw1.Stop();

            sw2.Restart();
            src.ReadResourceArtifact(new Uri("http://hl7.org/fhir/v2/vs/0292"));
            sw2.Stop();

            Assert.IsTrue(sw2.ElapsedMilliseconds < sw1.ElapsedMilliseconds && sw2.ElapsedMilliseconds < 100);
        }
Exemple #5
0
        public void LocateStructure()
        {
            var locator    = new StructureLoader(ArtifactResolver.CreateDefault());
            var profileUri = new Uri("http://hl7.org/fhir/Profile/Profile");

            var prof = locator.LocateStructure(profileUri, new Code("Profile"));

            Assert.IsNotNull(prof);
            Assert.AreEqual("Profile", prof.Type);
            //Assert.AreEqual(profileUri.ToString(), prof.GetProfileLocation());

            // Try to locate a structure that cannot be found in the given profile
            prof = locator.LocateStructure(profileUri, new Code("Patient"));
            Assert.IsNull(prof);

            profileUri = new Uri("http://take.from.disk/Profile/example-lipid-profile");
            var profileUriWithFrag = new Uri(profileUri.ToString() + "#lipidResultMessage");

            prof = locator.LocateStructure(profileUriWithFrag, new Code("MessageHeader"));
            Assert.IsNotNull(prof);
            Assert.AreEqual("MessageHeader", prof.Type);
            Assert.AreEqual("lipidResultMessage", prof.Name);
            //Assert.AreEqual(profileUri.ToString(), prof.GetProfileLocation());

            // Try to locate a structure that cannot be found in the profile by name
            profileUriWithFrag = new Uri(profileUri.ToString() + "#XXX");
            prof = locator.LocateStructure(profileUriWithFrag, new Code("Profile"));
            Assert.IsNull(prof);
        }
Exemple #6
0
        // Receive the SAML response from the identity provider.
        private void ReceiveSAMLResponse(ref SAMLResponse samlResponse, ref string relayState)
        {
            Trace.Write("SP", "Receiving SAML response");

            // Determine the identity provider to service provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            // Receive the SAML response over the specified binding.
            XmlElement samlResponseXml = null;

            switch (bindingType)
            {
            case SAMLIdentifiers.BindingURIs.HTTPPost:
                ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderURL = WebConfigurationManager.AppSettings["idpArtifactResponderURL"];

                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the SAML response from the artifact response.
                samlResponseXml = artifactResponse.SAMLMessage;
                break;

            default:
                Trace.Write("SP", "Invalid identity provider to service provider binding");
                return;
            }

            // Verify the response's signature.
            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate];

            if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate))
            {
                throw new ArgumentException("The SAML response signature failed to verify.");
            }

            // Deserialize the XML.
            samlResponse = new SAMLResponse(samlResponseXml);

            Trace.Write("SP", "Received SAML response");
        }
Exemple #7
0
        internal static bool ExpandElement(ElementNavigator nav, ArtifactResolver resolver)
        {
            if (resolver == null)
            {
                throw Error.ArgumentNull("source");
            }
            if (nav.Current == null)
            {
                throw Error.ArgumentNull("Navigator is not positioned on an element");
            }

            if (nav.HasChildren)
            {
                return(true);                     // already has children, we're not doing anything extra
            }
            var defn = nav.Current;

            if (!String.IsNullOrEmpty(defn.NameReference))
            {
                var sourceNav = new ElementNavigator(nav);
                var success   = sourceNav.JumpToNameReference(defn.NameReference);

                if (!success)
                {
                    throw Error.InvalidOperation("Trying to navigate down a node that has a nameReference of '{0}', which cannot be found in the StructureDefinition".FormatWith(defn.NameReference));
                }

                nav.CopyChildren(sourceNav);
            }
            else if (defn.Type != null && defn.Type.Count > 0)
            {
                if (defn.Type.Count > 1)
                {
                    throw new NotSupportedException("Element at path {0} has a choice of types, cannot expand".FormatWith(nav.Path));
                }
                else
                {
                    var coreType = resolver.GetStructureDefinitionForCoreType(defn.Type[0].Code.ToString());

                    if (coreType == null)
                    {
                        throw Error.NotSupported("Trying to navigate down a node that has a declared base type of '{0}', which is unknown".FormatWith(defn.Type[0].Code));
                    }
                    if (coreType.Snapshot == null)
                    {
                        throw Error.NotSupported("Found definition of base type '{0}', but is does not contain a snapshot representation".FormatWith(defn.Type[0].Code));
                    }

                    generateBaseElements(coreType.Snapshot.Element);
                    var sourceNav = new ElementNavigator(coreType.Snapshot.Element);
                    sourceNav.MoveToFirstChild();
                    nav.CopyChildren(sourceNav);
                }
            }

            return(true);
        }
Exemple #8
0
        public static void ExpandProfileFile(string inputfile, string outputfile)
        {
            var source   = new CachedArtifactSource(ArtifactResolver.CreateOffline());
            var expander = new ProfileExpander(source);

            string xml  = File.ReadAllText(inputfile);
            var    diff = (Profile)FhirParser.ParseResourceFromXml(xml);

            expander.Expand(diff);
            xml = FhirSerializer.SerializeResourceToXml(diff);
            File.WriteAllText(outputfile, xml);
        }
Exemple #9
0
        public static void ExpandProfileFile(string inputfile, string outputfile)
        {
            var source = ArtifactResolver.CreateOffline();
            //var source = new CachedArtifactSource(ArtifactResolver.CreateOffline());
            var expander = new SnapshotGenerator(source);

            string xml  = File.ReadAllText(inputfile);
            var    diff = (new FhirXmlParser()).Parse <StructureDefinition>(xml);

            expander.Generate(diff);
            xml = FhirSerializer.SerializeResourceToXml(diff);
            File.WriteAllText(outputfile, xml);
        }
Exemple #10
0
 public SnapshotGenerator(ArtifactResolver resolver, SnapshotGeneratorSettings settings)
 {
     if (resolver == null)
     {
         throw Error.ArgumentNull("resolver");
     }
     if (settings == null)
     {
         throw Error.ArgumentNull("settings");
     }
     _resolver = resolver;
     _settings = settings;
 }
Exemple #11
0
        public static SpecificationProvider CreateOffline(params IArtifactSource[] sources)
        {
            ArtifactResolver resolver = new ArtifactResolver();

            foreach (IArtifactSource s in sources)
            {
                resolver.AddSource(s);
            }
            resolver.AddSource(new CoreZipArtifactSource());
            resolver.AddSource(new FileArtifactSource());

            IArtifactSource cache = new CachedArtifactSource(resolver);

            return(new SpecificationProvider(cache));
        }
Exemple #12
0
        public void TestExpandChild()
        {
            var loader     = new StructureLoader(ArtifactResolver.CreateDefault());
            var profStruct = loader.LocateStructure(new Uri("http://hl7.org/fhir/Profile/Profile"), new Code("Profile"));

            var nav = new ElementNavigator(profStruct.Snapshot);

            nav.JumpToFirst("Profile.telecom");
            Assert.IsTrue(nav.ExpandElement(loader));
            Assert.IsTrue(nav.MoveToChild("period"));

            nav.JumpToFirst("Profile.structure.differential");
            Assert.IsTrue(nav.ExpandElement(loader));
            Assert.IsTrue(nav.MoveToChild("element"));
        }
        public void TestExpandChild()
        {
            var loader     = new StructureLoader(ArtifactResolver.CreateDefault());
            var profStruct = loader.Locate(new Uri("http://hl7.org/fhir/Profile/Profile"), new Code("Profile"));

            var nav = new ElementNavigator(profStruct);

            nav.JumpToFirst("Profile.telecom");
            Assert.IsTrue(nav.ExpandElement(loader));
            Assert.IsTrue(nav.MoveToChild("period"));

            nav.JumpToFirst("Profile.extensionDefn.definition");
            Assert.IsTrue(nav.ExpandElement(loader));
            Assert.IsTrue(nav.MoveToChild("max"));
        }
Exemple #14
0
        public void GenerateNorwegianSnapshots()
        {
            var mySource  = new FileDirectoryArtifactSource(@"C:\Git\helsenord.ig\Source\Chapter.3.Package", includeSubdirectories: false);
            var stdSource = ZipArtifactSource.CreateValidationSource();
            var resolver  = new ArtifactResolver(new MultiArtifactSource(mySource, stdSource));

            var sources = new[] { "noHealthcareService", "noHealthcareServiceLocation", "noOrganization", "noPractitioner", "acronym" };

            var generator = new SnapshotGenerator(resolver, markChanges: false);

            foreach (var source in sources)
            {
                var sd = resolver.GetStructureDefinition("http://hl7.no/fhir/StructureDefinition/" + source);
                Assert.IsNotNull(sd, "Cannot find SD " + sd.Url);

                generator.Generate(sd);
                File.WriteAllText(@"C:\Git\helsenord.ig\Source\Chapter.3.Package\structure." + source + ".xml", FhirSerializer.SerializeResourceToXml(sd));
            }
        }
        private void forDoc()
        {
            FhirXmlParser parser = new FhirXmlParser(new ParserSettings {
                AcceptUnknownMembers = true
            });
            IFhirReader xmlWithPatientData = null;
            var         patient            = parser.Parse <Patient>(xmlWithPatientData);

            // -----

            ArtifactResolver source = ArtifactResolver.CreateCachedDefault();
            var settings            = new SnapshotGeneratorSettings {
                IgnoreMissingTypeProfiles = true
            };
            StructureDefinition profile = null;

            var generator = new SnapshotGenerator(source, _settings);

            generator.Generate(profile);
        }
        private static void generateSnapshotAndCompare(StructureDefinition original, ArtifactResolver source)
        {
            var generator = new SnapshotGenerator(source, markChanges: false);

            var expanded = (StructureDefinition)original.DeepCopy();

            Assert.IsTrue(original.IsExactly(expanded));

            generator.Generate(expanded);

            var areEqual = original.IsExactly(expanded);

            if (!areEqual)
            {
                File.WriteAllText("c:\\temp\\snapshotgen-source.xml", FhirSerializer.SerializeResourceToXml(original));
                File.WriteAllText("c:\\temp\\snapshotgen-dest.xml", FhirSerializer.SerializeResourceToXml(expanded));
            }

            Assert.IsTrue(areEqual);
        }
        private void generateSnapshotAndCompare(StructureDefinition original, ArtifactResolver source)
        {
            // var generator = new SnapshotGenerator(source, markChanges: false);
            var generator = new SnapshotGenerator(source, _settings);

            var expanded = (StructureDefinition)original.DeepCopy();

            Assert.IsTrue(original.IsExactly(expanded));

            generator.Generate(expanded);

            var areEqual = original.IsExactly(expanded);

            if (!areEqual)
            {
                var tempPath = Path.GetTempPath();
                File.WriteAllText(Path.Combine(tempPath, "snapshotgen-source.xml"), FhirSerializer.SerializeResourceToXml(original));
                File.WriteAllText(Path.Combine(tempPath, "snapshotgen-dest.xml"), FhirSerializer.SerializeResourceToXml(expanded));
            }

            Assert.IsTrue(areEqual);
        }
        public void RetrieveArtifactMulti()
        {
            var resolver = ArtifactResolver.CreateDefault();

            resolver.Prepare();

            var vs = resolver.ReadResourceArtifact(new Uri("http://hl7.org/fhir/v2/vs/0292"));

            Assert.IsNotNull(vs);
            Assert.IsTrue(vs is ValueSet);

            using (var a = resolver.ReadContentArtifact("patient.sch"))
            {
                Assert.IsNotNull(a);
            }

            var artifact = resolver.ReadResourceArtifact(new Uri("http://fhir.healthintersections.com.au/open/Profile/alert"));

            Assert.IsNotNull(artifact);
            Assert.IsTrue(artifact is Profile);
            Assert.AreEqual("alert", ((Profile)artifact).Name);
        }
Exemple #19
0
 internal ProfileKnowledgeProvider(string baseUrl)
 {
     _loader  = new StructureLoader(ArtifactResolver.CreateCachedDefault());
     _baseUrl = baseUrl;
 }
 internal ProfileKnowledgeProvider(string baseName, string imageOutputDirectory)
 {
     this.baseName        = baseName;
     _loader              = new StructureLoader(ArtifactResolver.CreateCachedDefault());
     ImageOutputDirectory = imageOutputDirectory;
 }
Exemple #21
0
 public ProfileExpander()
 {
     _loader = new StructureLoader(new CachedArtifactSource(ArtifactResolver.CreateDefault()));
 }
Exemple #22
0
 public SnapshotGenerator(ArtifactResolver resolver, bool markChanges = false)
 {
     _resolver    = resolver;
     _markChanges = markChanges;
 }
Exemple #23
0
        public static SpecificationProvider CreateDefault()
        {
            IArtifactSource source = ArtifactResolver.CreateCachedDefault();

            return(new SpecificationProvider(source));
        }
        // Receive the authentication request from the service provider.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Determine the service provider to identity provider binding type.
            // We use a query string parameter rather than having separate endpoints per binding.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            // Receive the authentication request.
            XmlElement authnRequestXml = null;

            switch (bindingType)
            {
            case SAMLIdentifiers.BindingURIs.HTTPRedirect:
                bool             signed          = false;
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPPost:
                IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                break;

            case SAMLIdentifiers.BindingURIs.HTTPArtifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                string spArtifactResponderURL = WebConfigurationManager.AppSettings["spArtifactResponderURL"];

                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                authnRequestXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Invalid service provider to identity provider binding");
            }

            // If using HTTP redirect the message isn't signed as the generated query string is too long for most browsers.
            if (bindingType != SAMLIdentifiers.BindingURIs.HTTPRedirect)
            {
                if (SAMLMessageSignature.IsSigned(authnRequestXml))
                {
                    // Verify the request's signature.
                    X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];

                    if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate))
                    {
                        throw new ArgumentException("The authentication request signature failed to verify.");
                    }
                }
            }

            // Deserialize the XML.
            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
Exemple #25
0
        public static OperationOutcome ValidateEntry(ResourceEntry entry)
        {
            OperationOutcome result = new OperationOutcome();

            result.Issue = new List <OperationOutcome.OperationOutcomeIssueComponent>();

            ICollection <ValidationResult> vresults = new List <ValidationResult>();


            // Phase 1, validate against low-level rules built into the FHIR datatypes

            // todo: The API no longer seems to have the FhirValidator class.

            /*
             * (!FhirValidator.TryValidate(entry.Resource, vresults, recurse: true))
             * {
             *  foreach (var vresult in vresults)
             *      result.Issue.Add(createValidationResult("[.NET validation] " + vresult.ErrorMessage, vresult.MemberNames));
             * }
             */

            // Phase 2, validate against the XML schema
            var xml = FhirSerializer.SerializeResourceToXml(entry.Resource);
            var doc = XDocument.Parse(xml);

            doc.Validate(SchemaCollection.ValidationSchemaSet, (source, args) => result.Issue.Add(createValidationResult("[XSD validation] " + args.Message, null)));


            // Phase 3, validate against a profile, if present
            var profileTags = entry.GetAssertedProfiles();

            if (profileTags.Count() == 0)
            {
                // If there's no profile specified, at least compare it to the "base" profile
                string baseProfile = CoreZipArtifactSource.CORE_SPEC_PROFILE_URI_PREFIX + entry.Resource.GetCollectionName();
                profileTags = new Uri[] { new Uri(baseProfile, UriKind.Absolute) };
            }

            var artifactSource = ArtifactResolver.CreateOffline();
            var specProvider   = new SpecificationProvider(artifactSource);

            foreach (var profileTag in profileTags)
            {
                var specBuilder = new SpecificationBuilder(specProvider);
                specBuilder.Add(StructureFactory.PrimitiveTypes());
                specBuilder.Add(StructureFactory.MetaTypes());
                specBuilder.Add(StructureFactory.NonFhirNamespaces());
                specBuilder.Add(profileTag.ToString());
                specBuilder.Expand();

                string path = Directory.GetCurrentDirectory();

                var spec = specBuilder.ToSpecification();
                var nav  = doc.CreateNavigator();
                nav.MoveToFirstChild();

                Report report = spec.Validate(nav);
                var    errors = report.Errors;
                foreach (var error in errors)
                {
                    result.Issue.Add(createValidationResult("[Profile validator] " + error.Message, null));
                }
            }

            if (result.Issue.Count == 0)
            {
                return(null);
            }
            else
            {
                return(result);
            }
        }
Exemple #26
0
        internal static bool expandElement(ElementNavigator nav, ArtifactResolver resolver, SnapshotGeneratorSettings settings)
        {
            if (resolver == null)
            {
                throw Error.ArgumentNull("source");
            }
            if (nav.Current == null)
            {
                throw Error.ArgumentNull("Navigator is not positioned on an element");
            }

            if (nav.HasChildren)
            {
                return(true);                     // already has children, we're not doing anything extra
            }
            var defn = nav.Current;

            if (!String.IsNullOrEmpty(defn.NameReference))
            {
                var sourceNav = new ElementNavigator(nav);
                var success   = sourceNav.JumpToNameReference(defn.NameReference);

                if (!success)
                {
                    throw Error.InvalidOperation("Trying to navigate down a node that has a nameReference of '{0}', which cannot be found in the StructureDefinition".FormatWith(defn.NameReference));
                }

                nav.CopyChildren(sourceNav);
            }
            else if (defn.Type != null && defn.Type.Count > 0)
            {
                if (defn.Type.Count > 1)
                {
                    throw new NotSupportedException("Element at path '{0}' has a choice of types, cannot expand".FormatWith(nav.Path));
                }
                else
                {
                    // [WMR 20160720] Handle custom type profiles (GForge #9791)
                    // var coreType = resolver.GetStructureDefinitionForCoreType(defn.Type[0].Code.Value);
                    var primaryType = defn.Type[0];
                    var typeProfile = primaryType.Profile.FirstOrDefault();
                    StructureDefinition coreType = null;
                    if (!defn.IsExtension() && !defn.IsReference() && !string.IsNullOrEmpty(typeProfile) && settings.ExpandTypeProfiles)
                    {
                        coreType = resolver.GetStructureDefinition(typeProfile);
                        if ((coreType == null || coreType.Snapshot == null) && settings.IgnoreMissingTypeProfiles)
                        {
                            coreType = resolver.GetStructureDefinitionForCoreType(primaryType.Code.Value);
                        }
                    }
                    else
                    {
                        coreType = resolver.GetStructureDefinitionForCoreType(primaryType.Code.Value);
                    }

                    if (coreType == null)
                    {
                        throw Error.NotSupported("Trying to navigate down a node that has a declared base type of '{0}', which is unknown".FormatWith(defn.Type[0].Code));
                    }
                    if (coreType.Snapshot == null)
                    {
                        throw Error.NotSupported("Found definition of base type '{0}', but is does not contain a snapshot representation".FormatWith(defn.Type[0].Code));
                    }

                    generateBaseElements(coreType.Snapshot.Element);
                    var sourceNav = new ElementNavigator(coreType.Snapshot.Element);
                    sourceNav.MoveToFirstChild();
                    nav.CopyChildren(sourceNav);
                }
            }

            return(true);
        }
Exemple #27
0
 public SnapshotGenerator(ArtifactResolver resolver) : this(resolver, SnapshotGeneratorSettings.Default)
 {
 }
Exemple #28
0
        // Receive the authentication request and relay state.
        private void ReceiveAuthnRequest(out AuthnRequest authnRequest, out string relayState)
        {
            // Rather than separate endpoints per binding, we have a single endpoint and use a query string
            // parameter to determine the service provider to identity provider binding type.
            string bindingType = Request.QueryString[bindingQueryParameter];

            Trace.Write("IdP", "Receiving authentication request over binding " + bindingType);

            X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate];
            XmlElement       authnRequestXml = null;

            switch (bindingType)
            {
            case BindingTypes.Redirect:
                bool signed = false;

                IdentityProvider.ReceiveAuthnRequestByHTTPRedirect(Request, out authnRequestXml, out relayState, out signed, x509Certificate.PublicKey.Key);
                break;

            case BindingTypes.Post:
                IdentityProvider.ReceiveAuthnRequestByHTTPPost(Request, out authnRequestXml, out relayState);
                break;

            case BindingTypes.Artifact:
                // Receive the artifact.
                HTTPArtifact httpArtifact = null;

                IdentityProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState);

                // Create an artifact resolve request.
                ArtifactResolve artifactResolve = new ArtifactResolve();
                artifactResolve.Issuer   = new Issuer(CreateAbsoluteURL("~/"));
                artifactResolve.Artifact = new Artifact(httpArtifact.ToString());

                XmlElement artifactResolveXml = artifactResolve.ToXml();

                // Send the artifact resolve request and receive the artifact response.
                XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml);

                ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml);

                // Extract the authentication request from the artifact response.
                authnRequestXml = artifactResponse.SAMLMessage;
                break;

            default:
                throw new ArgumentException("Invalid binding type");
            }

            if (SAMLMessageSignature.IsSigned(authnRequestXml))
            {
                Trace.Write("IdP", "Verifying request signature");

                if (!SAMLMessageSignature.Verify(authnRequestXml, x509Certificate))
                {
                    throw new ArgumentException("The authentication request signature failed to verify.");
                }
            }

            authnRequest = new AuthnRequest(authnRequestXml);

            Trace.Write("IdP", "Received authentication request");
        }
 public void SetupSource()
 {
     source = ArtifactResolver.CreateOffline();
 }
 public void Setup()
 {
     _testSource = new ArtifactResolver(new CachedArtifactSource(new FileDirectoryArtifactSource("TestData/snapshot-test", includeSubdirectories: true)));
 }