Esempio n. 1
0
        public async Task MessageActivityWithHttpClient()
        {
            // Arrange
            var headerDictionaryMock = new Mock <IHeaderDictionary>();

            headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null);

            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream());
            httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object);

            var httpResponseMock = new Mock <HttpResponse>();

            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(CreateInternalHttpResponse()));

            var httpClient = new HttpClient(mockHttpMessageHandler.Object);

            var bot = new MessageBot();

            // Act
            var cloudEnvironment = BotFrameworkAuthenticationFactory.Create(null, false, null, null, null, null, null, null, null, new PasswordServiceClientCredentialFactory(), new AuthenticationConfiguration(), httpClient, null);
            var adapter          = new CloudAdapter(cloudEnvironment);
            await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot);

            // Assert
            mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Once(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());
        }
Esempio n. 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConfigurationAdaptiveDialogBot"/> class using <see cref="IConfiguration"/>.
 /// </summary>
 /// <param name="configuration">An <see cref="IConfiguration"/> instance.</param>
 /// <param name="resourceExplorer">The Bot Builder <see cref="ResourceExplorer"/> to load the <see cref="AdaptiveDialog"/> from.</param>
 /// <param name="conversationState">The <see cref="ConversationState"/> implementation to use for this <see cref="AdaptiveDialog"/>.</param>
 /// <param name="userState">The <see cref="UserState"/> implementation to use for this <see cref="AdaptiveDialog"/>.</param>
 /// <param name="skillConversationIdFactoryBase">The <see cref="SkillConversationIdFactoryBase"/> implementation to use for this <see cref="AdaptiveDialog"/>.</param>
 /// <param name="botFrameworkAuthentication">A <see cref="BotFrameworkAuthentication"/> for making calls to Bot Builder Skills.</param>
 /// <param name="scopes">A set of <see cref="MemoryScope"/> that will be added to the <see cref="ITurnContext"/>.</param>
 /// <param name="pathResolvers">A set of <see cref="IPathResolver"/> that will be added to the <see cref="ITurnContext"/>.</param>
 /// <param name="dialogs">Custom <see cref="Dialog"/> that will be added to the root DialogSet.</param>
 /// <param name="logger">An <see cref="ILogger"/> instance.</param>
 public ConfigurationAdaptiveDialogBot(
     IConfiguration configuration,
     ResourceExplorer resourceExplorer,
     ConversationState conversationState,
     UserState userState,
     SkillConversationIdFactoryBase skillConversationIdFactoryBase,
     BotFrameworkAuthentication botFrameworkAuthentication = null,
     IEnumerable <MemoryScope> scopes          = default,
     IEnumerable <IPathResolver> pathResolvers = default,
     IEnumerable <Dialog> dialogs = default,
     ILogger logger = null)
     : base(
         configuration.GetSection(ConfigurationConstants.RootDialogKey).Value,
         configuration.GetSection(ConfigurationConstants.LanguageGeneratorKey).Value ?? DefaultLanguageGeneratorId,
         configuration.GetSection(ConfigurationConstants.DefaultLocaleKey).Value ?? DefaultLocale,
         resourceExplorer,
         conversationState,
         userState,
         skillConversationIdFactoryBase,
         botFrameworkAuthentication ?? BotFrameworkAuthenticationFactory.Create(),
         scopes ?? Enumerable.Empty <MemoryScope>(),
         pathResolvers ?? Enumerable.Empty <IPathResolver>(),
         dialogs ?? Enumerable.Empty <Dialog>(),
         logger: logger ?? NullLogger <AdaptiveDialogBot> .Instance)
 {
 }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationBotFrameworkAuthentication"/> class.
        /// </summary>
        /// <param name="configuration">An IConfiguration instance.</param>
        /// <param name="credentialsFactory">An IServiceClientCredentialsFactory instance.</param>
        /// <param name="authConfiguration">An AuthenticationConfiguration instance.</param>
        /// <param name="httpClient">A custom HttpClient to use.</param>
        /// <param name="logger">The ILogger instance to use.</param>
        public ConfigurationBotFrameworkAuthentication(IConfiguration configuration, ServiceClientCredentialsFactory credentialsFactory = null, AuthenticationConfiguration authConfiguration = null, HttpClient httpClient = null, ILogger logger = null)
        {
            var channelService              = configuration.GetSection("ChannelService")?.Value;
            var validateAuthority           = configuration.GetSection("ValidateAuthority")?.Value;
            var toChannelFromBotLoginUrl    = configuration.GetSection("ToChannelFromBotLoginUrl")?.Value;
            var toChannelFromBotOAuthScope  = configuration.GetSection("ToChannelFromBotOAuthScope")?.Value;
            var toBotFromChannelTokenIssuer = configuration.GetSection("ToBotFromChannelTokenIssuer")?.Value;
            var oAuthUrl = configuration.GetSection("OAuthUrl")?.Value;
            var toBotFromChannelOpenIdMetadataUrl  = configuration.GetSection("ToBotFromChannelOpenIdMetadataUrl")?.Value;
            var toBotFromEmulatorOpenIdMetadataUrl = configuration.GetSection("ToBotFromEmulatorOpenIdMetadataUrl")?.Value;
            var callerId = configuration.GetSection("CallerId")?.Value;

            _inner = BotFrameworkAuthenticationFactory.Create(
                channelService,
                bool.Parse(validateAuthority ?? "true"),
                toChannelFromBotLoginUrl,
                toChannelFromBotOAuthScope,
                toBotFromChannelTokenIssuer,
                oAuthUrl,
                toBotFromChannelOpenIdMetadataUrl,
                toBotFromEmulatorOpenIdMetadataUrl,
                callerId,
                credentialsFactory ?? new ConfigurationServiceClientCredentialFactory(configuration),
                authConfiguration ?? new AuthenticationConfiguration(),
                httpClient,
                logger);
        }
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationBotFrameworkAuthentication"/> class.
        /// </summary>
        /// <param name="credentialsFactory">An IServiceClientCredentialsFactory instance.</param>
        /// <param name="authConfiguration">An AuthenticationConfiguration instance.</param>
        /// <param name="httpClient">A custom HttpClient to use.</param>
        /// <param name="logger">The ILogger instance to use.</param>
        public ConfigurationBotFrameworkAuthentication(ServiceClientCredentialsFactory credentialsFactory = null, AuthenticationConfiguration authConfiguration = null, HttpClient httpClient = null, ILogger logger = null)
        {
            var channelService              = ConfigurationManager.AppSettings["ChannelService"];
            var validateAuthority           = ConfigurationManager.AppSettings["ValidateAuthority"];
            var toChannelFromBotLoginUrl    = ConfigurationManager.AppSettings["ToChannelFromBotLoginUrl"];
            var toChannelFromBotOAuthScope  = ConfigurationManager.AppSettings["ToChannelFromBotOAuthScope"];
            var toBotFromChannelTokenIssuer = ConfigurationManager.AppSettings["ToBotFromChannelTokenIssuer"];
            var oAuthUrl = ConfigurationManager.AppSettings["OAuthUrl"];
            var toBotFromChannelOpenIdMetadataUrl  = ConfigurationManager.AppSettings["ToBotFromChannelOpenIdMetadataUrl"];
            var toBotFromEmulatorOpenIdMetadataUrl = ConfigurationManager.AppSettings["ToBotFromEmulatorOpenIdMetadataUrl"];
            var callerId = ConfigurationManager.AppSettings["CallerId"];

            _inner = BotFrameworkAuthenticationFactory.Create(
                channelService,
                bool.Parse(validateAuthority ?? "true"),
                toChannelFromBotLoginUrl,
                toChannelFromBotOAuthScope,
                toBotFromChannelTokenIssuer,
                oAuthUrl,
                toBotFromChannelOpenIdMetadataUrl,
                toBotFromEmulatorOpenIdMetadataUrl,
                callerId,
                credentialsFactory ?? new ConfigurationServiceClientCredentialFactory(),
                authConfiguration ?? new AuthenticationConfiguration(),
                httpClient,
                logger);
        }
Esempio n. 5
0
        //Dirty hack to get reference to OnTurn in component start

        public BotWithLookup(
            IConfiguration configuration,
            ResourceExplorer resourceExplorer,
            ConversationState conversationState,
            UserState userState,
            SkillConversationIdFactoryBase skillConversationIdFactoryBase,
            LanguagePolicy languagePolicy,
            BotFrameworkAuthentication botFrameworkAuthentication = null,
            IBotTelemetryClient telemetryClient       = null,
            IEnumerable <MemoryScope> scopes          = default,
            IEnumerable <IPathResolver> pathResolvers = default,
            IEnumerable <Dialog> dialogs = default,
            ILogger logger = null)
            : base(
                configuration.GetSection("defaultRootDialog").Value,
                configuration.GetSection("defaultLg").Value ?? "main.lg",
                resourceExplorer,
                conversationState,
                userState,
                skillConversationIdFactoryBase,
                languagePolicy,
                botFrameworkAuthentication ?? BotFrameworkAuthenticationFactory.Create(),
                telemetryClient ?? new NullBotTelemetryClient(),
                scopes ?? Enumerable.Empty <MemoryScope>(),
                pathResolvers ?? Enumerable.Empty <IPathResolver>(),
                dialogs ?? Enumerable.Empty <Dialog>(),
                logger: logger ?? NullLogger <AdaptiveDialogBot> .Instance)
        {
            OnTurn = OnTurn ?? this.OnTurnAsync;
        }
Esempio n. 6
0
        public async Task AuthenticateSetsAnonymousSkillClaim()
        {
            var sut = new TestCloudChannelServiceHandler(BotFrameworkAuthenticationFactory.Create());
            await sut.HandleReplyToActivityAsync(null, "123", "456", new Activity(), CancellationToken.None);

            Assert.Equal(AuthenticationConstants.AnonymousAuthType, sut.ClaimsIdentity.AuthenticationType);
            Assert.Equal(AuthenticationConstants.AnonymousSkillAppId, JwtTokenValidation.GetAppIdFromClaims(sut.ClaimsIdentity.Claims));
        }
        public async Task AddBotRuntimeSkills(object settings, string appId, Type exceptionType)
        {
            // Setup
            IServiceCollection services = new ServiceCollection();

            services.AddSingleton <IStorage, MemoryStorage>();
            services.AddSingleton <SkillConversationIdFactoryBase, SkillConversationIdFactory>();
            services.AddSingleton(sp => BotFrameworkAuthenticationFactory.Create());
            services.AddSingleton <BotAdapter, CloudAdapter>();
            services.AddSingleton <IBot, ActivityHandler>();

            var            skillSettings = settings as SkillSettings;
            IConfiguration configuration = new ConfigurationBuilder().AddRuntimeSettings(new RuntimeSettings()
            {
                Skills = skillSettings
            }).Build();

            // Test
            services.AddBotRuntimeSkills(configuration);

            // Assert
            var provider = services.BuildServiceProvider();

            Assertions.AssertService <SkillConversationIdFactoryBase, SkillConversationIdFactory>(services, provider, ServiceLifetime.Singleton);
            Assertions.AssertService <ChannelServiceHandlerBase, CloudSkillHandler>(services, provider, ServiceLifetime.Singleton);
            Assertions.AssertService <AuthenticationConfiguration>(
                services,
                provider,
                ServiceLifetime.Singleton,
                async authConfig =>
            {
                var versionClaim = new Claim(AuthenticationConstants.VersionClaim, "1.0");
                var appIdClaim   = new Claim(AuthenticationConstants.AppIdClaim, appId);

                if (exceptionType == null)
                {
                    await authConfig.ClaimsValidator.ValidateClaimsAsync(new Claim[] { versionClaim, appIdClaim });
                }
                else
                {
                    await Assert.ThrowsAsync(exceptionType, () => authConfig.ClaimsValidator.ValidateClaimsAsync(new Claim[] { versionClaim, appIdClaim }));
                }
            });

            await Task.CompletedTask;
        }
Esempio n. 8
0
        public async Task MethodNotAllowed(string httpMethod)
        {
            // Arrange
            var headerDictionaryMock = new Mock <IHeaderDictionary>();

            headerDictionaryMock.Setup(h => h[It.Is <string>(v => v == "Authorization")]).Returns <string>(null);

            var webSocketManagerMock = new Mock <WebSocketManager>();

            webSocketManagerMock.Setup(w => w.IsWebSocketRequest).Returns(false);
            var httpContextMock = new Mock <HttpContext>();

            httpContextMock.Setup(c => c.WebSockets).Returns(webSocketManagerMock.Object);
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(r => r.Method).Returns(httpMethod);
            httpRequestMock.Setup(r => r.Body).Returns(CreateMessageActivityStream());
            httpRequestMock.Setup(r => r.Headers).Returns(headerDictionaryMock.Object);
            httpRequestMock.Setup(r => r.HttpContext).Returns(httpContextMock.Object);

            var httpResponseMock = new Mock <HttpResponse>().SetupAllProperties();

            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .Returns((HttpRequestMessage request, CancellationToken cancellationToken) => Task.FromResult(CreateInternalHttpResponse()));

            var httpClient = new HttpClient(mockHttpMessageHandler.Object);

            var httpClientFactoryMock = new Mock <IHttpClientFactory>();

            httpClientFactoryMock.Setup(cf => cf.CreateClient(It.IsAny <string>())).Returns(httpClient);

            var bot = new MessageBot();

            // Act
            var cloudEnvironment = BotFrameworkAuthenticationFactory.Create(null, false, null, null, null, null, null, null, null, new PasswordServiceClientCredentialFactory(), new AuthenticationConfiguration(), httpClientFactoryMock.Object, null);
            var adapter          = new CloudAdapter(cloudEnvironment);
            await adapter.ProcessAsync(httpRequestMock.Object, httpResponseMock.Object, bot);

            // Assert
            Assert.Equal((int)HttpStatusCode.MethodNotAllowed, httpResponseMock.Object.StatusCode);
            mockHttpMessageHandler.Protected().Verify <Task <HttpResponseMessage> >("SendAsync", Times.Never(), ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>());
        }
        public async Task CreatesBotFrameworkClient()
        {
            // Arrange
            string fromBotId = "from-bot-id";
            string toBotId   = "to-bot-id";
            string loginUrl  = AuthenticationConstants.ToChannelFromBotLoginUrlTemplate;
            Uri    toUrl     = new Uri("http://test1.com/test");

            var credentialFactoryMock = new Mock <ServiceClientCredentialsFactory>();

            credentialFactoryMock.Setup(cssf => cssf.CreateCredentialsAsync(
                                            It.Is <string>(v => v == fromBotId),
                                            It.Is <string>(v => v == toBotId),
                                            It.Is <string>(v => v == loginUrl),
                                            It.IsAny <bool>(),
                                            It.IsAny <CancellationToken>())).ReturnsAsync(MicrosoftAppCredentials.Empty);

            var responseMessage = new HttpResponseMessage(HttpStatusCode.OK);

            responseMessage.Content = new StringContent("{ \"hello\": \"world\" }");

            var mockHttpMessageHandler = new Mock <HttpMessageHandler>();

            mockHttpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.Is <HttpRequestMessage>(hrm => hrm.RequestUri == toUrl), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(responseMessage);

            var client = new HttpClient(mockHttpMessageHandler.Object);
            var httpClientFactoryMock = new Mock <IHttpClientFactory>();

            httpClientFactoryMock.Setup(hcf => hcf.CreateClient(It.IsAny <string>())).Returns(client);

            var bfa = BotFrameworkAuthenticationFactory.Create(
                channelService: null,
                validateAuthority: true,
                toChannelFromBotLoginUrl: null,
                toChannelFromBotOAuthScope: null,
                toBotFromChannelTokenIssuer: null,
                oAuthUrl: null,
                toBotFromChannelOpenIdMetadataUrl: null,
                toBotFromEmulatorOpenIdMetadataUrl: null,
                callerId: null,
                credentialFactoryMock.Object,
                new AuthenticationConfiguration(),
                httpClientFactoryMock.Object,
                NullLogger.Instance);

            Uri    serviceUrl     = new Uri("http://root-bot/service-url");
            string conversationId = "conversation-id";
            var    activity       = new Activity
            {
                ChannelId    = "channel-id",
                ServiceUrl   = "service-url",
                Locale       = "locale",
                Conversation = new ConversationAccount
                {
                    Id   = "conversationiid",
                    Name = "conversation-name"
                }
            };

            // Act
            var bfc            = bfa.CreateBotFrameworkClient();
            var invokeResponse = await bfc.PostActivityAsync(fromBotId, toBotId, toUrl, serviceUrl, conversationId, activity);

            // Assert
            Assert.Equal("world", ((JObject)invokeResponse.Body)["hello"].ToString());
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudAdapter"/> class. (Public cloud. No auth. For testing.)
 /// </summary>
 public CloudAdapter()
     : this(BotFrameworkAuthenticationFactory.Create())
 {
 }
Esempio n. 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CloudAdapter"/> class. (Public cloud. No auth. For testing.)
 /// </summary>
 public CloudAdapter()
     : this(BotFrameworkAuthenticationFactory.Create(null, false, null, null, null, null, null, null, null, new PasswordServiceClientCredentialFactory(), new AuthenticationConfiguration(), null, null))
 {
 }