Beispiel #1
0
 public static BlobServiceClient GetServiceClient_BlobServiceSas_Container(
     string containerName,
     SharedKeyCredentials sharedKeyCredentials = default,
     SasQueryParameters sasCredentials         = default)
 => new BlobServiceClient(
     new Uri($"{TestConfigurations.DefaultTargetTenant.BlobServiceEndpoint}?{sasCredentials ?? GetNewBlobServiceSasCredentialsContainer(containerName: containerName, sharedKeyCredentials: sharedKeyCredentials ?? GetNewSharedKeyCredentials())}"),
     GetOptions <BlobConnectionOptions>());
Beispiel #2
0
        /// <summary>
        /// Use an account's <see cref="SharedKeyCredentials"/> to sign this
        /// shared access signature values to produce the proper SAS query
        /// parameters for authenticating requests.
        /// </summary>
        /// <param name="sharedKeyCredential">
        /// The storage account's <see cref="SharedKeyCredentials"/>.
        /// </param>
        /// <returns>
        /// The <see cref="SasQueryParameters"/> used for authenticating requests.
        /// </returns>
        public SasQueryParameters ToSasQueryParameters(SharedKeyCredentials sharedKeyCredential)
        {
            sharedKeyCredential = sharedKeyCredential ?? throw Errors.ArgumentNull(nameof(sharedKeyCredential));

            string resource;

            if (String.IsNullOrEmpty(this.FilePath))
            {
                // Make sure the permission characters are in the correct order
                this.Permissions = ShareSasPermissions.Parse(this.Permissions).ToString();
                resource         = Constants.Sas.Resource.Share;
            }
            else
            {
                // Make sure the permission characters are in the correct order
                this.Permissions = FileSasPermissions.Parse(this.Permissions).ToString();
                resource         = Constants.Sas.Resource.File;
            }

            if (String.IsNullOrEmpty(this.Version))
            {
                this.Version = SasQueryParameters.SasVersion;
            }

            var startTime  = SasQueryParameters.FormatTimesForSasSigning(this.StartTime);
            var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime);

            // String to sign: http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx
            var stringToSign = String.Join("\n",
                                           this.Permissions,
                                           startTime,
                                           expiryTime,
                                           GetCanonicalName(sharedKeyCredential.AccountName, this.ShareName ?? String.Empty, this.FilePath ?? String.Empty),
                                           this.Identifier,
                                           this.IPRange.ToString(),
                                           this.Protocol.ToString(),
                                           this.Version,
                                           this.CacheControl,
                                           this.ContentDisposition,
                                           this.ContentEncoding,
                                           this.ContentLanguage,
                                           this.ContentType);

            var signature = sharedKeyCredential.ComputeHMACSHA256(stringToSign);

            var p = new SasQueryParameters(
                version: this.Version,
                services: null,
                resourceTypes: null,
                protocol: this.Protocol,
                startTime: this.StartTime,
                expiryTime: this.ExpiryTime,
                ipRange: this.IPRange,
                identifier: this.Identifier,
                resource: resource,
                permissions: this.Permissions,
                signature: signature);

            return(p);
        }
 public BlobServiceClient GetServiceClient_AccountSas(
     SharedKeyCredentials sharedKeyCredentials = default,
     SasQueryParameters sasCredentials         = default)
 => this.InstrumentClient(
     new BlobServiceClient(
         new Uri($"{TestConfigurations.DefaultTargetTenant.BlobServiceEndpoint}?{sasCredentials ?? this.GetNewAccountSasCredentials(sharedKeyCredentials ?? this.GetNewSharedKeyCredentials())}"),
         this.GetOptions()));
        public async Task ConnectWithInvalidConnectionStringTest()
        {
            var edgeHub = Mock.Of <IEdgeHub>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(MessageConverterProvider, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60));

            cloudConnectionProvider.BindEdgeHub(edgeHub);
            var deviceIdentity1           = Mock.Of <IIdentity>(m => m.Id == "device1");
            var clientCredentials1        = new SharedKeyCredentials(deviceIdentity1, "dummyConnStr", null);
            Try <ICloudConnection> result = await cloudConnectionProvider.Connect(clientCredentials1, null);

            Assert.False(result.Success);
            Assert.IsType <AggregateException>(result.Exception);

            string deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("device1ConnStrKey");

            // Change the connection string key, deliberately.
            char updatedLastChar = (char)(deviceConnectionString[deviceConnectionString.Length - 1] + 1);

            deviceConnectionString = deviceConnectionString.Substring(0, deviceConnectionString.Length - 1) + updatedLastChar;
            var deviceIdentity2               = Mock.Of <IIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials2            = new SharedKeyCredentials(deviceIdentity2, deviceConnectionString, null);
            Try <ICloudConnection> cloudProxy = cloudConnectionProvider.Connect(clientCredentials2, null).Result;

            Assert.False(cloudProxy.Success);
        }
        public void DefaultStorageAccountWithHttps()
        {
            var cred = new SharedKeyCredentials(TestConfigurations.DefaultTargetTenant.AccountName, TestConfigurations.DefaultTargetTenant.AccountKey);
            var conn = new StorageConnectionString(cred, true);

            Assert.AreEqual(conn.BlobEndpoint,
                            new Uri(String.Format("https://{0}.blob.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.QueueEndpoint,
                            new Uri(String.Format("https://{0}.queue.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.TableEndpoint,
                            new Uri(String.Format("https://{0}.table.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.FileEndpoint,
                            new Uri(String.Format("https://{0}.file.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.BlobStorageUri.SecondaryUri,
                            new Uri(String.Format("https://{0}-secondary.blob.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.QueueStorageUri.SecondaryUri,
                            new Uri(String.Format("https://{0}-secondary.queue.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.TableStorageUri.SecondaryUri,
                            new Uri(String.Format("https://{0}-secondary.table.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));
            Assert.AreEqual(conn.FileStorageUri.SecondaryUri,
                            new Uri(String.Format("https://{0}-secondary.file.core.windows.net", TestConfigurations.DefaultTargetTenant.AccountName)));

            var storageConnectionStringToStringWithSecrets = conn.ToString(true);
            var testAccount = StorageConnectionString.Parse(storageConnectionStringToStringWithSecrets);

            this.AccountsAreEqual(testAccount, conn);
        }
Beispiel #6
0
        async Task <ICloudProxy> GetCloudProxyWithConnectionStringKey(string connectionStringConfigKey, IEdgeHub edgeHub)
        {
            const int ConnectionPoolSize     = 10;
            string    deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey(connectionStringConfigKey);

            var converters = new MessageConverterProvider(new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Client.Message), new DeviceClientMessageConverter() },
                { typeof(Twin), new TwinMessageConverter() },
                { typeof(TwinCollection), new TwinCollectionMessageConverter() }
            });

            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(converters, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), TimeSpan.FromMinutes(60), true);

            cloudConnectionProvider.BindEdgeHub(edgeHub);
            var deviceIdentity    = Mock.Of <IDeviceIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials = new SharedKeyCredentials(deviceIdentity, deviceConnectionString, string.Empty);

            Try <ICloudConnection> cloudConnection = await cloudConnectionProvider.Connect(clientCredentials, (_, __) => { });

            Assert.True(cloudConnection.Success);
            Assert.True(cloudConnection.Value.IsActive);
            Assert.True(cloudConnection.Value.CloudProxy.HasValue);
            return(cloudConnection.Value.CloudProxy.OrDefault());
        }
 public BlobServiceClient GetServiceClient_BlobServiceSas_Blob(
     string containerName,
     string blobName,
     SharedKeyCredentials sharedKeyCredentials = default,
     SasQueryParameters sasCredentials         = default)
 => this.InstrumentClient(
     new BlobServiceClient(
         new Uri($"{TestConfigurations.DefaultTargetTenant.BlobServiceEndpoint}?{sasCredentials ?? this.GetNewBlobServiceSasCredentialsBlob(containerName: containerName, blobName: blobName, sharedKeyCredentials: sharedKeyCredentials ?? this.GetNewSharedKeyCredentials())}"),
         this.GetOptions()));
Beispiel #8
0
        public async Task TestAddRemoveDeviceConnectionTest()
        {
            string deviceId = "id1";

            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.FromResult(true));

            var deviceCredentials = new SharedKeyCredentials(new DeviceIdentity("iotHub", deviceId), "dummyConnStr", "abc");

            var edgeHub = new Mock <IEdgeHub>();

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

            deviceClientProvider.Setup(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <string>(), It.IsAny <Client.ITransportSettings[]>()))
            .Returns(client);

            var cloudConnectionProvider          = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>());
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider);
            Try <ICloudProxy>  cloudProxyTry     = await connectionManager.CreateCloudConnectionAsync(deviceCredentials);

            Assert.True(cloudProxyTry.Success);
            var deviceListener = new DeviceMessageHandler(deviceCredentials.Identity, edgeHub.Object, connectionManager);

            Option <ICloudProxy> cloudProxy = connectionManager.GetCloudConnection(deviceId);

            Assert.True(cloudProxy.HasValue);
            Assert.True(cloudProxy.OrDefault().IsActive);

            deviceListener.BindDeviceProxy(deviceProxyMock1.Object);

            Option <IDeviceProxy> deviceProxy = connectionManager.GetDeviceConnection(deviceId);

            Assert.True(deviceProxy.HasValue);
            Assert.True(deviceProxy.OrDefault().IsActive);
            Assert.True(deviceProxyMock1.Object.IsActive);

            cloudProxy = connectionManager.GetCloudConnection(deviceId);
            Assert.True(cloudProxy.HasValue);
            Assert.True(cloudProxy.OrDefault().IsActive);

            await deviceListener.CloseAsync();

            deviceProxy = connectionManager.GetDeviceConnection(deviceId);
            Assert.False(deviceProxy.HasValue);
            Assert.False(deviceProxyMock1.Object.IsActive);

            cloudProxy = connectionManager.GetCloudConnection(deviceId);
            Assert.False(cloudProxy.HasValue);
            Assert.False(client.IsActive);
        }
Beispiel #9
0
        public void Ctor_ConnectionString()
        {
            var accountName = "accountName";
            var accountKey  = Convert.ToBase64String(new byte[] { 0, 1, 2, 3, 4, 5 });

            var credentials            = new SharedKeyCredentials(accountName, accountKey);
            var queueEndpoint          = new Uri("http://127.0.0.1/" + accountName);
            var queueSecondaryEndpoint = new Uri("http://127.0.0.1/" + accountName + "-secondary");

            var connectionString = new StorageConnectionString(credentials, (default, default), (queueEndpoint, queueSecondaryEndpoint), (default, default), (default, default));
        public BlobConnectionOptions GetFaultyBlobConnectionOptions(
            SharedKeyCredentials credentials = null,
            int raiseAt     = default,
            Exception raise = default)
        {
            raise = raise ?? new Exception("Simulated connection fault");
            var options = this.GetOptions(credentials);

            options.AddPolicy(HttpPipelinePosition.PerCall, new FaultyDownloadPipelinePolicy(raiseAt, raise));
            return(options);
        }
Beispiel #11
0
        public static BlobConnectionOptions GetFaultyBlobConnectionOptions(
            SharedKeyCredentials credentials = null,
            int raiseAt     = default,
            Exception raise = default)
        {
            raise = raise ?? new Exception("Simulated connection fault");
            var options = GetOptions <BlobConnectionOptions>(credentials);

            options.PerCallPolicies.Add(new FaultyDownloadPipelinePolicy(raiseAt, raise));
            return(options);
        }
        public async Task ConnectTest()
        {
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(MessageConverterProvider, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>());
            string deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("device1ConnStrKey");

            var deviceIdentity                = Mock.Of <IDeviceIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials             = new SharedKeyCredentials(deviceIdentity, deviceConnectionString, null);
            Try <ICloudConnection> cloudProxy = cloudConnectionProvider.Connect(clientCredentials, null).Result;

            Assert.True(cloudProxy.Success);
            bool result = await cloudProxy.Value.CloseAsync();

            Assert.True(result);
        }
        public SasQueryParameters GetNewQueueServiceSasCredentials(string queueName, SharedKeyCredentials sharedKeyCredentials = default)
        => new QueueSasBuilder
        {
            QueueName   = queueName,
            Protocol    = SasProtocol.None,
            StartTime   = this.Recording.UtcNow.AddHours(-1),
            ExpiryTime  = this.Recording.UtcNow.AddHours(+1),
            Permissions = new QueueAccountSasPermissions {
                Read = true, Update = true, Process = true, Add = true
            }.ToString(),
            IPRange = new IPRange {
                Start = IPAddress.None, End = IPAddress.None
            }
        }

        .ToSasQueryParameters(sharedKeyCredentials ?? this.GetNewSharedKeyCredentials());
Beispiel #14
0
        public async Task CreateCloudProxyTest()
        {
            string edgeDeviceId = "edgeDevice";
            string module1Id    = "module1";

            var module1Credentials = new SharedKeyCredentials(new ModuleIdentity("iotHub", edgeDeviceId, module1Id), "connStr", DummyProductInfo);

            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 <string>(), It.IsAny <Client.ITransportSettings[]>()))
            .Returns(client1)
            .Returns(client2);

            var cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), TimeSpan.FromMinutes(60));

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var credentialsCache = Mock.Of <ICredentialsCache>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, EdgeDeviceId, EdgeModuleId);

            Task <Try <ICloudProxy> > getCloudProxyTask1 = connectionManager.CreateCloudConnectionAsync(module1Credentials);
            Task <Try <ICloudProxy> > getCloudProxyTask2 = connectionManager.CreateCloudConnectionAsync(module1Credentials);

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

            Assert.NotEqual(cloudProxies[0].Value, cloudProxies[1].Value);

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

            ICloudProxy currentCloudProxy = currentCloudProxyId1.OrDefault();
            ICloudProxy cloudProxy1       = cloudProxies[0].Value;
            ICloudProxy cloudProxy2       = cloudProxies[1].Value;

            Assert.True(currentCloudProxy == cloudProxy1 || currentCloudProxy == cloudProxy2);
            if (currentCloudProxy == cloudProxy1)
            {
                Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Once);
                Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Never);
            }
            else
            {
                Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Once);
                Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Never);
            }
        }
Beispiel #15
0
        public async Task CloudConnectionInvalidUpdateTest()
        {
            var messageConverterProvider = Mock.Of <IMessageConverterProvider>();
            var deviceClientProvider     = new Mock <IClientProvider>();

            deviceClientProvider.SetupSequence(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <string>(), It.IsAny <Client.ITransportSettings[]>()))
            .Returns(GetDeviceClient())
            .Throws(new UnauthorizedException("connstr2 is invalid!"))
            .Throws(new UnauthorizedException("connstr2 is invalid!"));

            var cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), TimeSpan.FromMinutes(60));

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var credentialsCache = Mock.Of <ICredentialsCache>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, EdgeDeviceId, EdgeModuleId);

            string deviceConnStr1    = "connstr1";
            var    deviceCredentials = new SharedKeyCredentials(new DeviceIdentity("iotHub", "Device1"), deviceConnStr1, DummyProductInfo);
            var    deviceProxy       = Mock.Of <IDeviceProxy>(d => d.IsActive);

            Try <ICloudProxy> receivedCloudProxy1 = await connectionManager.CreateCloudConnectionAsync(deviceCredentials);

            await connectionManager.AddDeviceConnection(deviceCredentials.Identity, deviceProxy);

            Assert.True(receivedCloudProxy1.Success);
            Assert.NotNull(receivedCloudProxy1.Value);
            Assert.True(receivedCloudProxy1.Value.IsActive);
            Assert.Equal(deviceProxy, connectionManager.GetDeviceConnection(deviceCredentials.Identity.Id).OrDefault());

            string deviceConnStr2 = "connstr2";

            deviceCredentials = new SharedKeyCredentials(new DeviceIdentity("iotHub", "Device1"), deviceConnStr2, DummyProductInfo);

            Try <ICloudProxy> receivedCloudProxy2 = await connectionManager.CreateCloudConnectionAsync(deviceCredentials);

            Assert.False(receivedCloudProxy2.Success);
            Assert.IsType <EdgeHubConnectionException>(receivedCloudProxy2.Exception);
            List <Exception> innerExceptions = (receivedCloudProxy2.Exception.InnerException as AggregateException)?.InnerExceptions.ToList() ?? new List <Exception>();

            Assert.Equal(2, innerExceptions.Count);
            Assert.IsType <UnauthorizedException>(innerExceptions[0]);
            Assert.IsType <UnauthorizedException>(innerExceptions[1]);
            Assert.True(receivedCloudProxy1.Value.IsActive);
            Assert.Equal(deviceProxy, connectionManager.GetDeviceConnection(deviceCredentials.Identity.Id).OrDefault());
        }
Beispiel #16
0
        /// <summary>
        /// Use an account's <see cref="SharedKeyCredentials"/> to sign this
        /// shared access signature values to produce the proper SAS query
        /// parameters for authenticating requests.
        /// </summary>
        /// <param name="sharedKeyCredential">
        /// The storage account's <see cref="SharedKeyCredentials"/>.
        /// </param>
        /// <returns>
        /// The <see cref="SasQueryParameters"/> used for authenticating requests.
        /// </returns>
        public SasQueryParameters ToSasQueryParameters(SharedKeyCredentials sharedKeyCredential)
        {
            sharedKeyCredential = sharedKeyCredential ?? throw new ArgumentNullException(nameof(sharedKeyCredential));

            this.EnsureState();

            var startTime  = SasQueryParameters.FormatTimesForSasSigning(this.StartTime);
            var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime);

            // See http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx
            var stringToSign = String.Join("\n",
                                           this.Permissions,
                                           startTime,
                                           expiryTime,
                                           GetCanonicalName(sharedKeyCredential.AccountName, this.ContainerName ?? String.Empty, this.BlobName ?? String.Empty),
                                           this.Identifier,
                                           this.IPRange.ToString(),
                                           this.Protocol.ToString(),
                                           this.Version,
                                           this.Resource,
                                           this.Snapshot,
                                           this.CacheControl,
                                           this.ContentDisposition,
                                           this.ContentEncoding,
                                           this.ContentLanguage,
                                           this.ContentType);

            var signature = sharedKeyCredential.ComputeHMACSHA256(stringToSign);

            var p = new SasQueryParameters(
                version: this.Version,
                services: null,
                resourceTypes: null,
                protocol: this.Protocol,
                startTime: this.StartTime,
                expiryTime: this.ExpiryTime,
                ipRange: this.IPRange,
                identifier: this.Identifier,
                resource: this.Resource,
                permissions: this.Permissions,
                signature: signature);

            return(p);
        }
Beispiel #17
0
        public async Task CloudConnectionUpdateTest()
        {
            string receivedConnStr          = null;
            var    messageConverterProvider = Mock.Of <IMessageConverterProvider>();
            var    deviceClientProvider     = new Mock <IClientProvider>();

            deviceClientProvider.Setup(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <string>(), It.IsAny <Client.ITransportSettings[]>()))
            .Callback <IIdentity, string, Client.ITransportSettings[]>((i, s, t) => receivedConnStr = s)
            .Returns(() => GetDeviceClient());

            var cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), TimeSpan.FromMinutes(60));

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var credentialsCache = Mock.Of <ICredentialsCache>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, EdgeDeviceId, EdgeModuleId);

            string deviceConnStr1    = "connstr1";
            var    deviceCredentials = new SharedKeyCredentials(new DeviceIdentity("iotHub", "Device1"), deviceConnStr1, DummyProductInfo);
            var    deviceProxy       = Mock.Of <IDeviceProxy>(d => d.IsActive);

            Try <ICloudProxy> receivedCloudProxy1 = await connectionManager.CreateCloudConnectionAsync(deviceCredentials);

            await connectionManager.AddDeviceConnection(deviceCredentials.Identity, deviceProxy);

            Assert.True(receivedCloudProxy1.Success);
            Assert.NotNull(receivedCloudProxy1.Value);
            Assert.True(receivedCloudProxy1.Value.IsActive);
            Assert.Equal(deviceConnStr1, receivedConnStr);
            Assert.Equal(deviceProxy, connectionManager.GetDeviceConnection(deviceCredentials.Identity.Id).OrDefault());

            string deviceConnStr2 = "connstr2";

            deviceCredentials = new SharedKeyCredentials(new DeviceIdentity("iotHub", "Device1"), deviceConnStr2, DummyProductInfo);

            Try <ICloudProxy> receivedCloudProxy2 = await connectionManager.CreateCloudConnectionAsync(deviceCredentials);

            Assert.True(receivedCloudProxy2.Success);
            Assert.NotNull(receivedCloudProxy2.Value);
            Assert.True(receivedCloudProxy2.Value.IsActive);
            Assert.False(receivedCloudProxy1.Value.IsActive);
            Assert.Equal(deviceConnStr2, receivedConnStr);
            Assert.Equal(deviceProxy, connectionManager.GetDeviceConnection(deviceCredentials.Identity.Id).OrDefault());
        }
        public SasQueryParameters GetNewAccountSasCredentials(SharedKeyCredentials sharedKeyCredentials = default)
        => new AccountSasSignatureValues
        {
            Protocol = SasProtocol.None,
            Services = new AccountSasServices {
                Blob = true
            }.ToString(),
            ResourceTypes = new AccountSasResourceTypes {
                Container = true, Object = true
            }.ToString(),
            StartTime = this.Recording.UtcNow.AddHours(-1),
            ExpiryTime = this.Recording.UtcNow.AddHours(+1),
            Permissions = new ContainerSasPermissions {
                Read = true, Add = true, Create = true, Write = true, Delete = true, List = true
            }.ToString(),
            IPRange = new IPRange {
                Start = IPAddress.None, End = IPAddress.None
            }
        }

        .ToSasQueryParameters(sharedKeyCredentials);
Beispiel #19
0
        public static SasQueryParameters GetNewAccountSasCredentials(SharedKeyCredentials sharedKeyCredentials = default)
        => new AccountSasSignatureValues
        {
            Protocol = SasProtocol.None,
            Services = new AccountSasServices {
                Queue = true
            }.ToString(),
            ResourceTypes = new AccountSasResourceTypes {
                Container = true
            }.ToString(),
            StartTime = DateTimeOffset.UtcNow.AddHours(-1),
            ExpiryTime = DateTimeOffset.UtcNow.AddHours(+1),
            Permissions = new QueueAccountSasPermissions {
                Read = true, Write = true, Update = true, Process = true, Add = true, Delete = true, List = true
            }.ToString(),
            IPRange = new IPRange {
                Start = IPAddress.None, End = IPAddress.None
            }
        }

        .ToSasQueryParameters(sharedKeyCredentials);
        public async Task MutipleModulesConnectionTest()
        {
            string iotHubHostName        = "iotHubName";
            string edgeDeviceId          = "edge";
            string edgeDeviceConnStr     = "dummyConnStr";
            var    module1Credentials    = new TokenCredentials(new ModuleIdentity(iotHubHostName, edgeDeviceId, "module1"), "xyz", DummyProductInfo, false);
            var    module2Credentials    = new TokenCredentials(new ModuleIdentity(iotHubHostName, edgeDeviceId, "module2"), "xyz", DummyProductInfo, false);
            var    edgeDeviceCredentials = new SharedKeyCredentials(new DeviceIdentity(iotHubHostName, edgeDeviceId), edgeDeviceConnStr, "abc");
            var    device1Credentials    = new TokenCredentials(new DeviceIdentity(iotHubHostName, edgeDeviceId), "pqr", DummyProductInfo, false);

            var cloudConnectionProvider = Mock.Of <ICloudConnectionProvider>();

            Mock.Get(cloudConnectionProvider)
            .Setup(c => c.Connect(It.IsAny <IClientCredentials>(), It.IsAny <Action <string, CloudConnectionStatus> >()))
            .ReturnsAsync(() => Try.Success(GetCloudConnectionMock()));

            var credentialsManager = Mock.Of <ICredentialsCache>();

            var connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsManager, GetIdentityProvider());
            Try <ICloudProxy> module1CloudProxy = await connectionManager.CreateCloudConnectionAsync(module1Credentials);

            Assert.True(module1CloudProxy.Success);
            Assert.NotNull(module1CloudProxy.Value);

            Try <ICloudProxy> module2CloudProxy = await connectionManager.CreateCloudConnectionAsync(module2Credentials);

            Assert.True(module2CloudProxy.Success);
            Assert.NotEqual(module1CloudProxy.Value, module2CloudProxy.Value);

            Try <ICloudProxy> edgeDeviceCloudProxy = await connectionManager.CreateCloudConnectionAsync(edgeDeviceCredentials);

            Assert.True(edgeDeviceCloudProxy.Success);
            Assert.NotEqual(module1CloudProxy.Value, edgeDeviceCloudProxy.Value);

            Try <ICloudProxy> device1CloudProxy = await connectionManager.CreateCloudConnectionAsync(device1Credentials);

            Assert.True(device1CloudProxy.Success);
            Assert.NotEqual(edgeDeviceCloudProxy.Value, device1CloudProxy.Value);
        }
Beispiel #21
0
        /// <summary>
        /// ToSasQueryParameters uses an account's shared key credential to sign this signature values to produce
        /// the proper SAS query parameters.
        /// </summary>
        /// <param name="sharedKeyCredential">
        /// <see cref="SharedKeyCredentials"/>
        /// </param>
        /// <returns>
        /// <see cref="SasQueryParameters"/>
        /// </returns>
        public SasQueryParameters ToSasQueryParameters(SharedKeyCredentials sharedKeyCredential)
        {
            sharedKeyCredential = sharedKeyCredential ?? throw Errors.ArgumentNull(nameof(sharedKeyCredential));

            this.Permissions = QueueAccountSasPermissions.Parse(this.Permissions).ToString();
            if (String.IsNullOrEmpty(this.Version))
            {
                this.Version = SasQueryParameters.SasVersion;
            }

            var startTime  = SasQueryParameters.FormatTimesForSasSigning(this.StartTime);
            var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime);

            // String to sign: http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx
            var stringToSign = String.Join("\n",
                                           this.Permissions,
                                           startTime,
                                           expiryTime,
                                           GetCanonicalName(sharedKeyCredential.AccountName, this.QueueName ?? String.Empty),
                                           this.Identifier,
                                           this.IPRange.ToString(),
                                           this.Protocol.ToString(),
                                           this.Version);
            var signature = sharedKeyCredential.ComputeHMACSHA256(stringToSign);
            var p         = new SasQueryParameters(
                version: this.Version,
                services: null,
                resourceTypes: null,
                protocol: this.Protocol,
                startTime: this.StartTime,
                expiryTime: this.ExpiryTime,
                ipRange: this.IPRange,
                identifier: this.Identifier,
                resource: null,
                permissions: this.Permissions,
                signature: signature);

            return(p);
        }
        public void StorageCredentialsEmptyKeyValue()
        {
            var accountName = TestConfigurations.DefaultTargetTenant.AccountName;

            _ = TestConfigurations.DefaultTargetTenant.AccountKey;
            var emptyKeyValueAsString    = String.Empty;
            var emptyKeyConnectionString = String.Format(CultureInfo.InvariantCulture, "DefaultEndpointsProtocol=https;AccountName={0};AccountKey=", accountName);

            var credentials1 = new SharedKeyCredentials(accountName, emptyKeyValueAsString);

            var conn1 = new StorageConnectionString(credentials1, true);

            Assert.AreEqual(emptyKeyConnectionString, conn1.ToString(true));
            Assert.IsNotNull(conn1.Credentials);
            Assert.IsInstanceOf(typeof(SharedKeyCredentials), conn1.Credentials);
            Assert.AreEqual(accountName, ((SharedKeyCredentials)conn1.Credentials).AccountName);
            Assert.AreEqual(emptyKeyValueAsString, ((SharedKeyCredentials)conn1.Credentials).ExportBase64EncodedKey());

            var account2 = StorageConnectionString.Parse(emptyKeyConnectionString);

            Assert.AreEqual(emptyKeyConnectionString, account2.ToString(true));
            Assert.IsNotNull(account2.Credentials);
            Assert.IsInstanceOf(typeof(SharedKeyCredentials), account2.Credentials);
            Assert.AreEqual(accountName, ((SharedKeyCredentials)account2.Credentials).AccountName);
            Assert.AreEqual(emptyKeyValueAsString, ((SharedKeyCredentials)account2.Credentials).ExportBase64EncodedKey());

            var isValidAccount3 = StorageConnectionString.TryParse(emptyKeyConnectionString, out var account3);

            Assert.IsTrue(isValidAccount3);
            Assert.IsNotNull(account3);
            Assert.AreEqual(emptyKeyConnectionString, account3.ToString(true));
            Assert.IsNotNull(account3.Credentials);
            Assert.IsInstanceOf(typeof(SharedKeyCredentials), account3.Credentials);
            Assert.AreEqual(accountName, ((SharedKeyCredentials)account3.Credentials).AccountName);
            Assert.AreEqual(emptyKeyValueAsString, ((SharedKeyCredentials)account3.Credentials).ExportBase64EncodedKey());
        }
Beispiel #23
0
        // NewSASQueryParameters uses an account's shared key credential to sign this signature values to produce
        // the proper SAS query parameters.
        public SasQueryParameters ToSasQueryParameters(SharedKeyCredentials sharedKeyCredential)
        {
            // https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS
            sharedKeyCredential = sharedKeyCredential ?? throw Errors.ArgumentNull(nameof(sharedKeyCredential));

            if (this.ExpiryTime == default || String.IsNullOrEmpty(this.Permissions) || String.IsNullOrEmpty(this.ResourceTypes) || String.IsNullOrEmpty(this.Services))
            {
                throw Errors.AccountSasMissingData();
            }
            if (String.IsNullOrEmpty(this.Version))
            {
                this.Version = SasQueryParameters.SasVersion;
            }
            // Make sure the permission characters are in the correct order
            this.Permissions = AccountSasPermissions.Parse(this.Permissions).ToString();
            var startTime  = SasQueryParameters.FormatTimesForSasSigning(this.StartTime);
            var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime);

            // String to sign: http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx
            var stringToSign = String.Join("\n",
                                           sharedKeyCredential.AccountName,
                                           this.Permissions,
                                           this.Services,
                                           this.ResourceTypes,
                                           startTime,
                                           expiryTime,
                                           this.IPRange.ToString(),
                                           this.Protocol.ToString(),
                                           this.Version,
                                           ""); // That's right, the account SAS requires a terminating extra newline

            var signature = sharedKeyCredential.ComputeHMACSHA256(stringToSign);
            var p         = new SasQueryParameters(this.Version, this.Services, this.ResourceTypes, this.Protocol, this.StartTime, this.ExpiryTime, this.IPRange, null, null, this.Permissions, signature);

            return(p);
        }
 public QueueServiceClient GetServiceClient_QueueServiceSas(string queueName, SharedKeyCredentials sharedKeyCredentials = default, SasQueryParameters sasCredentials = default)
 => this.InstrumentClient(
     new QueueServiceClient(
         new Uri($"{TestConfigurations.DefaultTargetTenant.QueueServiceEndpoint}?{sasCredentials ?? this.GetNewQueueServiceSasCredentials(queueName, sharedKeyCredentials ?? this.GetNewSharedKeyCredentials())}"),
         this.GetOptions()));
        public SasQueryParameters GetNewBlobServiceSasCredentialsSnapshot(string containerName, string blobName, string snapshot, SharedKeyCredentials sharedKeyCredentials = default)
        => new BlobSasBuilder
        {
            ContainerName = containerName,
            BlobName      = blobName,
            Snapshot      = snapshot,
            Protocol      = SasProtocol.None,
            StartTime     = this.Recording.UtcNow.AddHours(-1),
            ExpiryTime    = this.Recording.UtcNow.AddHours(+1),
            Permissions   = new SnapshotSasPermissions {
                Read = true, Write = true, Delete = true
            }.ToString(),
            IPRange = new IPRange {
                Start = IPAddress.None, End = IPAddress.None
            }
        }

        .ToSasQueryParameters(sharedKeyCredentials ?? this.GetNewSharedKeyCredentials());
Beispiel #26
0
 /// <summary>
 /// Construct options for making service requests signed with an Azure
 /// Queue Storage shared key.
 /// </summary>
 /// <param name="credentials">
 /// The <see cref="SharedKeyCredentials"/> used to sign requests.
 /// </param>
 public QueueConnectionOptions(SharedKeyCredentials credentials)
     : base(credentials)
 {
 }
Beispiel #27
0
        public static SasQueryParameters GetNewBlobServiceSasCredentialsBlob(string containerName, string blobName, SharedKeyCredentials sharedKeyCredentials = default)
        => new BlobSasBuilder
        {
            ContainerName = containerName,
            BlobName      = blobName,
            Protocol      = SasProtocol.None,
            StartTime     = DateTimeOffset.UtcNow.AddHours(-1),
            ExpiryTime    = DateTimeOffset.UtcNow.AddHours(+1),
            Permissions   = new BlobSasPermissions {
                Read = true, Add = true, Create = true, Write = true, Delete = true
            }.ToString(),
            IPRange = new IPRange {
                Start = IPAddress.None, End = IPAddress.None
            }
        }

        .ToSasQueryParameters(sharedKeyCredentials ?? GetNewSharedKeyCredentials());
Beispiel #28
0
 public static BlobServiceClient GetServiceClient_AccountSas(
     SharedKeyCredentials sharedKeyCredentials = default,
     SasQueryParameters sasCredentials         = default)
 => new BlobServiceClient(
     new Uri($"{TestConfigurations.DefaultTargetTenant.BlobServiceEndpoint}?{sasCredentials ?? GetNewAccountSasCredentials(sharedKeyCredentials ?? GetNewSharedKeyCredentials())}"),
     GetOptions <BlobConnectionOptions>());
Beispiel #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlobConnectionOptions"/>
 /// class for making service requests signed with an Azure Blob
 /// Storage shared key.
 /// </summary>
 /// <param name="credentials">
 /// The <see cref="SharedKeyCredentials"/> used to sign requests.
 /// </param>
 public BlobConnectionOptions(SharedKeyCredentials credentials)
     : base(credentials)
 {
 }
Beispiel #30
0
 public static QueueServiceClient GetServiceClient_QueueServiceSas(string queueName, SharedKeyCredentials sharedKeyCredentials = default, SasQueryParameters sasCredentials = default)
 => new QueueServiceClient(
     new Uri($"{TestConfigurations.DefaultTargetTenant.QueueServiceEndpoint}?{sasCredentials ?? GetNewQueueServiceSasCredentials(queueName, sharedKeyCredentials ?? GetNewSharedKeyCredentials())}"),
     GetOptions <QueueConnectionOptions>());