/// <summary> /// Creates SJMPClient /// </summary> /// <param name="url">URL to connect to.</param> /// <param name="auth">Auth credentials. Null if not needed.</param> public SjmpClient(string url, IClientCredentials auth = null) { this.m_url = url; if (auth != null) { this.m_auth = new UserCredentials(auth); }; }
internal UserCredentials(IClientCredentials clientCredentials) { m_credential = new NetworkCredential(clientCredentials.Username, clientCredentials.Password); }
public DeviceConnection(IClientCredentials clientCredentials, IDictionary <DeviceSubscription, bool> subscriptions) { this.ClientCredentials = clientCredentials; this.Subscriptions = subscriptions; this.DeviceProxy = Option.None <IDeviceProxy>(); }
public ProtocolGatewayIdentity(IClientCredentials clientCredentials, Option <string> modelId) { this.ClientCredentials = Preconditions.CheckNotNull(clientCredentials, nameof(clientCredentials)); this.ModelId = modelId; }
public async Task <Try <ICloudConnection> > Connect(IClientCredentials clientCredentials, Action <string, CloudConnectionStatus> connectionStatusChangedHandler) { Preconditions.CheckNotNull(clientCredentials, nameof(clientCredentials)); try { Events.CreatingCloudConnectionUsingClientCredentials(clientCredentials); var cloudListener = new CloudListener(this.edgeHub.Expect(() => new InvalidOperationException("EdgeHub reference should not be null")), clientCredentials.Identity.Id); ConnectionMetadata connectionMetadata = await this.metadataStore.GetMetadata(clientCredentials.Identity.Id); string productInfo = connectionMetadata.EdgeProductInfo; Option <string> modelId = clientCredentials.ModelId.HasValue ? clientCredentials.ModelId : connectionMetadata.ModelId; string authChain = string.Empty; if (this.nestedEdgeEnabled) { Option <string> authChainMaybe = await this.deviceScopeIdentitiesCache.GetAuthChain(clientCredentials.Identity.Id); // It's possible to have no auth-chain for out-of-scope leaf devices connecting through // us as a gateway. In this case we let the upstream connection happen anyways, as any // unauthorized attempt here would be denied by IoTHub. authChain = authChainMaybe.OrDefault(); } // Get the transport settings ITransportSettings[] transportSettings = GetTransportSettings( this.upstreamProtocol, this.connectionPoolSize, this.proxy, this.useServerHeartbeat, authChain); if (this.edgeHubIdentity.Id.Equals(clientCredentials.Identity.Id)) { ICloudConnection cc = await CloudConnection.Create( clientCredentials.Identity, connectionStatusChangedHandler, transportSettings, this.messageConverterProvider, this.clientProvider, cloudListener, this.edgeHubTokenProvider, this.idleTimeout, this.closeOnIdleTimeout, this.operationTimeout, productInfo, modelId); Events.SuccessCreatingCloudConnection(clientCredentials.Identity); return(Try.Success(cc)); } else if (clientCredentials is ITokenCredentials clientTokenCredentails) { ICloudConnection cc = await ClientTokenCloudConnection.Create( clientTokenCredentails, connectionStatusChangedHandler, transportSettings, this.messageConverterProvider, this.clientProvider, cloudListener, this.idleTimeout, this.closeOnIdleTimeout, this.operationTimeout, productInfo, modelId); Events.SuccessCreatingCloudConnection(clientCredentials.Identity); return(Try.Success(cc)); } else { throw new InvalidOperationException($"Cannot connect using client credentials of type {clientCredentials.AuthenticationType} for identity {clientCredentials.Identity.Id}"); } } catch (Exception ex) { Events.ErrorCreatingCloudConnection(clientCredentials.Identity, ex); return(Try <ICloudConnection> .Failure(ex)); } }
public static IClientCredentials ServiceCertificate_CustomCertificateValidator(this IClientCredentials me, string certificateThumbprint) { var cre = me as _ClientCredentials; cre.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new CertificateValidator(certificate => { if (certificate.Thumbprint != certificateThumbprint) { throw new AuthenticationException("Certificate thumbprint validation failed"); } }); return(me); }
public static IClientCredentials ServiceCertificate_CustomCertificateValidator(this IClientCredentials me, X509CertificateValidator certificateValidator) { var cre = me as _ClientCredentials; cre.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = certificateValidator; return(me); }
public OAuth2Authenticator(IClientCredentials credentials) { _credentials = credentials; }
public void SetDatacenterRules(IClientCredentials clientCredentials, List <DatacenterRuleDto> datacenterRules) { SetEvaluationOrder(datacenterRules); _datacenterRules = datacenterRules; _persister.ReplaceDatacenterRules(datacenterRules); }
public void SetDatacenters(IClientCredentials clientCredentials, List <DatacenterDto> datacenters) { _datacenters = datacenters; _persister.ReplaceDatacenters(datacenters); }
public void SetApplications(IClientCredentials clientCredentials, List <ApplicationDto> applications) { _applications = applications.OrderBy(a => a.Name).ToList(); _persister.ReplaceApplications(applications); }
public void UpdateRule(IClientCredentials clientCredentials, int version, string oldName, RuleDto rule) { var ruleVersion = EnsureVersion(version, false); if (ruleVersion == null) { throw new Exception("There is no version of the rules with this RuleVersion number"); } var blockedEnvironments = GetBlockedEnvironments(clientCredentials) ?? new List <EnvironmentDto>(); // Make a deep copy of the rule list in a thread-safe way var rules = _mapper.Map <List <RuleDto>, List <RuleDto> >(ruleVersion.Rules); if (blockedEnvironments.Count > 0) { var blockedMachineNemes = GetBlockedMachines(blockedEnvironments); var blockedEnvironmentNames = blockedEnvironments.Select(e => e.EnvironmentName.ToLower()).ToList(); var existingRule = rules.FirstOrDefault(r => string.Equals(oldName, r.RuleName, StringComparison.InvariantCultureIgnoreCase)); if (existingRule != null) { if (!string.IsNullOrEmpty(existingRule.Environment)) { if (blockedEnvironmentNames.Contains(existingRule.Environment.ToLower())) { throw new Exception("You do not have permission to update rules for the " + existingRule.Environment + " environment"); } } if (!string.IsNullOrEmpty(existingRule.Machine)) { if (blockedMachineNemes.Contains(existingRule.Machine.ToLower())) { throw new Exception("You do not have permission to update rules for the " + existingRule.Machine + " machine"); } } } if (!string.IsNullOrEmpty(rule.Environment)) { if (blockedEnvironmentNames.Contains(rule.Environment.ToLower())) { throw new Exception("You do not have permission to update rules for the " + rule.Environment + " environment"); } } if (!string.IsNullOrEmpty(rule.Machine)) { if (blockedMachineNemes.Contains(rule.Machine.ToLower())) { throw new Exception("You do not have permission to update rules for the " + rule.Machine + " machine"); } } } _persister.DeleteRule(ruleVersion.Version, oldName); _persister.DeleteRule(ruleVersion.Version, rule.RuleName); rules.RemoveAll(r => string.Compare(r.RuleName, oldName, StringComparison.InvariantCultureIgnoreCase) == 0); rules.RemoveAll(r => string.Compare(r.RuleName, rule.RuleName, StringComparison.InvariantCultureIgnoreCase) == 0); _persister.InsertOrUpdateRule(version, rule); rules.Add(rule); SetEvaluationOrder(rules); ruleVersion.Rules = rules; }
public void SetEnvironments(IClientCredentials clientCredentials, List <EnvironmentDto> environments) { var blockedEnvironments = GetBlockedEnvironments(clientCredentials); var currentEnvironments = _environments; if (currentEnvironments == null) { currentEnvironments = new List <EnvironmentDto>(); } var toDelete = new List <string>(); var toAdd = new List <EnvironmentDto>(); Func <EnvironmentDto, EnvironmentDto, bool> eq = (e1, e2) => string.Equals(e1.EnvironmentName, e2.EnvironmentName, StringComparison.InvariantCultureIgnoreCase); var someUpdatesBlocked = false; lock (currentEnvironments) { if (environments == null || environments.Count == 0) { foreach (var environment in currentEnvironments) { if (blockedEnvironments.Any(e => eq(e, environment))) { someUpdatesBlocked = true; } else { toDelete.Add(environment.EnvironmentName); } } } else { foreach (var environment in currentEnvironments) { if (blockedEnvironments.Any(e => eq(e, environment))) { someUpdatesBlocked = true; } else { toDelete.Add(environment.EnvironmentName); } } foreach (var environment in environments) { if (blockedEnvironments.Any(e => eq(e, environment))) { someUpdatesBlocked = true; } else { toAdd.Add(environment); } } } } foreach (var environment in toDelete) { _persister.DeleteEnvironment(environment); } lock (currentEnvironments) { currentEnvironments = currentEnvironments .Where(e => !toDelete.Any(d => string.Equals(d, e.EnvironmentName, StringComparison.InvariantCultureIgnoreCase))) .ToList(); } foreach (var environment in toAdd) { _persister.InsertOrUpdateEnvironment(environment); lock (currentEnvironments) currentEnvironments.Add(environment); } _environments = currentEnvironments; if (someUpdatesBlocked) { throw new Exception("Some environments were not updated because you don't have permission"); } }
protected override void Load(ContainerBuilder builder) { // IMessageConverter<IRoutingMessage> builder.Register(c => new RoutingMessageConverter()) .As <Core.IMessageConverter <IRoutingMessage> >() .SingleInstance(); // IRoutingPerfCounter builder.Register( c => { Routing.PerfCounter = NullRoutingPerfCounter.Instance; return(Routing.PerfCounter); }) .As <IRoutingPerfCounter>() .AutoActivate() .SingleInstance(); // IRoutingUserAnalyticsLogger builder.Register( c => { Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance; return(Routing.UserAnalyticsLogger); }) .As <IRoutingUserAnalyticsLogger>() .AutoActivate() .SingleInstance(); // IRoutingUserMetricLogger builder.Register( c => { Routing.UserMetricLogger = NullRoutingUserMetricLogger.Instance; return(Routing.UserMetricLogger); }) .As <IRoutingUserMetricLogger>() .AutoActivate() .SingleInstance(); // IMessageConverter<Message> builder.Register(c => new DeviceClientMessageConverter()) .As <Core.IMessageConverter <Message> >() .SingleInstance(); // IMessageConverter<Twin> builder.Register(c => new TwinMessageConverter()) .As <Core.IMessageConverter <Twin> >() .SingleInstance(); // IMessageConverter<TwinCollection> builder.Register(c => new TwinCollectionMessageConverter()) .As <Core.IMessageConverter <TwinCollection> >() .SingleInstance(); // IMessageConverterProvider builder.Register( c => new MessageConverterProvider(new Dictionary <Type, IMessageConverter>() { { typeof(Message), c.Resolve <Core.IMessageConverter <Message> >() }, { typeof(Twin), c.Resolve <Core.IMessageConverter <Twin> >() }, { typeof(TwinCollection), c.Resolve <Core.IMessageConverter <TwinCollection> >() } })) .As <Core.IMessageConverterProvider>() .SingleInstance(); // IDeviceConnectivityManager builder.Register( c => { IDeviceConnectivityManager deviceConnectivityManager = new DeviceConnectivityManager(this.connectivityCheckFrequency, TimeSpan.FromMinutes(2)); return(deviceConnectivityManager); }) .As <IDeviceConnectivityManager>() .SingleInstance(); // IDeviceClientProvider builder.Register(c => { IClientProvider underlyingClientProvider = new ClientProvider(); IClientProvider connectivityAwareClientProvider = new ConnectivityAwareClientProvider(underlyingClientProvider, c.Resolve <IDeviceConnectivityManager>()); return(connectivityAwareClientProvider); }) .As <IClientProvider>() .SingleInstance(); // ICloudConnectionProvider builder.Register(c => new CloudConnectionProvider(c.Resolve <Core.IMessageConverterProvider>(), this.connectionPoolSize, c.Resolve <IClientProvider>(), this.upstreamProtocol)) .As <ICloudConnectionProvider>() .SingleInstance(); if (this.isStoreAndForwardEnabled || this.cacheTokens) { // 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(); // IDbStore 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<ICredentialsStore> builder.Register(async c => { if (this.cacheTokens) { var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IEncryptionProvider encryptionProvider = await this.workloadUri.Map( async uri => await EncryptionProvider.CreateAsync( this.storagePath, new Uri(uri), Service.Constants.WorkloadApiVersion, this.edgeModuleId, this.edgeModuleGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")), Service.Constants.InitializationVectorFileName) as IEncryptionProvider) .GetOrElse(() => Task.FromResult <IEncryptionProvider>(NullEncryptionProvider.Instance)); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IEntityStore <string, string> tokenCredentialsEntityStore = storeProvider.GetEntityStore <string, string>("tokenCredentials"); return(new TokenCredentialsStore(tokenCredentialsEntityStore, encryptionProvider)); } else { return(new NullCredentialsStore() as ICredentialsStore); } }) .As <Task <ICredentialsStore> >() .SingleInstance(); // IConnectionManager builder.Register(c => new ConnectionManager(c.Resolve <ICloudConnectionProvider>(), this.maxConnectedClients)) .As <IConnectionManager>() .SingleInstance(); // IEndpointFactory builder.Register(c => new EndpointFactory(c.Resolve <IConnectionManager>(), c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), this.edgeDeviceId)) .As <IEndpointFactory>() .SingleInstance(); // RouteFactory builder.Register(c => new EdgeRouteFactory(c.Resolve <IEndpointFactory>())) .As <RouteFactory>() .SingleInstance(); // RouterConfig builder.Register(c => new RouterConfig(Enumerable.Empty <Route>())) .As <RouterConfig>() .SingleInstance(); if (!this.isStoreAndForwardEnabled) { // EndpointExecutorConfig builder.Register( c => { RetryStrategy defaultRetryStrategy = new FixedInterval(0, TimeSpan.FromSeconds(1)); TimeSpan defaultRevivePeriod = TimeSpan.FromHours(1); TimeSpan defaultTimeout = TimeSpan.FromSeconds(60); return(new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // IEndpointExecutorFactory builder.Register(c => new SyncEndpointExecutorFactory(c.Resolve <EndpointExecutorConfig>())) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); var routerConfig = c.Resolve <RouterConfig>(); Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory); return(router); }) .As <Task <Router> >() .SingleInstance(); // ITwinManager builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.None <IStoreProvider>())) .As <ITwinManager>() .SingleInstance(); } else { // EndpointExecutorConfig builder.Register( c => { // Endpoint executor config values - // ExponentialBackoff - minBackoff = 1s, maxBackoff = 60s, delta (used to add randomness to backoff) - 1s (default) // Num of retries = int.MaxValue(we want to keep retrying till the message is sent) // Revive period - period for which the endpoint should be considered dead if it doesn't respond - 1 min (we want to try continuously till the message expires) // Timeout - time for which we want for the ack from the endpoint = 30s // TODO - Should the number of retries be tied to the Store and Forward ttl? Not // doing that right now as that value can be changed at runtime, but these settings // cannot. Need to make the number of retries dynamically configurable for that. TimeSpan minWait = TimeSpan.FromSeconds(1); TimeSpan maxWait = TimeSpan.FromSeconds(60); TimeSpan delta = TimeSpan.FromSeconds(1); int retries = int.MaxValue; RetryStrategy retryStrategy = new ExponentialBackoff(retries, minWait, maxWait, delta); TimeSpan timeout = TimeSpan.FromSeconds(30); TimeSpan revivePeriod = TimeSpan.FromSeconds(30); return(new EndpointExecutorConfig(timeout, retryStrategy, revivePeriod)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // ICheckpointStore builder.Register(c => CheckpointStore.Create(c.Resolve <IDbStoreProvider>())) .As <ICheckpointStore>() .SingleInstance(); // IMessageStore builder.Register( c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.MaxValue); return(messageStore); }) .As <IMessageStore>() .SingleInstance(); // IEndpointExecutorFactory builder.Register( c => { var endpointExecutorConfig = c.Resolve <EndpointExecutorConfig>(); var messageStore = c.Resolve <IMessageStore>(); IEndpointExecutorFactory endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(10, TimeSpan.FromSeconds(10)), messageStore); return(endpointExecutorFactory); }) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var routerConfig = c.Resolve <RouterConfig>(); var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); return(await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory, checkpointStore)); }) .As <Task <Router> >() .SingleInstance(); // ITwinManager builder.Register(c => TwinManager.CreateTwinManager(c.Resolve <IConnectionManager>(), c.Resolve <IMessageConverterProvider>(), Option.Some <IStoreProvider>(new StoreProvider(c.Resolve <IDbStoreProvider>())))) .As <ITwinManager>() .SingleInstance(); } // IClientCredentials "EdgeHubCredentials" builder.Register( c => { var identityFactory = c.Resolve <IClientCredentialsFactory>(); IClientCredentials edgeHubCredentials = this.connectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse( () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeModuleId)); return(edgeHubCredentials); }) .Named <IClientCredentials>("EdgeHubCredentials") .SingleInstance(); // Task<ICloudProxy> "EdgeHubCloudProxy" builder.Register( async c => { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var connectionManager = c.Resolve <IConnectionManager>(); Try <ICloudProxy> cloudProxyTry = await connectionManager.CreateCloudConnectionAsync(edgeHubCredentials); if (!cloudProxyTry.Success) { throw new EdgeHubConnectionException("Edge hub is unable to connect to IoT Hub", cloudProxyTry.Exception); } ICloudProxy cloudProxy = cloudProxyTry.Value; return(cloudProxy); }) .Named <Task <ICloudProxy> >("EdgeHubCloudProxy") .SingleInstance(); // IInvokeMethodHandler builder.Register(c => new InvokeMethodHandler(c.Resolve <IConnectionManager>())) .As <IInvokeMethodHandler>() .SingleInstance(); // Task<IEdgeHub> builder.Register( async c => { Router router = await c.Resolve <Task <Router> >(); IEdgeHub hub = new RoutingEdgeHub(router, c.Resolve <Core.IMessageConverter <IRoutingMessage> >(), c.Resolve <IConnectionManager>(), c.Resolve <ITwinManager>(), this.edgeDeviceId, c.Resolve <IInvokeMethodHandler>()); return(hub); }) .As <Task <IEdgeHub> >() .SingleInstance(); // Task<ConfigUpdater> builder.Register( async c => { IMessageStore messageStore = this.isStoreAndForwardEnabled ? c.Resolve <IMessageStore>() : null; Router router = await c.Resolve <Task <Router> >(); var configUpdater = new ConfigUpdater(router, messageStore); return(configUpdater); }) .As <Task <ConfigUpdater> >() .SingleInstance(); // Task<IConfigSource> builder.Register( async c => { var routeFactory = c.Resolve <RouteFactory>(); if (this.useTwinConfig) { var connectionManager = c.Resolve <IConnectionManager>(); var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var twinCollectionMessageConverter = c.Resolve <Core.IMessageConverter <TwinCollection> >(); var twinMessageConverter = c.Resolve <Core.IMessageConverter <Twin> >(); var twinManager = c.Resolve <ITwinManager>(); ICloudProxy cloudProxy = await c.ResolveNamed <Task <ICloudProxy> >("EdgeHubCloudProxy"); IEdgeHub edgeHub = await c.Resolve <Task <IEdgeHub> >(); IConfigSource edgeHubConnection = await EdgeHubConnection.Create( edgeHubCredentials.Identity as IModuleIdentity, edgeHub, twinManager, connectionManager, cloudProxy, routeFactory, twinCollectionMessageConverter, twinMessageConverter, this.versionInfo ); return(edgeHubConnection); } else { return(new LocalConfigSource(routeFactory, this.routes, this.storeAndForwardConfiguration)); } }) .As <Task <IConfigSource> >() .SingleInstance(); // Task<IConnectionProvider> builder.Register( async c => { IEdgeHub edgeHub = await c.Resolve <Task <IEdgeHub> >(); IConnectionProvider connectionProvider = new ConnectionProvider(c.Resolve <IConnectionManager>(), edgeHub); return(connectionProvider); }) .As <Task <IConnectionProvider> >() .SingleInstance(); base.Load(builder); }
public AuthCodeExchanger(StreamlabsSettings StreamlabsSettings, IClientCredentials clientCredentials) { settings = StreamlabsSettings; credentials = clientCredentials; }
public async Task RefreshTokenTest() { string iothubHostName = "test.azure-devices.net"; string deviceId = "device1"; IClientCredentials GetClientCredentialsWithExpiringToken() { string token = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(3)); var identity = new DeviceIdentity(iothubHostName, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } IClientCredentials GetClientCredentialsWithNonExpiringToken() { string token = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(10)); var identity = new DeviceIdentity(iothubHostName, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } IAuthenticationMethod authenticationMethod = null; IClientProvider clientProvider = GetMockDeviceClientProviderWithToken((s, a, t) => authenticationMethod = a); var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) }; var receivedStatus = CloudConnectionStatus.ConnectionEstablished; void ConnectionStatusHandler(string id, CloudConnectionStatus status) => receivedStatus = status; var messageConverterProvider = new MessageConverterProvider(new Dictionary <Type, IMessageConverter> { [typeof(TwinCollection)] = Mock.Of <IMessageConverter>() }); var cloudConnection = new CloudConnection(ConnectionStatusHandler, transportSettings, messageConverterProvider, clientProvider, Mock.Of <ICloudListener>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60)); IClientCredentials clientCredentialsWithExpiringToken1 = GetClientCredentialsWithExpiringToken(); ICloudProxy cloudProxy1 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken1); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudConnection.CloudProxy.OrDefault()); Assert.NotNull(authenticationMethod); var deviceAuthenticationWithTokenRefresh = authenticationMethod as DeviceAuthenticationWithTokenRefresh; Assert.NotNull(deviceAuthenticationWithTokenRefresh); Task <string> getTokenTask = deviceAuthenticationWithTokenRefresh.GetTokenAsync(iothubHostName); Assert.False(getTokenTask.IsCompleted); Assert.Equal(receivedStatus, CloudConnectionStatus.TokenNearExpiry); IClientCredentials clientCredentialsWithExpiringToken2 = GetClientCredentialsWithNonExpiringToken(); ICloudProxy cloudProxy2 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken2); // Wait for the task to complete await Task.Delay(TimeSpan.FromSeconds(10)); Assert.True(getTokenTask.IsCompletedSuccessfully); Assert.Equal(cloudProxy2, cloudConnection.CloudProxy.OrDefault()); Assert.True(cloudProxy2.IsActive); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudProxy2); Assert.Equal(getTokenTask.Result, (clientCredentialsWithExpiringToken2 as ITokenCredentials)?.Token); }
public static void ErrorAuthenticating(Exception exception, IClientCredentials credentials, bool reauthenticating) { string operation = reauthenticating ? "reauthenticating" : "authenticating"; Log.LogWarning((int)EventIds.ErrorAuthenticating, exception, $"Error {operation} credentials for {credentials.Identity.Id}"); }
public async Task CloudConnectionCallbackTest() { int receivedConnectedStatusCount = 0; ConnectionStatusChangesHandler connectionStatusChangesHandler = (_, __) => { }; 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); } var deviceClientProvider = new Mock <IClientProvider>(); deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <IAuthenticationMethod>(), It.IsAny <ITransportSettings[]>())) .Returns(() => GetMockedDeviceClient()); var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) }; void ConnectionStatusHandler(string id, CloudConnectionStatus status) { if (status == CloudConnectionStatus.ConnectionEstablished) { receivedConnectedStatusCount++; } } var messageConverterProvider = new MessageConverterProvider(new Dictionary <Type, IMessageConverter>()); var cloudConnection = new CloudConnection(ConnectionStatusHandler, transportSettings, messageConverterProvider, deviceClientProvider.Object); IClientCredentials clientCredentialsWithExpiringToken1 = GetMockClientCredentialsWithToken(); Assert.Equal(receivedConnectedStatusCount, 0); ICloudProxy cloudProxy1 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken1); Assert.True(cloudProxy1.IsActive); Assert.Equal(cloudProxy1, cloudConnection.CloudProxy.OrDefault()); Assert.Equal(receivedConnectedStatusCount, 1); Assert.NotNull(connectionStatusChangesHandler); connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.Equal(receivedConnectedStatusCount, 2); IClientCredentials clientCredentialsWithExpiringToken2 = GetMockClientCredentialsWithToken(); ICloudProxy cloudProxy2 = await cloudConnection.CreateOrUpdateAsync(clientCredentialsWithExpiringToken2); Assert.True(cloudProxy2.IsActive); Assert.Equal(cloudProxy2, cloudConnection.CloudProxy.OrDefault()); Assert.Equal(receivedConnectedStatusCount, 3); connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.Equal(receivedConnectedStatusCount, 4); }
public async Task TestEdgeHubConnection() { const string EdgeDeviceId = "testHubEdgeDevice1"; var twinMessageConverter = new TwinMessageConverter(); var twinCollectionMessageConverter = new TwinCollectionMessageConverter(); var messageConverterProvider = new MessageConverterProvider( new Dictionary <Type, IMessageConverter>() { { typeof(Message), new DeviceClientMessageConverter() }, { typeof(Twin), twinMessageConverter }, { typeof(TwinCollection), twinCollectionMessageConverter } }); string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); await registryManager.OpenAsync(); string iothubHostName = iotHubConnectionStringBuilder.HostName; var identityProvider = new IdentityProvider(iothubHostName); var identityFactory = new ClientCredentialsFactory(identityProvider); (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(EdgeDeviceId, iotHubConnectionString, registryManager, true, false); string edgeHubConnectionString = $"{deviceConnStr};ModuleId={EdgeHubModuleId}"; IClientCredentials edgeHubCredentials = identityFactory.GetWithConnectionString(edgeHubConnectionString); string sasKey = ConnectionStringHelper.GetSharedAccessKey(deviceConnStr); var signatureProvider = new SharedAccessKeySignatureProvider(sasKey); var credentialsCache = Mock.Of <ICredentialsCache>(); var cloudConnectionProvider = new CloudConnectionProvider( messageConverterProvider, 1, new ClientProvider(), Option.None <UpstreamProtocol>(), new ClientTokenProvider(signatureProvider, iothubHostName, edgeDeviceId, TimeSpan.FromMinutes(60)), Mock.Of <IDeviceScopeIdentitiesCache>(), credentialsCache, edgeHubCredentials.Identity, TimeSpan.FromMinutes(60), true, TimeSpan.FromSeconds(20), Option.None <IWebProxy>()); var connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), identityProvider); try { Mock.Get(credentialsCache) .Setup(c => c.Get(edgeHubCredentials.Identity)) .ReturnsAsync(Option.Some(edgeHubCredentials)); Assert.NotNull(edgeHubCredentials); Assert.NotNull(edgeHubCredentials.Identity); // Set Edge hub desired properties await this.SetDesiredProperties(registryManager, edgeDeviceId); var endpointFactory = new EndpointFactory(connectionManager, new RoutingMessageConverter(), edgeDeviceId); var routeFactory = new EdgeRouteFactory(endpointFactory); var dbStoreProvider = new InMemoryDbStoreProvider(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IEntityStore <string, TwinInfo> twinStore = storeProvider.GetEntityStore <string, TwinInfo>("twins"); var twinManager = new TwinManager(connectionManager, twinCollectionMessageConverter, twinMessageConverter, Option.Some(twinStore)); var routerConfig = new RouterConfig(Enumerable.Empty <Route>()); TimeSpan defaultTimeout = TimeSpan.FromSeconds(60); var endpointExecutorFactory = new SyncEndpointExecutorFactory(new EndpointExecutorConfig(defaultTimeout, new FixedInterval(0, TimeSpan.FromSeconds(1)), defaultTimeout, true)); Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), iothubHostName, routerConfig, endpointExecutorFactory); IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager); var deviceConnectivityManager = Mock.Of <IDeviceConnectivityManager>(); var subscriptionProcessor = new SubscriptionProcessor(connectionManager, invokeMethodHandler, deviceConnectivityManager); IEdgeHub edgeHub = new RoutingEdgeHub(router, new RoutingMessageConverter(), connectionManager, twinManager, edgeDeviceId, invokeMethodHandler, subscriptionProcessor); cloudConnectionProvider.BindEdgeHub(edgeHub); var versionInfo = new VersionInfo("v1", "b1", "c1"); // Create Edge Hub connection EdgeHubConnection edgeHubConnection = await EdgeHubConnection.Create( edgeHubCredentials.Identity, edgeHub, twinManager, connectionManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, new NullDeviceScopeIdentitiesCache()); await Task.Delay(TimeSpan.FromMinutes(1)); // Get and Validate EdgeHubConfig Option <EdgeHubConfig> edgeHubConfigOption = await edgeHubConnection.GetConfig(); Assert.True(edgeHubConfigOption.HasValue); EdgeHubConfig edgeHubConfig = edgeHubConfigOption.OrDefault(); Assert.Equal("1.0", edgeHubConfig.SchemaVersion); Assert.NotNull(edgeHubConfig.Routes); Assert.NotNull(edgeHubConfig.StoreAndForwardConfiguration); Assert.Equal(20, edgeHubConfig.StoreAndForwardConfiguration.TimeToLiveSecs); List <(string Name, string Value, Route Route)> routes = edgeHubConfig.Routes.ToList(); Assert.Equal(4, routes.Count); (string Name, string Value, Route Route)route1 = routes[0]; Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint)); Assert.Equal("route1", route1.Name); Assert.Equal("from /* INTO $upstream", route1.Value); (string Name, string Value, Route Route)route2 = routes[1]; Endpoint endpoint = route2.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id); Assert.Equal("route2", route2.Name); Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value); (string Name, string Value, Route Route)route3 = routes[2]; endpoint = route3.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module3/input1", endpoint.Id); Assert.Equal("route3", route3.Name); Assert.Equal("from /modules/module2 INTO BrokeredEndpoint(\"/modules/module3/inputs/input1\")", route3.Value); (string Name, string Value, Route Route)route4 = routes[3]; endpoint = route4.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module4/input1", endpoint.Id); Assert.Equal("route4", route4.Name); Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module4/inputs/input1\")", route4.Value); // Make sure reported properties were updated appropriately EdgeHubConnection.ReportedProperties reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.NotNull(reportedProperties.Clients); Assert.Equal(0, reportedProperties.Clients.Count); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Simulate a module and a downstream device that connects to Edge Hub. string moduleId = "module1"; string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{edgeDeviceId}/modules/{moduleId}"); string moduleConnectionstring = $"HostName={iothubHostName};DeviceId={edgeDeviceId};ModuleId={moduleId};SharedAccessSignature={sasToken}"; IClientCredentials moduleClientCredentials = identityFactory.GetWithConnectionString(moduleConnectionstring); var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive); string downstreamDeviceId = "device1"; sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{downstreamDeviceId}"); string downstreamDeviceConnectionstring = $"HostName={iothubHostName};DeviceId={downstreamDeviceId};SharedAccessSignature={sasToken}"; IClientCredentials downstreamDeviceCredentials = identityFactory.GetWithConnectionString(downstreamDeviceConnectionstring); var downstreamDeviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive); // Connect the module and downstream device and make sure the reported properties are updated as expected. await connectionManager.AddDeviceConnection(moduleClientCredentials.Identity, moduleProxy); await connectionManager.AddDeviceConnection(downstreamDeviceCredentials.Identity, downstreamDeviceProxy); string moduleIdKey = $"{edgeDeviceId}/{moduleId}"; await Task.Delay(TimeSpan.FromSeconds(10)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(2, reportedProperties.Clients.Count); Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[moduleIdKey].Status); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc); Assert.Null(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc); Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[downstreamDeviceId].Status); Assert.NotNull(reportedProperties.Clients[downstreamDeviceId].LastConnectedTimeUtc); Assert.Null(reportedProperties.Clients[downstreamDeviceId].LastDisconnectTimeUtc); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Update desired propertied and make sure callback is called with valid values bool callbackCalled = false; Task ConfigUpdatedCallback(EdgeHubConfig updatedConfig) { Assert.NotNull(updatedConfig); Assert.NotNull(updatedConfig.StoreAndForwardConfiguration); Assert.NotNull(updatedConfig.Routes); routes = updatedConfig.Routes.ToList(); Assert.Equal(4, routes.Count); route1 = routes[0]; Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint)); Assert.Equal("route1", route1.Name); Assert.Equal("from /* INTO $upstream", route1.Value); route2 = routes[1]; endpoint = route2.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id); Assert.Equal("route2", route2.Name); Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value); route3 = routes[2]; endpoint = route3.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module5/input1", endpoint.Id); Assert.Equal("route4", route3.Name); Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", route3.Value); route4 = routes[3]; endpoint = route4.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module6/input1", endpoint.Id); Assert.Equal("route5", route4.Name); Assert.Equal("from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", route4.Value); callbackCalled = true; return(Task.CompletedTask); } edgeHubConnection.SetConfigUpdatedCallback(ConfigUpdatedCallback); await this.UpdateDesiredProperties(registryManager, edgeDeviceId); await Task.Delay(TimeSpan.FromSeconds(5)); Assert.True(callbackCalled); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.NotNull(reportedProperties.Clients); Assert.Equal(2, reportedProperties.Clients.Count); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Disconnect the downstream device and make sure the reported properties are updated as expected. await connectionManager.RemoveDeviceConnection(moduleIdKey); await connectionManager.RemoveDeviceConnection(downstreamDeviceId); await Task.Delay(TimeSpan.FromSeconds(10)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(1, reportedProperties.Clients.Count); Assert.True(reportedProperties.Clients.ContainsKey(moduleIdKey)); Assert.False(reportedProperties.Clients.ContainsKey(downstreamDeviceId)); Assert.Equal(ConnectionStatus.Disconnected, reportedProperties.Clients[moduleIdKey].Status); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // If the edge hub restarts, clear out the connected devices in the reported properties. await EdgeHubConnection.Create( edgeHubCredentials.Identity, edgeHub, twinManager, connectionManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo, new NullDeviceScopeIdentitiesCache()); await Task.Delay(TimeSpan.FromMinutes(1)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Null(reportedProperties.Clients); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); } finally { try { await RegistryManagerHelper.RemoveDevice(edgeDeviceId, registryManager); } catch (Exception) { // ignored } } }
public async Task UpdateDeviceConnectionTest() { int receivedConnectedStatusCount = 0; ConnectionStatusChangesHandler connectionStatusChangesHandler = null; string hostname = "dummy.azure-devices.net"; string deviceId = "device1"; IClientCredentials GetClientCredentials() { string token = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(10)); var identity = new DeviceIdentity(hostname, deviceId); return(new TokenCredentials(identity, token, string.Empty)); } 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>()); IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider); IClientCredentials clientCredentials1 = GetClientCredentials(); 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(); 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.True(tokenGetter.IsCompleted); Assert.Equal(tokenGetter.Result, (clientCredentials2 as ITokenCredentials)?.Token); await Task.Delay(TimeSpan.FromSeconds(10)); Assert.NotNull(authenticationMethod); deviceTokenRefresher = authenticationMethod as DeviceAuthenticationWithTokenRefresh; Assert.NotNull(deviceTokenRefresher); tokenGetter = deviceTokenRefresher.GetTokenAsync(hostname); Assert.False(tokenGetter.IsCompleted); IClientCredentials clientCredentials3 = GetClientCredentials(); 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(3)); Assert.True(tokenGetter.IsCompleted); Assert.Equal(tokenGetter.Result, (clientCredentials3 as ITokenCredentials)?.Token); Mock.VerifyAll(Mock.Get(deviceProxy1), Mock.Get(deviceProxy2)); }
public static IClientCredentials ServiceCertificate_CustomCertificateValidator(this IClientCredentials me, Action <X509Certificate2> certificateValidationAction) { var cre = me as _ClientCredentials; cre.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new CertificateValidator(certificateValidationAction); return(me); }
public async Task <IDeviceIdentity> GetAsync(string clientId, string username, string password, EndPoint clientAddress) { try { Preconditions.CheckNonWhiteSpace(username, nameof(username)); Preconditions.CheckNonWhiteSpace(clientId, nameof(clientId)); ClientInfo clientInfo = this.usernameParser.Parse(username); clientInfo.ModelId.ForEach(async m => await this.metadataStore.SetModelId(clientInfo.DeviceId, m)); IClientCredentials deviceCredentials = null; Option <IClientCredentials> actorCredentials = Option.None <IClientCredentials>(); if (!string.IsNullOrEmpty(password)) { deviceCredentials = this.clientCredentialsFactory.GetWithSasToken(clientInfo.DeviceId, clientInfo.ModuleId, clientInfo.DeviceClientType, password, false, clientInfo.ModelId, clientInfo.AuthChain); // For OnBehalfOf connections, we'll get the token for the actor EdgeHub instead // of the actual leaf/module, so we need to construct the credentials accordingly Option <string> actorDeviceIdOption = AuthChainHelpers.GetActorDeviceId(clientInfo.AuthChain); actorCredentials = actorDeviceIdOption.Map(actorDeviceId => this.clientCredentialsFactory.GetWithSasToken( actorDeviceId, Microsoft.Azure.Devices.Edge.Hub.Core.Constants.EdgeHubModuleId, clientInfo.DeviceClientType, password, false, clientInfo.ModelId, clientInfo.AuthChain)); } else if (this.remoteCertificate.HasValue) { if (!this.clientCertAuthAllowed) { Events.CertAuthNotEnabled(clientInfo.DeviceId, clientInfo.ModuleId); return(UnauthenticatedDeviceIdentity.Instance); } this.remoteCertificate.ForEach( cert => { deviceCredentials = this.clientCredentialsFactory.GetWithX509Cert( clientInfo.DeviceId, clientInfo.ModuleId, clientInfo.DeviceClientType, cert, this.remoteCertificateChain, clientInfo.ModelId, Option.None <string>()); }); } else { Events.AuthNotFound(clientInfo.DeviceId, clientInfo.ModuleId); return(UnauthenticatedDeviceIdentity.Instance); } if (deviceCredentials == null || !clientId.Equals(deviceCredentials.Identity.Id, StringComparison.Ordinal) || !await this.authenticator.AuthenticateAsync(actorCredentials.GetOrElse(deviceCredentials))) { Events.Error(clientId, username); return(UnauthenticatedDeviceIdentity.Instance); } await this.metadataStore.SetMetadata(deviceCredentials.Identity.Id, clientInfo.DeviceClientType, clientInfo.ModelId); Events.Success(clientId, username); return(new ProtocolGatewayIdentity(deviceCredentials, clientInfo.ModelId)); } catch (Exception ex) { Events.ErrorCreatingIdentity(ex); throw; } }
public static void CreatingCloudConnectionUsingClientCredentials(IClientCredentials clientCredentials) { Log.LogDebug((int)EventIds.CreatingCloudConnectionUsingClientCredentials, $"Creating cloud connection for client {clientCredentials.Identity.Id} using client credentials"); }
public AuthCodeExchanger(GoogleDriveSettings googleDriveSettings, IClientCredentials clientCredentials) { settings = googleDriveSettings; credentials = clientCredentials; }
public SaslPrincipal(bool isAuthenticated, IClientCredentials clientCredentials) { this.isAuthenticated = isAuthenticated; this.clientCredentials = Preconditions.CheckNotNull(clientCredentials, nameof(clientCredentials)); this.Identity = new GenericIdentity(this.clientCredentials.Identity.Id); }
public SystemComponentIdProvider(IClientCredentials edgeHubCredentials) { this.EdgeHubBridgeId = edgeHubCredentials.Identity.Id + "/$bridge"; }
Task <Try <ICloudConnection> > CreateOrUpdateCloudConnection(ConnectedDevice device, IClientCredentials credentials) => device.CloudConnection.Map( async c => { try { await c.CreateOrUpdateAsync(credentials); return(Try.Success(c)); } catch (Exception ex) { return(Try <ICloudConnection> .Failure(new EdgeHubConnectionException($"Error updating identity for device {device.Identity.Id}", ex))); } }) .GetOrElse(() => this.cloudConnectionProvider.Connect(credentials, (identity, status) => this.CloudConnectionStatusChangedHandler(identity, status)));
Task <Try <ICloudConnection> > CreateOrUpdateCloudConnection(ConnectedDevice device, IClientCredentials credentials) => device.CloudConnection.Map(
protected override void Load(ContainerBuilder builder) { // IMessageConverter<IRoutingMessage> builder.Register(c => new RoutingMessageConverter()) .As <Core.IMessageConverter <IRoutingMessage> >() .SingleInstance(); // IRoutingPerfCounter builder.Register( c => { Routing.PerfCounter = NullRoutingPerfCounter.Instance; return(Routing.PerfCounter); }) .As <IRoutingPerfCounter>() .AutoActivate() .SingleInstance(); // IRoutingUserAnalyticsLogger builder.Register( c => { Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance; return(Routing.UserAnalyticsLogger); }) .As <IRoutingUserAnalyticsLogger>() .AutoActivate() .SingleInstance(); // IRoutingUserMetricLogger builder.Register( c => { Routing.UserMetricLogger = NullRoutingUserMetricLogger.Instance; return(Routing.UserMetricLogger); }) .As <IRoutingUserMetricLogger>() .AutoActivate() .SingleInstance(); // IMessageConverter<Message> builder.Register(c => new DeviceClientMessageConverter()) .As <Core.IMessageConverter <Message> >() .SingleInstance(); // IMessageConverter<Twin> builder.Register(c => new TwinMessageConverter()) .As <Core.IMessageConverter <Twin> >() .SingleInstance(); // IMessageConverter<TwinCollection> builder.Register(c => new TwinCollectionMessageConverter()) .As <Core.IMessageConverter <TwinCollection> >() .SingleInstance(); // IMessageConverterProvider builder.Register( c => new MessageConverterProvider( new Dictionary <Type, IMessageConverter>() { { typeof(Message), c.Resolve <Core.IMessageConverter <Message> >() }, { typeof(Twin), c.Resolve <Core.IMessageConverter <Twin> >() }, { typeof(TwinCollection), c.Resolve <Core.IMessageConverter <TwinCollection> >() } })) .As <IMessageConverterProvider>() .SingleInstance(); // IDeviceConnectivityManager builder.Register( c => { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); IDeviceConnectivityManager deviceConnectivityManager = new DeviceConnectivityManager(this.connectivityCheckFrequency, TimeSpan.FromMinutes(2), edgeHubCredentials.Identity); return(deviceConnectivityManager); }) .As <IDeviceConnectivityManager>() .SingleInstance(); // IDeviceClientProvider builder.Register( c => { IClientProvider underlyingClientProvider = new ClientProvider(); IClientProvider connectivityAwareClientProvider = new ConnectivityAwareClientProvider(underlyingClientProvider, c.Resolve <IDeviceConnectivityManager>()); return(connectivityAwareClientProvider); }) .As <IClientProvider>() .SingleInstance(); // Task<ICloudConnectionProvider> builder.Register( async c => { var messageConverterProvider = c.Resolve <IMessageConverterProvider>(); var clientProvider = c.Resolve <IClientProvider>(); var tokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubClientAuthTokenProvider"); var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var deviceScopeIdentitiesCacheTask = c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); var proxy = c.Resolve <Option <IWebProxy> >(); IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask; ICredentialsCache credentialsCache = await credentialsCacheTask; ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider( messageConverterProvider, this.connectionPoolSize, clientProvider, this.upstreamProtocol, tokenProvider, deviceScopeIdentitiesCache, credentialsCache, edgeHubCredentials.Identity, this.cloudConnectionIdleTimeout, this.closeCloudConnectionOnIdleTimeout, this.operationTimeout, proxy); return(cloudConnectionProvider); }) .As <Task <ICloudConnectionProvider> >() .SingleInstance(); // IIdentityProvider builder.Register(_ => new IdentityProvider(this.iotHubName)) .As <IIdentityProvider>() .SingleInstance(); // Task<IConnectionManager> builder.Register( async c => { var cloudConnectionProviderTask = c.Resolve <Task <ICloudConnectionProvider> >(); var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >(); var identityProvider = c.Resolve <IIdentityProvider>(); ICloudConnectionProvider cloudConnectionProvider = await cloudConnectionProviderTask; ICredentialsCache credentialsCache = await credentialsCacheTask; IConnectionManager connectionManager = new ConnectionManager( cloudConnectionProvider, credentialsCache, identityProvider, this.maxConnectedClients); return(connectionManager); }) .As <Task <IConnectionManager> >() .SingleInstance(); // Task<IEndpointFactory> builder.Register( async c => { var messageConverter = c.Resolve <Core.IMessageConverter <IRoutingMessage> >(); IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); return(new EndpointFactory(connectionManager, messageConverter, this.edgeDeviceId, this.maxUpstreamBatchSize, this.upstreamFanOutFactor) as IEndpointFactory); }) .As <Task <IEndpointFactory> >() .SingleInstance(); // Task<RouteFactory> builder.Register(async c => new EdgeRouteFactory(await c.Resolve <Task <IEndpointFactory> >()) as RouteFactory) .As <Task <RouteFactory> >() .SingleInstance(); // RouterConfig builder.Register(c => new RouterConfig(Enumerable.Empty <Route>())) .As <RouterConfig>() .SingleInstance(); if (!this.isStoreAndForwardEnabled) { // EndpointExecutorConfig builder.Register( c => { RetryStrategy defaultRetryStrategy = new FixedInterval(0, TimeSpan.FromSeconds(1)); TimeSpan defaultRevivePeriod = TimeSpan.FromHours(1); TimeSpan defaultTimeout = TimeSpan.FromSeconds(60); return(new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // IEndpointExecutorFactory builder.Register(c => new SyncEndpointExecutorFactory(c.Resolve <EndpointExecutorConfig>())) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); var routerConfig = c.Resolve <RouterConfig>(); Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory); return(router); }) .As <Task <Router> >() .SingleInstance(); // Task<ITwinManager> builder.Register( async c => { if (this.useV1TwinManager) { var messageConverterProvider = c.Resolve <IMessageConverterProvider>(); IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); ITwinManager twinManager = new PassThroughTwinManager(connectionManager, messageConverterProvider); return(twinManager); } else { var messageConverterProvider = c.Resolve <IMessageConverterProvider>(); IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); return(TwinManager.CreateTwinManager(connectionManager, messageConverterProvider, Option.None <IStoreProvider>())); } }) .As <Task <ITwinManager> >() .SingleInstance(); } else { // EndpointExecutorConfig builder.Register( c => { // Endpoint executor config values - // ExponentialBackoff - minBackoff = 1s, maxBackoff = 60s, delta (used to add randomness to backoff) - 1s (default) // Num of retries = int.MaxValue(we want to keep retrying till the message is sent) // Revive period - period for which the endpoint should be considered dead if it doesn't respond - 1 min (we want to try continuously till the message expires) // Timeout - time for which we want for the ack from the endpoint = 30s // TODO - Should the number of retries be tied to the Store and Forward ttl? Not // doing that right now as that value can be changed at runtime, but these settings // cannot. Need to make the number of retries dynamically configurable for that. TimeSpan minWait = TimeSpan.FromSeconds(1); TimeSpan maxWait = TimeSpan.FromSeconds(60); TimeSpan delta = TimeSpan.FromSeconds(1); int retries = int.MaxValue; RetryStrategy retryStrategy = new ExponentialBackoff(retries, minWait, maxWait, delta); TimeSpan timeout = TimeSpan.FromSeconds(30); TimeSpan revivePeriod = TimeSpan.FromSeconds(30); return(new EndpointExecutorConfig(timeout, retryStrategy, revivePeriod)); }) .As <EndpointExecutorConfig>() .SingleInstance(); // ICheckpointStore builder.Register( c => { var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); return(CheckpointStore.Create(storeProvider)); }) .As <ICheckpointStore>() .SingleInstance(); // IMessageStore builder.Register( c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var dbStoreProvider = c.Resolve <IDbStoreProvider>(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.MaxValue); return(messageStore); }) .As <IMessageStore>() .SingleInstance(); // IEndpointExecutorFactory builder.Register( c => { var endpointExecutorConfig = c.Resolve <EndpointExecutorConfig>(); var messageStore = c.Resolve <IMessageStore>(); IEndpointExecutorFactory endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(10, TimeSpan.FromSeconds(10)), messageStore); return(endpointExecutorFactory); }) .As <IEndpointExecutorFactory>() .SingleInstance(); // Task<Router> builder.Register( async c => { var checkpointStore = c.Resolve <ICheckpointStore>(); var routerConfig = c.Resolve <RouterConfig>(); var endpointExecutorFactory = c.Resolve <IEndpointExecutorFactory>(); return(await Router.CreateAsync(Guid.NewGuid().ToString(), this.iotHubName, routerConfig, endpointExecutorFactory, checkpointStore)); }) .As <Task <Router> >() .SingleInstance(); // Task<ITwinManager> builder.Register( async c => { if (this.useV1TwinManager) { var dbStoreProvider = c.Resolve <IDbStoreProvider>(); var messageConverterProvider = c.Resolve <IMessageConverterProvider>(); IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); return(TwinManager.CreateTwinManager(connectionManager, messageConverterProvider, Option.Some <IStoreProvider>(new StoreProvider(dbStoreProvider)))); } else { var messageConverterProvider = c.Resolve <IMessageConverterProvider>(); var deviceConnectivityManager = c.Resolve <IDeviceConnectivityManager>(); var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); IEntityStore <string, TwinStoreEntity> entityStore = await this.GetTwinStore(c); IConnectionManager connectionManager = await connectionManagerTask; ITwinManager twinManager = StoringTwinManager.Create( connectionManager, messageConverterProvider, entityStore, deviceConnectivityManager, new ReportedPropertiesValidator(), this.minTwinSyncPeriod, this.reportedPropertiesSyncFrequency); return(twinManager); } }) .As <Task <ITwinManager> >() .SingleInstance(); } // IClientCredentials "EdgeHubCredentials" builder.Register( c => { var identityFactory = c.Resolve <IClientCredentialsFactory>(); IClientCredentials edgeHubCredentials = this.connectionString.Map(cs => identityFactory.GetWithConnectionString(cs)).GetOrElse( () => identityFactory.GetWithIotEdged(this.edgeDeviceId, this.edgeModuleId)); return(edgeHubCredentials); }) .Named <IClientCredentials>("EdgeHubCredentials") .SingleInstance(); // Task<IInvokeMethodHandler> builder.Register( async c => { IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); return(new InvokeMethodHandler(connectionManager) as IInvokeMethodHandler); }) .As <Task <IInvokeMethodHandler> >() .SingleInstance(); // Task<ISubscriptionProcessor> builder.Register( async c => { var invokeMethodHandlerTask = c.Resolve <Task <IInvokeMethodHandler> >(); var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); var deviceConnectivityManager = c.Resolve <IDeviceConnectivityManager>(); IConnectionManager connectionManager = await connectionManagerTask; IInvokeMethodHandler invokeMethodHandler = await invokeMethodHandlerTask; return(new SubscriptionProcessor(connectionManager, invokeMethodHandler, deviceConnectivityManager) as ISubscriptionProcessor); }) .As <Task <ISubscriptionProcessor> >() .SingleInstance(); // Task<IEdgeHub> builder.Register( async c => { var routingMessageConverter = c.Resolve <Core.IMessageConverter <IRoutingMessage> >(); var routerTask = c.Resolve <Task <Router> >(); var twinManagerTask = c.Resolve <Task <ITwinManager> >(); var invokeMethodHandlerTask = c.Resolve <Task <IInvokeMethodHandler> >(); var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); var subscriptionProcessorTask = c.Resolve <Task <ISubscriptionProcessor> >(); Router router = await routerTask; ITwinManager twinManager = await twinManagerTask; IConnectionManager connectionManager = await connectionManagerTask; IInvokeMethodHandler invokeMethodHandler = await invokeMethodHandlerTask; ISubscriptionProcessor subscriptionProcessor = await subscriptionProcessorTask; IEdgeHub hub = new RoutingEdgeHub( router, routingMessageConverter, connectionManager, twinManager, this.edgeDeviceId, invokeMethodHandler, subscriptionProcessor); return(hub); }) .As <Task <IEdgeHub> >() .SingleInstance(); // Task<ConfigUpdater> builder.Register( async c => { IMessageStore messageStore = this.isStoreAndForwardEnabled ? c.Resolve <IMessageStore>() : null; Router router = await c.Resolve <Task <Router> >(); var configUpdater = new ConfigUpdater(router, messageStore); return(configUpdater); }) .As <Task <ConfigUpdater> >() .SingleInstance(); // Task<IConfigSource> builder.Register( async c => { RouteFactory routeFactory = await c.Resolve <Task <RouteFactory> >(); if (this.useTwinConfig) { var edgeHubCredentials = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials"); var twinCollectionMessageConverter = c.Resolve <Core.IMessageConverter <TwinCollection> >(); var twinMessageConverter = c.Resolve <Core.IMessageConverter <Twin> >(); var twinManagerTask = c.Resolve <Task <ITwinManager> >(); var edgeHubTask = c.Resolve <Task <IEdgeHub> >(); ITwinManager twinManager = await twinManagerTask; IEdgeHub edgeHub = await edgeHubTask; IConnectionManager connectionManager = await c.Resolve <Task <IConnectionManager> >(); IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >(); IConfigSource edgeHubConnection = await EdgeHubConnection.Create( edgeHubCredentials.Identity, edgeHub, twinManager, connectionManager, routeFactory, twinCollectionMessageConverter, twinMessageConverter, this.versionInfo, deviceScopeIdentitiesCache); return(edgeHubConnection); } else { return(new LocalConfigSource(routeFactory, this.routes, this.storeAndForwardConfiguration)); } }) .As <Task <IConfigSource> >() .SingleInstance(); // Task<IConnectionProvider> builder.Register( async c => { var connectionManagerTask = c.Resolve <Task <IConnectionManager> >(); var edgeHubTask = c.Resolve <Task <IEdgeHub> >(); IConnectionManager connectionManager = await connectionManagerTask; IEdgeHub edgeHub = await edgeHubTask; IConnectionProvider connectionProvider = new ConnectionProvider(connectionManager, edgeHub); return(connectionProvider); }) .As <Task <IConnectionProvider> >() .SingleInstance(); base.Load(builder); }
public Task <bool> AuthenticateAsync(IClientCredentials clientCredentials) => this.AuthenticateAsync(clientCredentials, false);
public Task <bool> ReauthenticateAsync(IClientCredentials clientCredentials) => this.AuthenticateAsync(clientCredentials, true);
public AccessTokenRefresher(IClientCredentials clientCredentials) { credentials = clientCredentials; }