Ejemplo n.º 1
0
        public async Task RoundtripTest()
        {
            // Arrange
            var underlyingCredentialsCache = new NullCredentialsCache();
            var credentialsCache           = new CredentialsCache(underlyingCredentialsCache);
            var identity1 = Mock.Of <IIdentity>(i => i.Id == "d1");
            var identity2 = Mock.Of <IIdentity>(i => i.Id == "d2/m2");
            var creds1    = Mock.Of <ITokenCredentials>(c => c.Identity == identity1);
            var creds2    = Mock.Of <IClientCredentials>(c => c.Identity == identity2);

            // Act
            await credentialsCache.Add(creds1);

            await credentialsCache.Add(creds2);

            Option <IClientCredentials> receivedClientCredentials1 = await credentialsCache.Get(identity1);

            Option <IClientCredentials> receivedClientCredentials2 = await credentialsCache.Get(identity2);

            // Assert
            Assert.True(receivedClientCredentials1.HasValue);
            Assert.True(receivedClientCredentials2.HasValue);
            Assert.Equal(creds1, receivedClientCredentials1.OrDefault());
            Assert.Equal(creds2, receivedClientCredentials2.OrDefault());
        }
Ejemplo n.º 2
0
        public async Task GetCloudProxyTest()
        {
            // Arrange
            string edgeDeviceId       = "edgeDevice";
            string module1Id          = "module1";
            string iotHub             = "foo.azure-devices.net";
            string token              = TokenHelper.CreateSasToken(iotHub);
            var    module1Credentials = new TokenCredentials(new ModuleIdentity(iotHub, edgeDeviceId, module1Id), token, DummyProductInfo, true);

            IClient client1 = GetDeviceClient();
            IClient client2 = GetDeviceClient();
            var     messageConverterProvider = Mock.Of <IMessageConverterProvider>();
            var     deviceClientProvider     = new Mock <IClientProvider>();

            deviceClientProvider.SetupSequence(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>()))
            .Returns(client1)
            .Returns(client2);

            ICredentialsCache credentialsCache = new CredentialsCache(new NullCredentialsCache());
            await credentialsCache.Add(module1Credentials);

            var productInfoStore        = Mock.Of <IProductInfoStore>();
            var cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                deviceClientProvider.Object,
                Option.None <UpstreamProtocol>(),
                Mock.Of <ITokenProvider>(),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                new ModuleIdentity(iotHub, edgeDeviceId, "$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                Option.None <IWebProxy>(),
                productInfoStore);

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, GetIdentityProvider());

            // Act
            Option <ICloudProxy> getCloudProxyTask = await connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            // Assert
            Assert.True(getCloudProxyTask.HasValue);
            Assert.True(getCloudProxyTask.OrDefault().IsActive);

            // Act
            await getCloudProxyTask.OrDefault().CloseAsync();

            Option <ICloudProxy> newCloudProxyTask1 = await connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            // Assert
            Assert.True(newCloudProxyTask1.HasValue);
            Assert.NotEqual(newCloudProxyTask1.OrDefault(), getCloudProxyTask.OrDefault());

            Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Once);
            Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Never);
        }
Ejemplo n.º 3
0
        internal Credentials GetCredentials(Uri uri, bool cacheAllowed, bool hidePasswordField)
        {
            // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once
            // (e.g. on startup). So the user only needs to enter credentials once for the same host.
            lock (this)
            {
                string userName = null;
                string password = null;
                if (uri.UserInfo != null && uri.UserInfo.Length > 0)
                {
                    string[] split = uri.UserInfo.Split(new char[] { ':' });
                    if (split.Length > 0)
                    {
                        userName = split[0];
                    }

                    if (split.Length > 1)
                    {
                        password = split[1];
                    }
                }

                IList <string> usersForHost = CredentialsCache.GetUsersForHost(uri.Host);
                if (userName == null && cacheAllowed)
                {
                    if (usersForHost.Count == 1)
                    {
                        userName = usersForHost[0];
                    }
                }

                if (userName != null && password == null && cacheAllowed)
                {
                    Credentials cred = CredentialsCache.GetCredentials(uri.Host, userName);
                    if (cred != null)
                    {
                        return(cred);
                    }
                }

                if (userName == null || password == null)
                {
                    LoginDialog dlg = new LoginDialog(uri.Host, usersForHost, hidePasswordField);
                    dlg.UserName = userName;
                    if (DialogResult.OK == dlg.ShowDialog())
                    {
                        password = dlg.Password;
                        userName = dlg.UserName;
                    }

                    dlg.Dispose();
                }

                Credentials credentials = new Credentials(uri.Host, userName, password);
                CredentialsCache.Add(credentials);
                return(credentials);
            }
        }
Ejemplo n.º 4
0
        public async Task GetMultipleCloudProxiesTest()
        {
            // Arrange
            string  edgeDeviceId             = "edgeDevice";
            string  module1Id                = "module1";
            string  token                    = TokenHelper.CreateSasToken(IotHubHostName);
            var     module1Credentials       = new TokenCredentials(new ModuleIdentity(IotHubHostName, edgeDeviceId, module1Id), token, DummyProductInfo, true);
            IClient client1                  = GetDeviceClient();
            IClient client2                  = GetDeviceClient();
            var     messageConverterProvider = Mock.Of <IMessageConverterProvider>();
            var     deviceClientProvider     = new Mock <IClientProvider>();

            deviceClientProvider.SetupSequence(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>()))
            .Returns(client1)
            .Returns(client2);

            ICredentialsCache credentialsCache = new CredentialsCache(new NullCredentialsCache());
            await credentialsCache.Add(module1Credentials);

            var cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                deviceClientProvider.Object,
                Option.None <UpstreamProtocol>(),
                Mock.Of <ITokenProvider>(),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                new ModuleIdentity(IotHubHostName, edgeDeviceId, "$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20));

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, GetIdentityProvider());

            // Act
            Task <Option <ICloudProxy> > getCloudProxyTask1 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask2 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask3 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask4 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            Option <ICloudProxy>[] cloudProxies = await Task.WhenAll(getCloudProxyTask1, getCloudProxyTask2, getCloudProxyTask3, getCloudProxyTask4);

            // Assert
            Assert.True(cloudProxies[0].HasValue);
            Assert.True(cloudProxies[1].HasValue);
            Assert.True(cloudProxies[2].HasValue);
            Assert.True(cloudProxies[3].HasValue);
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[1].OrDefault());
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[2].OrDefault());
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[3].OrDefault());

            // Act
            await cloudProxies[0].OrDefault().CloseAsync();
            Option <ICloudProxy> newCloudProxyTask1 = await connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            // Assert
            Assert.True(newCloudProxyTask1.HasValue);
            Assert.NotEqual(newCloudProxyTask1.OrDefault(), cloudProxies[0].OrDefault());
            Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Once);
            Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Never);
        }
Ejemplo n.º 5
0
        public async Task UpdateDeviceConnectionTest()
        {
            int receivedConnectedStatusCount = 0;
            ConnectionStatusChangesHandler connectionStatusChangesHandler = null;
            string hostname = "dummy.azure-devices.net";
            string deviceId = "device1";

            IClientCredentials GetClientCredentials(TimeSpan tokenExpiryDuration)
            {
                string token    = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds));
                var    identity = new DeviceIdentity(hostname, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, false));
            }

            IDeviceProxy GetMockDeviceProxy()
            {
                var deviceProxyMock1 = new Mock <IDeviceProxy>();

                deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true);
                deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>()))
                .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false))
                .Returns(Task.CompletedTask);
                return(deviceProxyMock1.Object);
            }

            IClient GetMockedDeviceClient()
            {
                var deviceClient = new Mock <IClient>();

                deviceClient.SetupGet(dc => dc.IsActive).Returns(true);
                deviceClient.Setup(dc => dc.CloseAsync())
                .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false))
                .Returns(Task.FromResult(true));

                deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>()))
                .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c);

                deviceClient.Setup(dc => dc.OpenAsync())
                .Callback(() =>
                {
                    int currentCount = receivedConnectedStatusCount;
                    Assert.NotNull(connectionStatusChangesHandler);
                    connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                    Assert.Equal(receivedConnectedStatusCount, currentCount);
                })
                .Returns(Task.CompletedTask);
                return(deviceClient.Object);
            }

            IAuthenticationMethod authenticationMethod = null;
            var deviceClientProvider = new Mock <IClientProvider>();

            deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <IAuthenticationMethod>(), It.IsAny <ITransportSettings[]>()))
            .Callback <IIdentity, IAuthenticationMethod, ITransportSettings[]>((s, a, t) => authenticationMethod = a)
            .Returns(() => GetMockedDeviceClient());

            var messageConverterProvider = Mock.Of <IMessageConverterProvider>();

            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60), true);

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var credentialsCache = new CredentialsCache(new NullCredentialsCache());
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache);

            IClientCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10));
            await credentialsCache.Add(clientCredentials1);

            Try <ICloudProxy> cloudProxyTry1 = await connectionManager.CreateCloudConnectionAsync(clientCredentials1);

            Assert.True(cloudProxyTry1.Success);

            IDeviceProxy deviceProxy1 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1);

            await Task.Delay(TimeSpan.FromSeconds(10));

            Assert.NotNull(authenticationMethod);
            var deviceTokenRefresher = authenticationMethod as DeviceAuthenticationWithTokenRefresh;

            Assert.NotNull(deviceTokenRefresher);
            Task <string> tokenGetter = deviceTokenRefresher.GetTokenAsync(hostname);

            Assert.False(tokenGetter.IsCompleted);

            IClientCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2));
            await credentialsCache.Add(clientCredentials2);

            Try <ICloudProxy> cloudProxyTry2 = await connectionManager.CreateCloudConnectionAsync(clientCredentials2);

            Assert.True(cloudProxyTry2.Success);

            IDeviceProxy deviceProxy2 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Assert.False(tokenGetter.IsCompleted);

            IClientCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10));
            await credentialsCache.Add(clientCredentials3);

            Try <ICloudProxy> cloudProxyTry3 = await connectionManager.CreateCloudConnectionAsync(clientCredentials3);

            Assert.True(cloudProxyTry3.Success);

            IDeviceProxy deviceProxy3 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3);

            await Task.Delay(TimeSpan.FromSeconds(23));

            Assert.True(tokenGetter.IsCompleted);
            Assert.Equal(tokenGetter.Result, (clientCredentials3 as ITokenCredentials)?.Token);
        }