Exemple #1
0
        public void TryGetSpecialSourceClaim_Subject_Test()
        {
            // ReSharper disable ConvertToUsingDeclaration
            using (var certificate = this.GetCertificate())
            {
                using (var loggerFactory = new LoggerFactoryMock())
                {
                    var httpContextAccessor = new HttpContextAccessor
                    {
                        HttpContext = new DefaultHttpContext
                        {
                            Connection = { ClientCertificate = certificate }
                        }
                    };
                    const string source = "Certificate.Subject";

                    var certificateAuthenticationDecorator = this.CreateCertificateAuthenticationDecorator(httpContextAccessor, loggerFactory);

                    Assert.IsTrue(certificateAuthenticationDecorator.TryGetSpecialSourceClaim(new ClaimsPrincipal(), source, out var claim));
                    Assert.AreEqual(source, claim.Type);
                    Assert.AreEqual("CN=Unit-test-certificate", claim.Value);
                }
            }
            // ReSharper restore ConvertToUsingDeclaration
        }
        internal static IServiceCollection GetInitialServiceCollection()
        {
            var serviceCollection = new ServiceCollection();

            // Default server services.
            serviceCollection.AddSingleton(Environment);
            serviceCollection.AddSingleton <IHostEnvironment>(Environment);
            serviceCollection.AddSingleton <IHostApplicationLifetime, ApplicationLifetime>();

            serviceCollection.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            serviceCollection.AddTransient <IHttpContextFactory, DefaultHttpContextFactory>();
            serviceCollection.AddScoped <IMiddlewareFactory, MiddlewareFactory>();
            serviceCollection.AddOptions();

            serviceCollection.AddSingleton <ILoggerFactory>(LoggerFactoryMock.Create());
            serviceCollection.AddLogging();

            serviceCollection.AddSingleton(ServerTestConfiguration.Global.Configuration);

            var diagnosticListener = new DiagnosticListener(TestFramework.TestFrameworkName);

            serviceCollection.AddSingleton(diagnosticListener);
            serviceCollection.AddSingleton <DiagnosticSource>(diagnosticListener);

            serviceCollection.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            serviceCollection.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            // Test services.
            serviceCollection.AddRoutingServices();

            return(serviceCollection);
        }
        private static IServiceCollection GetInitialServiceCollection()
        {
            var serviceCollection   = new ServiceCollection();
            var diagnosticSource    = new DiagnosticListener(TestFrameworkName);
            var applicationLifetime = new ApplicationLifetime();

            // default server services
            serviceCollection.AddSingleton(Environment);
            serviceCollection.AddSingleton <IApplicationLifetime>(applicationLifetime);

            serviceCollection.AddSingleton <ILoggerFactory>(LoggerFactoryMock.Create());
            serviceCollection.AddLogging();

            serviceCollection.AddTransient <IApplicationBuilderFactory, ApplicationBuilderFactory>();
            serviceCollection.AddTransient <IHttpContextFactory, HttpContextFactory>();
            serviceCollection.AddOptions();

            serviceCollection.AddSingleton <DiagnosticSource>(diagnosticSource);
            serviceCollection.AddSingleton(diagnosticSource);

            serviceCollection.AddTransient <IStartupFilter, AutoRequestServicesStartupFilter>();
            serviceCollection.AddTransient <IServiceProviderFactory <IServiceCollection>, DefaultServiceProviderFactory>();

            serviceCollection.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();

            return(serviceCollection);
        }
        public When_starting_the_projector_with_a_projection_that_throws_an_exception()
        {
            _loggerFactoryMock = new LoggerFactoryMock();
            _expectedException = new FeedProjectionException("error1");

            _sut = new FeedProjector <FeedProjectorTestContext>(
                () => new Mock <Owned <FeedProjectorTestContext> >().Object,
                _loggerFactoryMock,
                new [] { new FailingRunner(_expectedException) });
        }
        public async Task GetRolesAsync_IfTheUserPrincipalNameIsInvalid_ShouldReturnNoRoles()
        {
            using (var loggerFactory = new LoggerFactoryMock())
            {
                var claimsPrincipalHelper = new ClaimsPrincipalHelper();
                var windowsRoleProvider   = new WindowsRoleProvider(await this.CreateMemoryCacheAsync(), claimsPrincipalHelper, loggerFactory, await this.CreateOptionsMonitorAsync());
                var principal             = await this.CreatePrincipalAsync("Invalid-user-principal-name", claimsPrincipalHelper.UserPrincipalNameClaimTypes.ToArray());

                var roles = (await windowsRoleProvider.GetRolesAsync(principal)).ToArray();
                Assert.IsFalse(roles.Any());
            }
        }
        public void GetSourceClaim_IfThePrincipalParameterDoesNotContainAClaimWithTheSourceAsClaimType_ShouldReturnNull()
        {
            // ReSharper disable ConvertToUsingDeclaration
            using (var loggerFactory = new LoggerFactoryMock())
            {
                const string claimType             = "Test";
                var          includeClaimDecorator = this.CreateIncludeClaimDecorator(loggerFactory);

                var claim = includeClaimDecorator.GetSourceClaim(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(claimType, string.Empty), })), "Another");

                Assert.IsNull(claim);
            }
            // ReSharper restore ConvertToUsingDeclaration
        }
Exemple #7
0
        public async Task TestServerFailedConnect()
        {
            var loggerFactoryMock = new LoggerFactoryMock();

            await using var wscli = new HassClient(loggerFactoryMock);
            bool result = await wscli.ConnectAsync(new Uri("ws://127.0.0.1:5001/api/websocket_not_exist"),
                                                   "ABCDEFGHIJKLMNOPQ");

            Assert.False(result);
            Assert.True(loggerFactoryMock.LoggedError);
            Assert.True(loggerFactoryMock.LoggedDebug);
            Assert.False(loggerFactoryMock.LoggedTrace);
            await wscli.CloseAsync();
        }
        public async Task GetRolesAsync_IfTheUserPrincipalNameIsInvalid_ShouldLogAnError()
        {
            using (var loggerFactory = new LoggerFactoryMock())
            {
                var windowsRoleProvider = await this.CreateWindowsRoleProviderAsync(loggerFactory);

                var principal = await this.CreatePrincipalAsync("Invalid-user-principal-name", ClaimTypes.Upn);

                await windowsRoleProvider.GetRolesAsync(principal);

                var log = loggerFactory.Logs.First();
                Assert.AreEqual(LogLevel.Error, log.LogLevel);
                Assert.AreEqual("Could not get windows-roles for user-principal-name \"Invalid-user-principal-name\".", log.Message);
            }
        }
        public async Task GetRolesAsync_IfThereAreMultipelUserPrincipalNameClaims_ShouldLog()
        {
            using (var loggerFactory = new LoggerFactoryMock())
            {
                var claimsPrincipalHelper = new ClaimsPrincipalHelper();
                var windowsRoleProvider   = new WindowsRoleProvider(await this.CreateMemoryCacheAsync(), claimsPrincipalHelper, loggerFactory, await this.CreateOptionsMonitorAsync());
                var principal             = await this.CreatePrincipalAsync("Invalid-user-principal-name", claimsPrincipalHelper.UserPrincipalNameClaimTypes.ToArray());

                await windowsRoleProvider.GetRolesAsync(principal);

                var log = loggerFactory.Logs.First();
                Assert.AreEqual(LogLevel.Warning, log.LogLevel);
                Assert.AreEqual("Multiple claims were found. The following claims were found: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn: Invalid-user-principal-name, upn: Invalid-user-principal-name", log.Message);
            }
        }
Exemple #10
0
        private static (Logger, LoggerFactoryMock) CreateLoggerFactoryMock(out MicrosoftILoggerTarget target)
        {
            var logFactory        = new LogFactory();
            var logConfig         = new Config.LoggingConfiguration();
            var loggerFactoryMock = new LoggerFactoryMock();

            target = new MicrosoftILoggerTarget(loggerFactoryMock)
            {
                Layout = "${message}"
            };
            logConfig.AddRuleForAllLevels(target);
            logFactory.Configuration = logConfig;
            var logger = logFactory.GetCurrentClassLogger();

            return(logger, loggerFactoryMock);
        }
        public void OneTimeSetUp()
        {
            Setup.Bootstrap(SetupType.Test);

            ApiClientMock              = new ApiClientMock();
            CatServiceMock             = new CatServiceMock();
            MessageBrokerMock          = new MessageBrokerMock <Cat>();
            MessageConsumerMock        = new MessageConsumerMock <Cat>();
            MessageConsumerServiceMock = new MessageServiceMock <Cat>();
            LoggerFactoryMock          = new LoggerFactoryMock();

            CatService      = new CatService(MessageBrokerMock.Instance, ApiClientMock.Instance);
            MessageConsumer = new MessageConsumer <Cat>(ApiClientMock.Instance, LoggerFactoryMock.Instance);
            MessageService  = new MessageService <Cat>(MessageBrokerMock.Instance, MessageConsumerMock.Instance, LoggerFactoryMock.Instance);
            ViewModel       = new MainViewModel(CatServiceMock.Instance);
        }
        public When_starting_the_projector_with_a_multiple_failing_projections_and_an_infinte_projection()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            _loggerFactoryMock       = new LoggerFactoryMock();
            _firstExpectedException  = new FeedProjectionException("error1");
            _secondExpectedException = new FeedProjectionException("error2");

            _sut = new FeedProjector <FeedProjectorTestContext>(
                () => new Mock <Owned <FeedProjectorTestContext> >().Object,
                _loggerFactoryMock,
                new IFeedProjectionRunner <FeedProjectorTestContext>[]
            {
                new FailingRunner(_secondExpectedException, TimeSpan.FromMilliseconds(300)),
                new InfiniteRunner(),
                new FailingRunner(_firstExpectedException, TimeSpan.FromMilliseconds(50)),
            });
        }
Exemple #13
0
 public UnitTestContext(AuthenticationScheme authenticationScheme, Action <CertificateAuthenticationOptions> certificateAuthenticationOptionsConfigurer, HttpContextMock httpContext, LoggerFactoryMock loggerFactory, SystemClockMock systemClock, UrlEncoder urlEncoder)
 {
     this.AuthenticationScheme = authenticationScheme ?? throw new ArgumentNullException(nameof(authenticationScheme));
     this.CertificateAuthenticationOptionsMonitor = new OptionsMonitorMock <CertificateAuthenticationOptions>(certificateAuthenticationOptionsConfigurer);
     this.HttpContext   = httpContext ?? throw new ArgumentNullException(nameof(httpContext));
     this.LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
     this.SystemClock   = systemClock ?? throw new ArgumentNullException(nameof(systemClock));
     this.UrlEncoder    = urlEncoder ?? throw new ArgumentNullException(nameof(urlEncoder));
 }
 protected internal virtual async Task <WindowsRoleProvider> CreateWindowsRoleProviderAsync(LoggerFactoryMock loggerFactory, ExtendedAuthorizationOptions options = null)
 {
     return(await Task.FromResult(new WindowsRoleProvider(await this.CreateMemoryCacheAsync(), new ClaimsPrincipalHelper(), loggerFactory, await this.CreateOptionsMonitorAsync(options))));
 }
        protected internal virtual async Task GetRolesAsyncTest(bool builtInRolesEnabled, string domain, string errorMessage, bool machineRolesEnabled, IPrincipal principal, IdentityReferenceCollection windowsGroups)
        {
            if (domain == null)
            {
                throw new ArgumentNullException(nameof(domain));
            }

            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            if (windowsGroups == null)
            {
                throw new ArgumentNullException(nameof(windowsGroups));
            }

            var options = new ExtendedAuthorizationOptions
            {
                Roles =
                {
                    Windows                 =
                    {
                        BuiltInRolesEnabled = builtInRolesEnabled,
                        MachineRolesEnabled = machineRolesEnabled
                    }
                }
            };

            var expectedRoles = windowsGroups.AsRoles(options.Roles.Windows);

            using (var loggerFactory = new LoggerFactoryMock())
            {
                var windowsRoleProvider = await this.CreateWindowsRoleProviderAsync(loggerFactory, options);

                var roles = (await windowsRoleProvider.GetRolesAsync(principal)).ToArray();
                Assert.AreEqual(expectedRoles.Count, roles.Length, errorMessage);

                for (var i = 0; i < roles.Length; i++)
                {
                    var role = roles[i];

                    // ReSharper disable All
                    if (!builtInRolesEnabled && !machineRolesEnabled)
                    {
                        Assert.IsTrue(role.StartsWith($"{domain}\\", StringComparison.OrdinalIgnoreCase), errorMessage);
                    }
                    else if (builtInRolesEnabled && !machineRolesEnabled)
                    {
                        Assert.IsFalse(role.StartsWith(Environment.MachineName, StringComparison.OrdinalIgnoreCase), errorMessage);
                    }
                    else if (!builtInRolesEnabled && machineRolesEnabled)
                    {
                        Assert.IsTrue(role.StartsWith($"{domain}\\", StringComparison.OrdinalIgnoreCase) || role.StartsWith(Environment.MachineName, StringComparison.OrdinalIgnoreCase), errorMessage);
                    }
                    // ReSharper restore All

                    Assert.AreEqual(expectedRoles.ElementAt(i), role, errorMessage);
                }
            }
        }
 public void MessageConsumerService_NewInstance_Successful()
 {
     MessageService.Should().NotBeNull();
     LoggerFactoryMock.Verify();
 }
Exemple #17
0
 public Helper()
 {
     LoggerFactoryMock.Setup(f => f.CreateLogger(It.IsAny <string>()))
     .Returns(new Mock <ILogger <Application> >().Object);
 }