public async Task ClientCanConnectUsingSharedKeyCredential()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false))
            {
                var options    = new ServiceBusClientOptions();
                var audience   = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName);
                var credential = new AzureNamedKeyCredential(TestEnvironment.SharedAccessKeyName, TestEnvironment.SharedAccessKey);

                await using (var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, credential, options))
                {
                    Assert.That(async() =>
                    {
                        ServiceBusReceiver receiver = null;

                        try
                        {
                            receiver = client.CreateReceiver(scope.QueueName);
                        }
                        finally
                        {
                            await(receiver?.DisposeAsync() ?? new ValueTask());
                        }
                    }, Throws.Nothing);
                }
            }
        }
Esempio n. 2
0
        public void NameCanBeReadFromTheProperty()
        {
            var expectedName = "real-name";
            var expectedKey  = "real-key";
            var credential   = new AzureNamedKeyCredential(expectedName, expectedKey);

            Assert.AreEqual(expectedName, credential.Name);
        }
Esempio n. 3
0
 public MinimalProcessorMock(int eventBatchMaximumCount,
                             string consumerGroup,
                             string fullyQualifiedNamespace,
                             string eventHubName,
                             AzureNamedKeyCredential credential,
                             EventProcessorOptions options = default) : base(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
 }
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="signature">The shared access signature on which to base the token.</param>
        ///
        public SharedAccessCredential(SharedAccessSignature signature)
        {
            Argument.AssertNotNull(signature, nameof(signature));

            _sharedAccessSignature = signature;
            _sourceKeyCredential   = null;
            _sourceSasCredential   = null;
        }
Esempio n. 5
0
        public void ConstructorWithSharedKeyCredentialValidatesOptions()
        {
            var token          = new AzureNamedKeyCredential("key", "value");
            var invalidOptions = new ServiceBusClientOptions {
                TransportType = ServiceBusTransportType.AmqpTcp, WebProxy = Mock.Of <IWebProxy>()
            };

            Assert.That(() => new ServiceBusClient("fullyQualifiedNamespace", token, invalidOptions), Throws.InstanceOf <ArgumentException>(), "The expanded argument constructor should validate client options");
        }
 public MockCheckpointStoreProcessor(CheckpointStore checkpointStore,
                                     int eventBatchMaximumCount,
                                     string consumerGroup,
                                     string fullyQualifiedNamespace,
                                     string eventHubName,
                                     AzureNamedKeyCredential credential,
                                     EventProcessorOptions options = default) : base(checkpointStore, eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
 }
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="sourceCredential">The <see cref="AzureSasCredential"/> to base signatures on.</param>
        ///
        public SharedAccessCredential(AzureSasCredential sourceCredential)
        {
            Argument.AssertNotNull(sourceCredential, nameof(sourceCredential));

            _sourceSasCredential = sourceCredential;
            _sourceKeyCredential = null;

            _sharedAccessSignature = new SharedAccessSignature(_sourceSasCredential.Signature);
        }
 /// <summary>
 ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
 /// </summary>
 ///
 /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
 /// <param name="credential">The <see cref="AzureNamedKeyCredential"/> to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
 /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
 ///
 public EventHubConnection(string fullyQualifiedNamespace,
                           string eventHubName,
                           AzureNamedKeyCredential credential,
                           EventHubConnectionOptions connectionOptions = default) : this(fullyQualifiedNamespace,
                                                                                         eventHubName,
                                                                                         TranslateNamedKeyCredential(credential, fullyQualifiedNamespace, eventHubName, connectionOptions?.TransportType),
                                                                                         connectionOptions)
 {
 }
Esempio n. 9
0
        public void ConstructorWithSharedKeyCredentialSetsTransportTypeFromOptions()
        {
            var token   = new AzureNamedKeyCredential("key", "value");
            var options = new ServiceBusClientOptions {
                TransportType = ServiceBusTransportType.AmqpWebSockets
            };
            var client = new ServiceBusClient("fullyQualifiedNamespace", token, options);

            Assert.That(client.TransportType, Is.EqualTo(options.TransportType));
        }
 /// <summary>
 ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
 /// </summary>
 ///
 /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="credential">The <see cref="AzureNamedKeyCredential"/> credential to use for authorization.  Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param>
 /// <param name="options">A set of options to apply when configuring the connection.</param>
 internal ServiceBusConnection(
     string fullyQualifiedNamespace,
     AzureNamedKeyCredential credential,
     ServiceBusClientOptions options)
     : this(
         fullyQualifiedNamespace,
         TranslateNamedKeyCredential(credential, fullyQualifiedNamespace, null, options.TransportType),
         options)
 {
 }
Esempio n. 11
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="sourceCredential">The <see cref="AzureNamedKeyCredential"/> to base signatures on.</param>
        /// <param name="signatureResource">The fully-qualified identifier for the resource to which this credential is intended to serve as authorization for.  This is also known as the "token audience" in some contexts.</param>
        ///
        public SharedAccessCredential(AzureNamedKeyCredential sourceCredential, string signatureResource)
        {
            Argument.AssertNotNull(sourceCredential, nameof(sourceCredential));
            Argument.AssertNotNullOrEmpty(signatureResource, nameof(signatureResource));

            _sourceKeyCredential = sourceCredential;
            _sourceSasCredential = null;

            var(name, key)         = sourceCredential;
            _sharedAccessSignature = new SharedAccessSignature(signatureResource, name, key);
        }
        private ServiceBusAdministrationClient CreateSharedKeyTokenClient()
        {
            var properties = ServiceBusConnectionStringProperties.Parse(GetConnectionString());
            var credential = new AzureNamedKeyCredential(properties.SharedAccessKeyName, properties.SharedAccessKey);

            return(InstrumentClient(
                       new ServiceBusAdministrationClient(
                           TestEnvironment.FullyQualifiedNamespace,
                           credential,
                           InstrumentClientOptions(new ServiceBusAdministrationClientOptions()))));
        }
Esempio n. 13
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="PluggableCheckpointStoreEventProcessor{TPartition}"/> class.
 /// </summary>
 ///
 /// <param name="checkpointStore">The provider of checkpoint and ownership data for the processor.</param>
 /// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed.  This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
 /// <param name="consumerGroup">The name of the consumer group the processor is associated with.  Events are read in the context of this group.</param>
 /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
 /// <param name="credential">The shared access key credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
 /// <param name="options">The set of options to use for the processor.</param>
 ///
 /// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
 ///
 protected PluggableCheckpointStoreEventProcessor(CheckpointStore checkpointStore,
                                                  int eventBatchMaximumCount,
                                                  string consumerGroup,
                                                  string fullyQualifiedNamespace,
                                                  string eventHubName,
                                                  AzureNamedKeyCredential credential,
                                                  EventProcessorOptions options = default) : base(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
     Argument.AssertNotNull(checkpointStore, nameof(checkpointStore));
     _checkpointStore = checkpointStore;
 }
Esempio n. 14
0
        public void AttributesCanBeReadWithDeconstruction()
        {
            var expectedName = "real-name";
            var expectedKey  = "real-key";
            var credential   = new AzureNamedKeyCredential(expectedName, expectedKey);

            var(name, key) = credential;

            Assert.AreEqual(expectedName, name);
            Assert.AreEqual(expectedKey, key);
        }
        public async Task ConnectionCanConnectToEventHubsUsingSharedKeyCredential()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var credential = new AzureNamedKeyCredential(EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);

                await using (var connection = new TestConnectionWithRetryPolicy(EventHubsTestEnvironment.Instance.FullyQualifiedNamespace, scope.EventHubName, credential))
                {
                    Assert.That(() => connection.GetPropertiesAsync(), Throws.Nothing);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        ///   Provides the invalid test cases for the constructor tests.
        /// </summary>
        ///
        public static IEnumerable <object[]> ConstructorSharedKeyCredentialArgumentInvalidCases()
        {
            var credential = new AzureNamedKeyCredential("name", "value");

            yield return(new object[] { null, credential });

            yield return(new object[] { "", credential });

            yield return(new object[] { "FakeNamespace", null });

            yield return(new object[] { "sb://fakenamspace.com", credential });
        }
        /// <summary>
        ///   Creates an <see cref="EventProcessorClient" /> that uses mock storage and
        ///   a connection based on an identity credential.
        /// </summary>
        ///
        /// <param name="consumerGroup">The consumer group for the processor.</param>
        /// <param name="eventHubName">The name of the Event Hub for the processor.</param>
        /// <param name="options">The set of client options to pass.</param>
        ///
        /// <returns>The processor instance.</returns>
        ///
        private EventProcessorClient CreateProcessorWithSharedAccessKey(string consumerGroup,
                                                                        string eventHubName,
                                                                        StorageManager storageManager = default,
                                                                        EventProcessorOptions options = default)
        {
            var credential = new AzureNamedKeyCredential(EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);

            EventHubConnection createConnection() => new EventHubConnection(EventHubsTestEnvironment.Instance.FullyQualifiedNamespace, eventHubName, credential);

            storageManager ??= new InMemoryStorageManager(_ => { });
            return(new TestEventProcessorClient(storageManager, consumerGroup, EventHubsTestEnvironment.Instance.FullyQualifiedNamespace, eventHubName, credential, createConnection, options));
        }
Esempio n. 18
0
 public async Task SendWithNamedKeyCredential()
 {
     await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
     {
         var properties = ServiceBusConnectionStringProperties.Parse(TestEnvironment.ServiceBusConnectionString);
         var credential = new AzureNamedKeyCredential(properties.SharedAccessKeyName, properties.SharedAccessKey);
         await using var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, credential, new ServiceBusClientOptions
         {
             TransportType = ServiceBusTransportType.AmqpWebSockets
         });
         var sender = client.CreateSender(scope.QueueName);
         await sender.SendMessageAsync(ServiceBusTestUtilities.GetMessage());
     }
 }
        public void KeyConstructorInitializesProperties()
        {
            var signature           = new SharedAccessSignature("hub-name", "keyName", "key");
            var sourceCredential    = new AzureNamedKeyCredential(signature.SharedAccessKeyName, signature.SharedAccessKey);
            var credential          = new SharedAccessCredential(sourceCredential, signature.Resource);
            var credentialSignature = GetSharedAccessSignature(credential);

            var(signatureKeyName, signatureKeyValue) = sourceCredential;

            Assert.That(credentialSignature.SharedAccessKeyName, Is.EqualTo(signatureKeyName), "The shared key name should match the source credential.");
            Assert.That(credentialSignature.SharedAccessKey, Is.EqualTo(signatureKeyValue), "The shared key should match the source credential.");
            Assert.That(GetSourceSasCredential(credential), Is.Null, "The source SAS credential should not be populated.");
            Assert.That(GetSourceKeyCredential(credential), Is.SameAs(sourceCredential), "The source key credential should match.");
        }
        public void SharedKeyCredentialConstructorSetsDelegatedProperties()
        {
            var expectedIdentifier = "Test-Identifier";
            var expectedNamespace  = "testns.namespace.com";
            var expectedEventHub   = "testHub";
            var credential         = new AzureNamedKeyCredential("key", "value");
            var options            = new EventHubBufferedProducerClientOptions {
                Identifier = expectedIdentifier
            };
            var producer = new EventHubBufferedProducerClient(expectedNamespace, expectedEventHub, credential, options);

            Assert.That(producer.Identifier, Is.EqualTo(expectedIdentifier), "The identifier should have been initialized.");
            Assert.That(producer.FullyQualifiedNamespace, Is.EqualTo(expectedNamespace), "The fully qualified namespace should have been initialized.");
            Assert.That(producer.EventHubName, Is.EqualTo(expectedEventHub), "The event hub name should have been initialized.");
        }
Esempio n. 21
0
        public void MultipleUpdatesCanBePerformed()
        {
            var expectedName = "expect_name";
            var expectedKey  = "expect_key";

            var credential = new AzureNamedKeyCredential("<< Name >>", "<< Key >>");

            credential.Update("interimname", "interimkey");
            credential.Update(expectedName, expectedKey);

            var(name, key) = credential;

            Assert.AreEqual(expectedName, credential.Name);
            Assert.AreEqual(expectedName, name);
            Assert.AreEqual(expectedKey, key);
        }
Esempio n. 22
0
        public void UpdateCanBePerformed()
        {
            var expectedName = "expect_name";
            var expectedKey  = "expect_key";

            #region Snippet:AzureNamedKeyCredential_Deconstruct
            var credential = new AzureNamedKeyCredential("SomeName", "SomeKey");
            /*@@*/
            /*@@*/ credential.Update(expectedName, expectedKey);
            /*@@*/
            (string name, string key) = credential;
            #endregion

            Assert.AreEqual(expectedName, credential.Name);
            Assert.AreEqual(expectedName, name);
            Assert.AreEqual(expectedKey, key);
        }
        public async Task SharedAccessKey()
        {
            await using var scope = await EventHubScope.CreateAsync(1);

            #region Snippet:EventHubs_Sample06_SharedAccessKey

#if SNIPPET
            var credential = new AzureNamedKeyCredential("<< SHARED KEY NAME >>", "<< SHARED KEY >>");

            var fullyQualifiedNamespace = "<< NAMESPACE (likely similar to {your-namespace}.servicebus.windows.net) >>";
            var eventHubName            = "<< NAME OF THE EVENT HUB >>";
#else
            var credential = new AzureNamedKeyCredential(EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);
            var fullyQualifiedNamespace = EventHubsTestEnvironment.Instance.FullyQualifiedNamespace;
            var eventHubName            = scope.EventHubName;
#endif

            var producer = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, credential);

            try
            {
                using EventDataBatch eventBatch = await producer.CreateBatchAsync();

                for (var index = 0; index < 5; ++index)
                {
                    var eventBody = new BinaryData($"Event #{ index }");
                    var eventData = new EventData(eventBody);

                    if (!eventBatch.TryAdd(eventData))
                    {
                        throw new Exception($"The event at { index } could not be added.");
                    }
                }

                await producer.SendAsync(eventBatch);
            }
            finally
            {
                await producer.CloseAsync();
            }

            #endregion
        }
        public void NamedKeyCredentialUpdatesAreRespected()
        {
            var updatedKeyName      = "updated-name";
            var updatedKey          = "updated-Key";
            var signature           = new SharedAccessSignature("hub-name", "keyName", "key");
            var sourceCredential    = new AzureNamedKeyCredential(signature.SharedAccessKeyName, signature.SharedAccessKey);
            var credential          = new SharedAccessCredential(sourceCredential, signature.Resource);
            var credentialSignature = GetSharedAccessSignature(credential);

            var(signatureKeyName, signatureKeyValue) = sourceCredential;

            Assert.That(credentialSignature.SharedAccessKeyName, Is.EqualTo(signatureKeyName), "The shared key name should match the source credential.");
            Assert.That(credentialSignature.SharedAccessKey, Is.EqualTo(signatureKeyValue), "The shared key should match the source credential.");

            sourceCredential.Update(updatedKeyName, updatedKey);
            _ = credential.GetToken(new TokenRequestContext(), CancellationToken.None);

            var newSignature = GetSharedAccessSignature(credential);

            Assert.That(newSignature.SharedAccessKeyName, Is.EqualTo(updatedKeyName));
            Assert.That(newSignature.SharedAccessKey, Is.EqualTo(updatedKey));
            Assert.That(newSignature.SignatureExpiration, Is.EqualTo(signature.SignatureExpiration).Within(TimeSpan.FromMinutes(5)));
        }
Esempio n. 25
0
 internal ReadableOptionsMock(string fullyQualifiedNamespace,
                              AzureNamedKeyCredential credential,
                              ServiceBusClientOptions clientOptions = default) : base(fullyQualifiedNamespace, credential, clientOptions)
 {
 }
Esempio n. 26
0
 public ObservableTransportClientMock(string fullyQualifiedNamespace,
                                      AzureNamedKeyCredential credential,
                                      ServiceBusClientOptions clientOptions = default) : base(fullyQualifiedNamespace, credential, clientOptions)
 {
 }
        public async Task SharedAccessKey()
        {
            await using var eventHubScope = await EventHubScope.CreateAsync(1);

            await using var storageScope = await StorageScope.CreateAsync();

            #region Snippet:EventHubs_Processor_Sample05_SharedAccessKey

            var storageConnectionString = "<< CONNECTION STRING FOR THE STORAGE ACCOUNT >>";
            var blobContainerName       = "<< NAME OF THE BLOB CONTAINER >>";
            /*@@*/
            /*@@*/ storageConnectionString = StorageTestEnvironment.Instance.StorageConnectionString;
            /*@@*/ blobContainerName       = storageScope.ContainerName;

            var credential = new AzureNamedKeyCredential("<< SHARED KEY NAME >>", "<< SHARED KEY >>");
            var fullyQualifiedNamespace = "<< NAMESPACE (likely similar to {your-namespace}.servicebus.windows.net) >>";
            var eventHubName            = "<< NAME OF THE EVENT HUB >>";
            var consumerGroup           = "<< NAME OF THE EVENT HUB CONSUMER GROUP >>";
            /*@@*/
            /*@@*/ fullyQualifiedNamespace = EventHubsTestEnvironment.Instance.FullyQualifiedNamespace;
            /*@@*/ eventHubName            = eventHubScope.EventHubName;
            /*@@*/ consumerGroup           = eventHubScope.ConsumerGroups.First();
            /*@@*/ credential = new AzureNamedKeyCredential(EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);

            var storageClient = new BlobContainerClient(
                storageConnectionString,
                blobContainerName);

            var processor = new EventProcessorClient(
                storageClient,
                consumerGroup,
                fullyQualifiedNamespace,
                eventHubName,
                credential);

            try
            {
                using var cancellationSource = new CancellationTokenSource();
                cancellationSource.CancelAfter(TimeSpan.FromSeconds(30));

                // The event handlers are not relevant for this sample; for
                // illustration, they're delegating the implementation to the
                // host application.

                processor.ProcessEventAsync += Application.ProcessorEventHandler;
                processor.ProcessErrorAsync += Application.ProcessorErrorHandler;

                try
                {
                    await processor.StartProcessingAsync(cancellationSource.Token);

                    await Task.Delay(Timeout.Infinite, cancellationSource.Token);
                }
                catch (TaskCanceledException)
                {
                    // This is expected if the cancellation token is
                    // signaled.
                }
                finally
                {
                    // This may take up to the length of time defined
                    // as part of the configured TryTimeout of the processor;
                    // by default, this is 60 seconds.

                    await processor.StopProcessingAsync();
                }
            }
            catch
            {
                // If this block is invoked, then something external to the
                // processor was the source of the exception.
            }
            finally
            {
                // It is encouraged that you unregister your handlers when you have
                // finished using the Event Processor to ensure proper cleanup.

                processor.ProcessEventAsync -= Application.ProcessorEventHandler;
                processor.ProcessErrorAsync -= Application.ProcessorErrorHandler;
            }

            #endregion
        }
Esempio n. 28
0
        public void UpdateValidatesTheKey(string key, Type expectedExceptionType)
        {
            var credential = new AzureNamedKeyCredential("initial-name", "initial-key");

            Assert.Throws(expectedExceptionType, () => credential.Update("name", key));
        }
Esempio n. 29
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="IdempotentProducer" /> class.
 /// </summary>
 ///
 /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="eventHubName">The name of the specific Event Hub to associate the producer with.</param>
 /// <param name="credential">The shared access key credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
 /// <param name="clientOptions">A set of options to apply when configuring the producer.</param>
 ///
 public IdempotentProducer(string fullyQualifiedNamespace,
                           string eventHubName,
                           AzureNamedKeyCredential credential,
                           IdempotentProducerOptions clientOptions = default) : base(fullyQualifiedNamespace, eventHubName, credential, clientOptions.ToCoreOptions())
 {
 }
        public void KeyCredentialConstructorValidatesTheResource(string resource)
        {
            var credential = new AzureNamedKeyCredential("name", "key");

            Assert.That(() => new SharedAccessCredential(credential, resource), Throws.InstanceOf <ArgumentException>());
        }