Пример #1
0
        public async Task AuthenticateFromCacheTest()
        {
            // Arrange
            var cloudProxy        = Mock.Of <ICloudProxy>(c => c.IsActive && c.OpenAsync() == Task.FromResult(true));
            var connectionManager = Mock.Of <IConnectionManager>(
                c =>
                c.CreateCloudConnectionAsync(It.IsAny <IClientCredentials>()) == Task.FromResult(Try.Success(cloudProxy)));

            string iothubHostName    = "iothub1.azure.net";
            string callerProductInfo = "productInfo";
            string sasToken          = TokenHelper.CreateSasToken($"{iothubHostName}/devices/device1/modules/moduleId");
            var    identity          = Mock.Of <IIdentity>(i => i.Id == "d1");
            var    credentials       = new TokenCredentials(identity, sasToken, callerProductInfo);

            var storedTokenCredentials = Mock.Of <ITokenCredentials>(c => c.Token == sasToken);
            var credentialsStore       = new Mock <ICredentialsStore>();

            credentialsStore.Setup(c => c.Get(It.IsAny <IIdentity>()))
            .ReturnsAsync(Option.Some((IClientCredentials)storedTokenCredentials));
            credentialsStore.Setup(c => c.Add(It.IsAny <IClientCredentials>()))
            .Returns(Task.CompletedTask);

            var tokenCredentialsAuthenticator = new TokenCacheAuthenticator(new CloudTokenAuthenticator(connectionManager), credentialsStore.Object, iothubHostName);

            // Act
            bool isAuthenticated = await tokenCredentialsAuthenticator.AuthenticateAsync(credentials);

            // assert
            Assert.True(isAuthenticated);
            Mock.Verify(credentialsStore);
            Mock.Get(connectionManager).Verify(c => c.CreateCloudConnectionAsync(It.IsAny <IClientCredentials>()), Times.Never);
            Mock.Get(cloudProxy).Verify(c => c.OpenAsync(), Times.Never);
        }
Пример #2
0
        public async Task NotAuthenticatedTest()
        {
            // Arrange
            var connectionManager = Mock.Of <IConnectionManager>(
                c =>
                c.CreateCloudConnectionAsync(It.IsAny <IClientCredentials>()) == Task.FromResult(Try <ICloudProxy> .Failure(new UnauthorizedException("Not authorized"))));

            string iothubHostName    = "iothub1.azure.net";
            string callerProductInfo = "productInfo";
            string sasToken          = TokenHelper.CreateSasToken($"{iothubHostName}/devices/device1/modules/moduleId");
            var    identity          = Mock.Of <IIdentity>(i => i.Id == "d1");
            var    credentials       = new TokenCredentials(identity, sasToken, callerProductInfo, Option.None <string>(), false);

            string sasToken2 = TokenHelper.CreateSasToken($"{iothubHostName}/devices/device1/modules/moduleId") + "a";
            var    storedTokenCredentials = Mock.Of <ITokenCredentials>(c => c.Token == sasToken2);
            var    credentialsStore       = new Mock <ICredentialsCache>();

            credentialsStore.Setup(c => c.Get(It.IsAny <IIdentity>()))
            .ReturnsAsync(Option.Some((IClientCredentials)storedTokenCredentials));
            credentialsStore.Setup(c => c.Add(It.IsAny <IClientCredentials>()))
            .Returns(Task.CompletedTask);

            var tokenCredentialsAuthenticator = new TokenCacheAuthenticator(new CloudTokenAuthenticator(connectionManager, iothubHostName), credentialsStore.Object, iothubHostName);

            // Act
            bool isAuthenticated = await tokenCredentialsAuthenticator.AuthenticateAsync(credentials);

            // assert
            Assert.False(isAuthenticated);
            Mock.Verify(credentialsStore);
            Mock.Verify(Mock.Get(connectionManager));
        }
Пример #3
0
        async Task <IAuthenticator> GetCloudTokenAuthenticator(IComponentContext context)
        {
            IAuthenticator     tokenAuthenticator;
            var                connectionManagerTask = context.Resolve <Task <IConnectionManager> >();
            var                credentialsCacheTask  = context.Resolve <Task <ICredentialsCache> >();
            IConnectionManager connectionManager     = await connectionManagerTask;
            ICredentialsCache  credentialsCache      = await credentialsCacheTask;

            if (this.persistTokens)
            {
                IAuthenticator authenticator = new CloudTokenAuthenticator(connectionManager, this.iothubHostName);
                tokenAuthenticator = new TokenCacheAuthenticator(authenticator, credentialsCache, this.iothubHostName);
            }
            else
            {
                tokenAuthenticator = new CloudTokenAuthenticator(connectionManager, this.iothubHostName);
            }

            return(tokenAuthenticator);
        }
Пример #4
0
        protected override void Load(ContainerBuilder builder)
        {
            // Task<IAuthenticator>
            builder.Register(async c =>
            {
                var connectionManager = c.Resolve <IConnectionManager>();
                ICredentialsStore credentialsStore = await c.Resolve <Task <ICredentialsStore> >();
                var tokenCredentialsAuthenticator  = new TokenCacheAuthenticator(new CloudTokenAuthenticator(connectionManager), credentialsStore, this.iothubHostName);
                return(new Authenticator(tokenCredentialsAuthenticator, this.deviceId, connectionManager) as IAuthenticator);
            })
            .As <Task <IAuthenticator> >()
            .SingleInstance();

            // IClientCredentialsFactory
            builder.Register(c => new ClientCredentialsFactory(this.iothubHostName, this.productInfo))
            .As <IClientCredentialsFactory>()
            .SingleInstance();

            base.Load(builder);
        }
Пример #5
0
        protected override void Load(ContainerBuilder builder)
        {
            // ISignatureProvider
            builder.Register(
                c =>
            {
                ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map(
                    cs =>
                {
                    IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs);
                    return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider);
                })
                                                       .GetOrElse(
                    () =>
                {
                    string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing"));
                    string workloadUri         = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing"));
                    return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, Service.Constants.WorkloadApiVersion) as ISignatureProvider);
                });
                return(signatureProvider);
            })
            .As <ISignatureProvider>()
            .SingleInstance();

            // Detect system environment
            builder.Register(c => new SystemEnvironment())
            .As <ISystemEnvironment>()
            .SingleInstance();

            // DataBase options
            builder.Register(c => new Storage.RocksDb.RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance))
            .As <Storage.RocksDb.IRocksDbOptionsProvider>()
            .SingleInstance();

            // IDbStoreProvider
            builder.Register(
                c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                ILogger logger    = loggerFactory.CreateLogger(typeof(RoutingModule));

                if (this.usePersistentStorage)
                {
                    // Create partitions for messages and twins
                    var partitionsList = new List <string> {
                        Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey
                    };
                    try
                    {
                        IDbStoreProvider dbStoreprovider = Storage.RocksDb.DbStoreProvider.Create(c.Resolve <Storage.RocksDb.IRocksDbOptionsProvider>(),
                                                                                                  this.storagePath, partitionsList);
                        logger.LogInformation($"Created persistent store at {this.storagePath}");
                        return(dbStoreprovider);
                    }
                    catch (Exception ex) when(!ExceptionEx.IsFatal(ex))
                    {
                        logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                        return(new InMemoryDbStoreProvider());
                    }
                }
                else
                {
                    logger.LogInformation($"Using in-memory store");
                    return(new InMemoryDbStoreProvider());
                }
            })
            .As <IDbStoreProvider>()
            .SingleInstance();

            // Task<IEncryptionProvider>
            builder.Register(
                async c =>
            {
                IEncryptionProvider encryptionProvider = await this.workloadUri.Map(
                    async uri => await EncryptionProvider.CreateAsync(
                        this.storagePath,
                        new Uri(uri),
                        Service.Constants.WorkloadApiVersion,
                        this.edgeHubModuleId,
                        this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                        Service.Constants.InitializationVectorFileName) as IEncryptionProvider)
                                                         .GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance));
                return(encryptionProvider);
            })
            .As <Task <IEncryptionProvider> >()
            .SingleInstance();

            // IStoreProvider
            builder.Register(c => new StoreProvider(c.Resolve <IDbStoreProvider>()))
            .As <IStoreProvider>()
            .SingleInstance();

            // ITokenProvider
            builder.Register(c => new ModuleTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1)))
            .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider")
            .SingleInstance();

            // ITokenProvider
            builder.Register(c =>
            {
                string deviceId = WebUtility.UrlEncode(this.edgeDeviceId);
                string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId);
                return(new ModuleTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1)));
            })
            .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider")
            .SingleInstance();

            // Task<IKeyValueStore<string, string>> - EncryptedStore
            builder.Register(
                async c =>
            {
                var storeProvider = c.Resolve <IStoreProvider>();
                IEncryptionProvider encryptionProvider         = await c.Resolve <Task <IEncryptionProvider> >();
                IEntityStore <string, string> entityStore      = storeProvider.GetEntityStore <string, string>("SecurityScopeCache");
                IKeyValueStore <string, string> encryptedStore = new EncryptedStore <string, string>(entityStore, encryptionProvider);
                return(encryptedStore);
            })
            .Named <Task <IKeyValueStore <string, string> > >("EncryptedStore")
            .SingleInstance();


            // Task<IDeviceScopeIdentitiesCache>
            builder.Register(
                async c =>
            {
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope)
                {
                    var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider");
                    IDeviceScopeApiClient securityScopesApiClient = new DeviceScopeApiClient(this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider);
                    IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClient);
                    IKeyValueStore <string, string> encryptedStore = await c.ResolveNamed <Task <IKeyValueStore <string, string> > >("EncryptedStore");
                    deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy, encryptedStore, this.scopeCacheRefreshRate);
                }
                else
                {
                    deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache();
                }

                return(deviceScopeIdentitiesCache);
            })
            .As <Task <IDeviceScopeIdentitiesCache> >()
            .SingleInstance();

            // Task<IAuthenticator>
            builder.Register(async c =>
            {
                IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >();
                IAuthenticator tokenAuthenticator;
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                switch (this.authenticationMode)
                {
                case AuthenticationMode.Cloud:
                    if (this.cacheTokens)
                    {
                        ICredentialsStore credentialsStore = await c.Resolve <Task <ICredentialsStore> >();
                        IAuthenticator authenticator       = new CloudTokenAuthenticator(connectionManager);
                        tokenAuthenticator = new TokenCacheAuthenticator(authenticator, credentialsStore, this.iothubHostName);
                    }
                    else
                    {
                        tokenAuthenticator = new CloudTokenAuthenticator(connectionManager);
                    }
                    break;

                case AuthenticationMode.Scope:
                    deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                    tokenAuthenticator         = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), connectionManager);
                    break;

                default:
                    deviceScopeIdentitiesCache        = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                    IAuthenticator cloudAuthenticator = new CloudTokenAuthenticator(connectionManager);
                    tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudAuthenticator, connectionManager);
                    break;
                }

                return(new Authenticator(tokenAuthenticator, this.edgeDeviceId, connectionManager) as IAuthenticator);
            })
            .As <Task <IAuthenticator> >()
            .SingleInstance();

            // IClientCredentialsFactory
            builder.Register(c => new ClientCredentialsFactory(this.iothubHostName, this.productInfo))
            .As <IClientCredentialsFactory>()
            .SingleInstance();

            base.Load(builder);
        }