Example #1
0
        /// <summary>
        /// Runs the application.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The task.</returns>
        private static async Task Run(Settings settings)
        {
            var certificate = new CertificateResolver()
                              .FromStoreByThumbprint(
                StoreName.My,
                StoreLocation.CurrentUser,
                thumbprint: settings.Thumbprint);

            var containerUriBuilder = new StorageContainerUriBuilder(
                settings.StorageContainerUri,
                settings.SasToken);

            // See https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#storing-your-connection-string
            var connectionString = new StorageConnectionStringBuilder()
                                   .WithBlobEndpoint(settings.BlobEndpoint)
                                   .BuildSasToken(settings.SasToken);

            var storageAccountService = new StorageAccountService();
            var storageAccount        = storageAccountService.GetStorageAccount(connectionString);

            // var status = await storageAccountService.UploadFolder("templates", settings., "foo3");
            await storageAccount.DeleteFolder(settings.ContainerName, "foo3");

            // var tester = new ArmTester(settings.Authority, clientId: settings.ClientId, certificate: certificate);
            // var result = await tester.ValidateResourceGroupDeployment(
            //    subscriptionId: settings.SubscriptionId,
            //    resourceGroupName: settings.ResourceGroupName,
            //    templateLink: containerUriBuilder.WithFile("azuredeploy.json").Build(),
            //    parametersLink: containerUriBuilder.WithFile("azuredeploy.parameters.json").Build());
        }
Example #2
0
        public void CachingVerifyTTL()
        {
            m_resolver = CreateResolver(
                true,   /* caching enabled */
                3,      /* TTL */
                false); /* negative cache */

            string domain = DomainIncubator;
            X509Certificate2Collection source = m_resolver.GetCertificatesForDomain(domain);
            X509Certificate2Collection cached = m_cache.Get(domain);

            VerifyValidCert(source, cached);

            Thread.Sleep(4000);

            // verify its evicted from cache.
            cached = m_cache.Get(domain);
            Assert.Null(cached);

            // now get it served from the cache.
            source = m_resolver.GetCertificatesForDomain(domain);
            cached = m_cache.Get(domain);

            VerifyValidCert(source, cached);
        }
Example #3
0
        public void TestErrorEventHandler()
        {
            ThrowingX509Index throwingIndex = new ThrowingX509Index();
            CacheSettings     cacheSettings = new CacheSettings();

            cacheSettings.Cache = false;

            List <Exception> notifiedErrors = new List <Exception>();
            List <Exception> thrownErrors   = new List <Exception>();
            //
            // Test Notifications are fired
            //
            CertificateResolver resolver = new CertificateResolver(throwingIndex, cacheSettings);

            resolver.Error += (r, e) => notifiedErrors.Add(e);
            MailAddress address = new MailAddress("toby@toby");

            this.TryResolveCerts(resolver, address, thrownErrors);

            Assert.True(notifiedErrors.Count == thrownErrors.Count);
            //
            // Test they are NOT fired
            //
            int countThrownFiredBefore = thrownErrors.Count;

            resolver = new CertificateResolver(throwingIndex, cacheSettings);
            notifiedErrors.Clear();
            thrownErrors.Clear();
            this.TryResolveCerts(resolver, address, thrownErrors);

            Assert.True(notifiedErrors.Count == 0);
            Assert.True(thrownErrors.Count == countThrownFiredBefore);
        }
Example #4
0
        /// <inheritdoc />
        public async Task InitializeAsync()
        {
            this.settings = new SettingsService()
                            .GetFromJson <Settings>("deployment");

            var certificate = new CertificateResolver().FromStoreByThumbprint(
                StoreName.My,
                StoreLocation.CurrentUser,
                this.settings.Thumbprint);

            this.credentials = new AzureCredentialsFactory().FromServicePrincipal(
                this.settings.ClientId,
                certificate,
                this.settings.TenantId,
                AzureEnvironment.AzureGlobalCloud);

            var storageAccountService = new StorageAccountService();

            this.storageAccount = storageAccountService.CreateStorageAccount(
                credentials: this.credentials,
                subscriptionId: this.settings.SubscriptionId,
                resourceGroup: "my-resource-group");

            this.sasToken     = this.storageAccount.CreateContainerSasToken("armtemplates");
            this.remoteFolder = Guid.NewGuid().ToString();

            await this.storageAccount.UploadFolder(
                localFolder : "templates",
                containerName : "armtemplates",
                remoteFolder : this.remoteFolder,
                createContainerIfNotExists : true);
        }
Example #5
0
        public CertificateResolverFacts()
        {
            m_resolver = CreateResolver(true, 60, false); // enable caching, ttl=60secs, disable negative caching

            m_cache = m_resolver.Cache;

            ClearCache();
        }
Example #6
0
        public void TestDomain()
        {
            DummyX509Index      index    = new DummyX509Index();
            CertificateResolver resolver = new CertificateResolver(index, null);

            resolver.GetCertificatesForDomain("redmond.hsgincubator.com");
            Assert.True(index.Log.Count == 1);
            Assert.True(index.Log[0] == "redmond.hsgincubator.com");
        }
Example #7
0
        public void Test()
        {
            DummyX509Index      index    = new DummyX509Index();
            CertificateResolver resolver = new CertificateResolver(index, null);

            resolver.GetCertificates(new MailAddress("*****@*****.**"));
            Assert.True(index.Log.Count == 2);
            Assert.True(index.Log[0] == "*****@*****.**");
            Assert.True(index.Log[1] == "redmond.hsgincubator.com");
        }
Example #8
0
        public void CachingVerifyDisabledNullCacheSettings()
        {
            using (SystemX509Store store = SystemX509Store.OpenExternal())
            {
                m_resolver = new CertificateResolver(store, null);
                m_cache    = m_resolver.Cache;
                string domain = DomainIncubator;
                X509Certificate2Collection source = m_resolver.GetCertificatesForDomain(domain);

                Assert.Null(m_resolver.Cache);
                Assert.True(source.Count > 0);
            }
        }
Example #9
0
        public void CachingVerifyDisabled()
        {
            m_resolver = CreateResolver(
                false,  /* caching disabled */
                0,      /* TTL */
                false); /* negative caching */

            string domain = DomainIncubator;
            X509Certificate2Collection source = m_resolver.GetCertificatesForDomain(domain);
            X509Certificate2Collection cached = m_cache.Get(domain);

            Assert.Null(cached);
            Assert.True(source.Count > 0);
        }
Example #10
0
        /// <summary>
        /// Create a resolver that resolvers anchors from the middle tier
        /// </summary>
        /// <param name="clientSettings">Settings to set up WCF connections to the middle tier</param>
        /// <param name="cacheSettings">Optional: if caching is enabled. Else null</param>
        public ConfigAnchorResolver(ClientSettings clientSettings, CacheSettings cacheSettings)
        {
            if (clientSettings == null)
            {
                throw new ArgumentNullException("clientSettings");
            }

            CacheSettings incomingCacheSettings = new CacheSettings(cacheSettings)
            {
                Name = "AnchorCache.incoming"
            };
            CacheSettings outgoingCacheSettings = new CacheSettings(cacheSettings)
            {
                Name = "AnchorCache.outgoing"
            };

            m_incomingResolver = new CertificateResolver(new AnchorIndex(clientSettings, true), incomingCacheSettings);
            m_outgoingResolver = new CertificateResolver(new AnchorIndex(clientSettings, false), outgoingCacheSettings);
        }
Example #11
0
        /// <summary>
        /// Tuck away settings and create resolvers.
        /// </summary>
        /// <param name="settings"></param>
        public void Initialize(BundleResolverSettings settings)
        {
            m_settings = settings;

            CacheSettings incomingCacheSettings =
                new CacheSettings(m_settings.CacheSettings)
            {
                Name = "BundleCache.incoming"
            };

            CacheSettings outgoingCacheSettings =
                new CacheSettings(m_settings.CacheSettings)
            {
                Name = "BundleCache.outgoing"
            };

            m_incomingResolver =
                new CertificateResolver(new BundleAnchorIndex(m_settings, true), incomingCacheSettings);

            m_outgoingResolver =
                new CertificateResolver(new BundleAnchorIndex(m_settings, false), outgoingCacheSettings);
        }
Example #12
0
 public void CachingCertNotFoundNegativeCache()
 {
     m_resolver = CreateResolver(true, 60, true);
     CachingCertNotFound();
 }
Example #13
0
 public void CachingVerifyFallbackAddressesNegativeCache()
 {
     m_resolver = CreateResolver(true, 60, true);
     CachingVerifyFallbackAddresses();
 }
Example #14
0
        private static async Task <IOnDemandClientChannel> EstablishChannelAsync(ConnectionInformation connectionInformation, CancellationToken cancellationToken)
        {
            var certificate = CertificateResolver.GetCertificateFromThumbprint(connectionInformation.CertificateThumbprint);

            ITransport transportFactory() => CreateTransportForUri(connectionInformation.ServerUri, certificate);

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transportFactory, connectionInformation.ServerUri)
                          .AddBuiltHandler((channel, handlerCancellationToken) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(Task.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .WithEncryption(SessionEncryption.None)
                          .WithInstance(connectionInformation.Instance)
                          .WithIdentity(connectionInformation.Identity)
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                if (connectionInformation.Presence != null)
                {
                    await channel.SetResourceAsync(
                        new LimeUri(UriTemplates.PRESENCE),
                        connectionInformation.Presence,
                        handlerCancellationToken);
                }
            })
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                if (connectionInformation.Receipt != null)
                {
                    await channel.SetResourceAsync(
                        new LimeUri(UriTemplates.RECEIPT),
                        connectionInformation.Receipt,
                        handlerCancellationToken);
                }
            });

            if (connectionInformation.Password != null)
            {
                builder = builder.WithPlainAuthentication(connectionInformation.Password);
            }
            else if (connectionInformation.Key != null)
            {
                builder = builder.WithKeyAuthentication(connectionInformation.Key);
            }
            else if (connectionInformation.Token != null)
            {
                builder = builder.WithExternalAuthentication(connectionInformation.Token, connectionInformation.Issuer);
            }
            else if (connectionInformation.CertificateThumbprint != null)
            {
                builder = builder
                          .WithTransportAuthentication(connectionInformation.DomainRole)
                          .WithEncryption(SessionEncryption.TLS);
            }

            var clientChannel = new OnDemandClientChannel(builder);

            clientChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                WriteError("Could not establish the session: {0}", information.Exception.Message);
                return(TaskUtil.FalseCompletedTask);
            });

            var channelListener = new ChannelListener(message =>
            {
                WriteInfo("Message with id '{0}' received from '{1}': {2}", message.Id, message.GetSender(), message.Content);
                return(TaskUtil.TrueCompletedTask);
            },
                                                      notification =>
            {
                WriteInfo("Notification with id {0} received from '{1}' - Event: {2}", notification.Id, notification.GetSender(), notification.Event);
                return(TaskUtil.TrueCompletedTask);
            },
                                                      command =>
            {
                WriteInfo("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id, command.GetSender(), command.Method, command.Uri);
                return(TaskUtil.TrueCompletedTask);
            });


            await clientChannel.EstablishAsync(cancellationToken);

            channelListener.Start(clientChannel);

            return(clientChannel);
        }