public void Setup() { options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "OneStopShopDatabase") .Options; //...Setup the mock as needed mockEnvironment .Setup(m => m.EnvironmentName) .Returns("Hosting:UnitTestEnvironment"); entities = new List <Blogs>(); using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); var blogsController = new BlogsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); if (context.Blogs == null || context.Blogs.CountAsync().Result == 0) { context.Blogs.Add(new Blogs { BlogId = 1, BlogTitle = "Title File", BlogCreatedDate = DateTime.Now, BlogDescription = "blog Description", StoreId = 1 }); context.SaveChanges(); } } }
private static TokenManager GetTokenManager() { var options = CreateOptions(); var claimsManager = CreateClaimsManager(options); var factory = new LoggerFactory(); var protector = new EphemeralDataProtectionProvider(factory).CreateProtector("test"); var codeSerializer = new TokenDataSerializer <AuthorizationCode>(options, ArrayPool <char> .Shared); var codeDataFormat = new SecureDataFormat <AuthorizationCode>(codeSerializer, protector); var refreshTokenSerializer = new TokenDataSerializer <RefreshToken>(options, ArrayPool <char> .Shared); var refreshTokenDataFormat = new SecureDataFormat <RefreshToken>(refreshTokenSerializer, protector); var timeStampManager = new TimeStampManager(); var credentialsPolicy = GetCredentialsPolicy(options, timeStampManager); var codeIssuer = new AuthorizationCodeIssuer(claimsManager, codeDataFormat, new ProtocolErrorProvider()); var accessTokenIssuer = new JwtAccessTokenIssuer(claimsManager, credentialsPolicy, new JwtSecurityTokenHandler(), options); var idTokenIssuer = new JwtIdTokenIssuer(claimsManager, credentialsPolicy, new JwtSecurityTokenHandler(), options); var refreshTokenIssuer = new RefreshTokenIssuer(claimsManager, refreshTokenDataFormat); return(new TokenManager( codeIssuer, accessTokenIssuer, idTokenIssuer, refreshTokenIssuer, new ProtocolErrorProvider())); }
public TestState() { Mock <IGetPersonalProfileDependencies> dependencies = new Mock <IGetPersonalProfileDependencies>(); Mock <IHttpContextAccessor> httpContextAccessor = new Mock <IHttpContextAccessor>(); Mock <IHeaderDictionary> headerDictionary = new Mock <IHeaderDictionary>(); httpContextAccessor.Setup(a => a.HttpContext.Request.Headers) .Returns(headerDictionary.Object); IDataProtectionProvider provider = new EphemeralDataProtectionProvider(); _protector = provider.CreateProtector("PersonalProfile.Protector"); dependencies.Setup(a => a.GetUserId(Username)) .Returns(Task.FromResult(UserIdEntity.Create(Username, UserId))); dependencies.Setup(a => a.GetPersonalProfile(UserId)) .Returns(Task.FromResult(GetPersonalProfileEntity(UserId))); dependencies.Setup(a => a.GetSkills(UserId)) .Returns(Task.FromResult(GetSkills(UserId))); dependencies.Setup(a => a.GetInterests(UserId)) .Returns(Task.FromResult(GetInterests(UserId))); _dependencies = dependencies; Subject = new PersonalProfile(_dependencies.Object, provider, httpContextAccessor.Object); }
public void Index_GetStores() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); storeController = new StoresController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = storeController.Index(); resultTask.Wait(); var model = (List <Store>)((ViewResult)resultTask.Result).Model; Assert.AreEqual(1, model.Count); } }
public void Index_NotFound_By_StoreId() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); blogsController = new BlogsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = blogsController.Index(); resultTask.Wait(); var response = resultTask.Result as NotFoundResult; Assert.AreEqual((int)HttpStatusCode.NotFound, response.StatusCode); } }
public void Product_NotFound_By_ProductId() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); productController = new ProductsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = productController.Details(3); resultTask.Wait(); var response = resultTask.Result as NotFoundResult; Assert.AreEqual((int)HttpStatusCode.NotFound, response.StatusCode); } }
public void Details_By_StoreId() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); storeController = new StoresController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = storeController.Details(1); resultTask.Wait(); Assert.IsNotNull(resultTask.Result); var model = (Tuple <IList <Product>, Store>)((ViewResult)resultTask.Result).Model; Assert.AreEqual(1, model.Item2.StoreId); } }
public void Index_By_StoredId() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); productController = new ProductsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = productController.Index(1); resultTask.Wait(); var model = (List <Product>)((ViewResult)resultTask.Result).Model; Assert.IsNotNull(resultTask.Result); Assert.AreEqual(1, model.Count); } }
public void TestDataProtectionProvider() { //SETUP var eProvider = new EphemeralDataProtectionProvider(); //ATTEMPT var provider = eProvider.CreateProtector("XXX"); var encrypted = provider.Protect("Hello world"); var unencrypted = provider.Unprotect(encrypted); //VERIFY unencrypted.ShouldEqual("Hello world"); }
public void ReadNonExistentCookie() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(mocks.MockContext, eProvider); //ATTEMPT var data = cookie.GetCookieInValue(); //VERIFY data.ShouldBeNull(); }
public void Details_By_BlogId() { using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); blogsController = new BlogsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); var resultTask = blogsController.Details(1); resultTask.Wait(); Assert.IsNotNull(resultTask.Result); var model = (Blogs)((ViewResult)resultTask.Result).Model; Assert.AreEqual(1, model.BlogId); } }
public static void SetupContainer() { IDataProtectionProvider dataProtectionProvider = new EphemeralDataProtectionProvider(); var builder = new ContainerBuilder(); builder.RegisterModule(new JackettModule(new RuntimeSettings())); builder.RegisterType <Jackett.Server.Services.ProtectionService>().As <IProtectionService>(); builder.RegisterType <TestWebClient>().As <WebClient>().SingleInstance(); builder.RegisterInstance(LogManager.GetCurrentClassLogger()).SingleInstance(); builder.RegisterType <TestIndexerManagerServiceHelper>().As <IIndexerManagerService>().SingleInstance(); builder.RegisterInstance(dataProtectionProvider).SingleInstance(); testContainer = builder.Build(); }
public void ReadEncryptedCookie() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(mocks.MockContext, eProvider); //ATTEMPT mocks.RequestCookies["UserImpersonation"] = eProvider.CreateProtector(cookie.EncryptPurpose).Protect("Hello world"); var data = cookie.GetCookieInValue(); //VERIFY data.ShouldEqual("Hello world"); }
public void Setup() { options = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase(databaseName: "OneStopShopDatabase") .Options; //...Setup the mock as needed mockEnvironment .Setup(m => m.EnvironmentName) .Returns("Hosting:UnitTestEnvironment"); entities = new List <Product>(); using (var context = new ApplicationDbContext(options)) { var dataProtectionProvider = new EphemeralDataProtectionProvider(); productController = new ProductsController(context, dataProtectionProvider, mockHttpContextAccessor.Object, mockEnvironment.Object); if (context.Products == null || context.Products.CountAsync().Result == 0) { context.Products.Add(new Product { ProductColor = "#FFFFFF", ProductID = 1, ProductImage = "", IsAddedToCart = false, ProductCreatedDate = DateTime.Now, ProductDescription = "The aluminium case is lightweight and made from 100 per cent recycled aerospace-grade alloy." + "The Sport Band is made from a durable yet surprisingly soft high - performance fluoroelastomer" + "with an innovative pin - and - tuck closure.", ProductName = "Apple smart watch", ProductPrice = 5873, ProductSize = "1", StoreId = 1, store = new Store() { Email = "*****@*****.**", PhoneNumber = "8585858585", SellerFirstname = "Rob", SellerLasttname = "Miller", StoreName = "UE Enterprise", StoreDescription = "This is description of store", StoreId = 1 } }); context.SaveChanges(); } } }
public void SingleProvider_SamePurpose_RoundTripsData() { // Arrange var dataProtectionProvider = new EphemeralDataProtectionProvider(); var dataProtector1 = dataProtectionProvider.CreateProtector("purpose"); var dataProtector2 = dataProtectionProvider.CreateProtector("purpose"); // should be equivalent to the previous instance byte[] bytes = Encoding.UTF8.GetBytes("Hello there!"); // Act byte[] protectedBytes = dataProtector1.Protect(bytes); byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes); // Assert Assert.Equal(bytes, unprotectedBytes); }
public void SingleProvider_DifferentPurpose_DoesNotRoundTripData() { // Arrange var dataProtectionProvider = new EphemeralDataProtectionProvider(); var dataProtector1 = dataProtectionProvider.CreateProtector("purpose"); var dataProtector2 = dataProtectionProvider.CreateProtector("different purpose"); byte[] bytes = Encoding.UTF8.GetBytes("Hello there!"); // Act & assert byte[] protectedBytes = dataProtector1.Protect(bytes); Assert.ThrowsAny<CryptographicException>(() => { byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes); }); }
public void DifferentProvider_SamePurpose_DoesNotRoundTripData() { // Arrange var dataProtector1 = new EphemeralDataProtectionProvider().CreateProtector("purpose"); var dataProtector2 = new EphemeralDataProtectionProvider().CreateProtector("purpose"); byte[] bytes = Encoding.UTF8.GetBytes("Hello there!"); // Act & assert // Each instance of the EphemeralDataProtectionProvider has its own unique KDK, so payloads can't be shared. byte[] protectedBytes = dataProtector1.Protect(bytes); Assert.ThrowsAny<CryptographicException>(() => { byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes); }); }
public void AddEncryptedCookie() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); //ATTEMPT var cookie = new ImpersonationCookie(mocks.MockContext, eProvider); cookie.AddUpdateCookie("Hello world"); //VERIFY mocks.ResponseCookies.Count.ShouldEqual(1); mocks.ResponseCookies["Set-Cookie"].ShouldNotBeNull(); mocks.ResponseCookies["Set-Cookie"][0].ShouldStartWith("UserImpersonation="); }
public void TestCookieExists() { //SETUP var httpContext = new DefaultHttpContext(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(httpContext, eProvider); cookie.AddUpdateCookie("Hello world"); httpContext.AddRequestCookie("UserImpersonation", "???"); //ATTEMPT //VERIFY cookie.Exists(httpContext.Request.Cookies).ShouldBeTrue(); }
public void AddEncryptedCookie() { //SETUP var httpContext = new DefaultHttpContext(); var eProvider = new EphemeralDataProtectionProvider(); //ATTEMPT var cookie = new ImpersonationCookie(httpContext, eProvider); cookie.AddUpdateCookie("Hello world"); //VERIFY httpContext.Response.Headers.Keys.Count.ShouldEqual(1); httpContext.Response.Headers["Set-Cookie"].ShouldNotBeNull(); httpContext.Response.Headers["Set-Cookie"][0].ShouldStartWith("UserImpersonation="); }
public void SingleProvider_DifferentPurpose_DoesNotRoundTripData() { // Arrange var dataProtectionProvider = new EphemeralDataProtectionProvider(); var dataProtector1 = dataProtectionProvider.CreateProtector("purpose"); var dataProtector2 = dataProtectionProvider.CreateProtector("different purpose"); byte[] bytes = Encoding.UTF8.GetBytes("Hello there!"); // Act & assert byte[] protectedBytes = dataProtector1.Protect(bytes); Assert.ThrowsAny <CryptographicException>(() => { byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes); }); }
public void ReadEncryptedCookie() { //SETUP var httpContext = new DefaultHttpContext(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(httpContext, eProvider); var codedData = eProvider.CreateProtector(cookie.EncryptPurpose).Protect("Hello world"); //ATTEMPT httpContext.AddRequestCookie("UserImpersonation", codedData); var data = cookie.GetCookieInValue(); //VERIFY data.ShouldEqual("Hello world"); }
public void DifferentProvider_SamePurpose_DoesNotRoundTripData() { // Arrange var dataProtector1 = new EphemeralDataProtectionProvider().CreateProtector("purpose"); var dataProtector2 = new EphemeralDataProtectionProvider().CreateProtector("purpose"); byte[] bytes = Encoding.UTF8.GetBytes("Hello there!"); // Act & assert // Each instance of the EphemeralDataProtectionProvider has its own unique KDK, so payloads can't be shared. byte[] protectedBytes = dataProtector1.Protect(bytes); Assert.ThrowsAny <CryptographicException>(() => { byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes); }); }
public void TestCookieExists() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(mocks.MockContext, eProvider); cookie.AddUpdateCookie("Hello world"); mocks.RequestCookies["UserImpersonation"] = "???"; //ATTEMPT //VERIFY cookie.Exists(mocks.MockContext.Request.Cookies).ShouldBeTrue(); }
public void ReadEncryptedCookieBadDeletesCookie() { //SETUP var httpContext = new DefaultHttpContext(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(httpContext, eProvider); //ATTEMPT httpContext.AddRequestCookie("UserImpersonation", "???"); var ex = Assert.Throws <CryptographicException>(() => cookie.GetCookieInValue()); //VERIFY ex.Message.ShouldStartWith("An error occurred during a cryptographic operation."); httpContext.Response.Headers["Set-Cookie"].ShouldNotBeNull(); httpContext.Response.Headers["Set-Cookie"][0].ShouldEndWith("expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; httponly"); }
public void ReadEncryptedCookieBadDeletesCookie() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); var cookie = new ImpersonationCookie(mocks.MockContext, eProvider); //ATTEMPT mocks.RequestCookies["UserImpersonation"] = "???"; var ex = Assert.Throws <CryptographicException>(() => cookie.GetCookieInValue()); //VERIFY ex.Message.ShouldStartWith("An error occurred during a cryptographic operation."); mocks.ResponseCookies["Set-Cookie"].ShouldNotBeNull(); mocks.ResponseCookies["Set-Cookie"][0].ShouldEndWith("expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; samesite=lax; httponly"); }
public async Task ReferenceNumber_ShouldReturn_500OnError() { var _dataProtectionProvider = new EphemeralDataProtectionProvider(); var controller = Substitute.ForPartsOf <SaveProgressController>(new object[] { _logger, _apiServices, _appSettings, _dataProtectionProvider }); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; controller.Redirect("/").Throws(new Exception()); var result = await controller.SmsInput(); var viewResult = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Error500", viewResult.ActionName); Assert.Equal("Error", viewResult.ControllerName); }
public static Mock <HttpContext> SetupControllerHttpContext() { var httpContext = new Mock <HttpContext>(); var httpRequest = new Mock <HttpRequest>(); var httpResponse = new Mock <HttpResponse>(); var requestCookie = new Mock <IRequestCookieCollection>(); var _dataProtectionProvider = new EphemeralDataProtectionProvider(); httpResponse.Setup(x => x.Cookies).Returns(new Mock <IResponseCookies>().Object); httpRequest.Setup(x => x.Cookies).Returns(requestCookie.Object); httpContext.Setup(x => x.Request).Returns(httpRequest.Object); httpContext.Setup(x => x.Response).Returns(httpResponse.Object); return(httpContext); }
public PasswordServiceTests() { var dbContextOptions = new DbContextOptionsBuilder <ApplicationDbContext>() .UseInMemoryDatabase("Db").Options; _dbContext = new ApplicationDbContext(dbContextOptions); _dataProtectionProvider = new EphemeralDataProtectionProvider(); _dataProtector = _dataProtectionProvider.CreateProtector(PasswordService.ProtectorPurpose); _clock = new FakeClock(new Instant()); _sessionService = new Mock <ISessionService>(); _sut = new PasswordService( _dbContext, _dataProtectionProvider, _clock, _sessionService.Object, NullLogger <PasswordService> .Instance ); }
public async Task JwtRefreshTokenIssuer_ExchangeRefreshTokenAsync_ReadTheRefreshTokenCorrectly() { // Arrange var options = GetOptions(); var protector = new EphemeralDataProtectionProvider(new LoggerFactory()).CreateProtector("test"); var refreshTokenSerializer = new TokenDataSerializer <RefreshToken>(options, ArrayPool <char> .Shared); var dataFormat = new SecureDataFormat <RefreshToken>(refreshTokenSerializer, protector); var expectedDateTime = new DateTimeOffset(2000, 01, 01, 0, 0, 0, TimeSpan.FromHours(1)); var now = DateTimeOffset.UtcNow; var expires = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, TimeSpan.Zero); var timeManager = GetTimeManager(expectedDateTime, expires, expectedDateTime); var issuer = new RefreshTokenIssuer(GetClaimsManager(timeManager), dataFormat); var context = GetTokenGenerationContext( new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "user") })), new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(IdentityServiceClaimTypes.ClientId, "clientId") }))); context.InitializeForToken(TokenTypes.RefreshToken); await issuer.IssueRefreshTokenAsync(context); var message = new OpenIdConnectMessage(); message.ClientId = "clientId"; message.RefreshToken = context.RefreshToken.SerializedValue; // Act var grant = await issuer.ExchangeRefreshTokenAsync(message); // Assert Assert.NotNull(grant); Assert.NotNull(grant.Token); var refreshToken = Assert.IsType <RefreshToken>(grant.Token); Assert.Equal("clientId", refreshToken.ClientId); Assert.Equal("user", refreshToken.UserId); Assert.Equal(expectedDateTime, refreshToken.IssuedAt); Assert.Equal(expires, refreshToken.Expires); Assert.Equal(expectedDateTime, refreshToken.NotBefore); Assert.Equal(new[] { "openid profile" }, refreshToken.Scopes.ToArray()); }
static void Main(string[] args) { // Short term provider IDataProtectionProvider provider = new EphemeralDataProtectionProvider(); //or long term provider from Extensions provider = DataProtectionProvider.Create(nameof(Main)); var protector = provider.CreateProtector("encrypt"); // Write File.WriteAllText("C:\\temp\\protected.txt", protector.Protect("Secret Text")); //return; // Read var secret = protector.Unprotect(File.ReadAllText("C:\\temp\\protected.txt")); Console.WriteLine(secret); }
public void RoundTrip_ProtectedData() { // Arrange var ephemeralProtector = new EphemeralDataProtectionProvider().CreateProtector("my purpose"); var timeLimitedProtector = new TimeLimitedDataProtector(ephemeralProtector); var expectedExpiration = StringToDateTime("2020-01-01 00:00:00Z"); // Act byte[] ephemeralProtectedPayload = ephemeralProtector.Protect(new byte[] { 0x01, 0x02, 0x03, 0x04 }); byte[] timeLimitedProtectedPayload = timeLimitedProtector.Protect(new byte[] { 0x11, 0x22, 0x33, 0x44 }, expectedExpiration); // Assert DateTimeOffset actualExpiration; Assert.Equal(new byte[] { 0x11, 0x22, 0x33, 0x44 }, timeLimitedProtector.UnprotectCore(timeLimitedProtectedPayload, StringToDateTime("2010-01-01 00:00:00Z"), out actualExpiration)); Assert.Equal(expectedExpiration, actualExpiration); // the two providers shouldn't be able to talk to one another (due to the purpose chaining) Assert.Throws<CryptographicException>(() => ephemeralProtector.Unprotect(timeLimitedProtectedPayload)); Assert.Throws<CryptographicException>(() => timeLimitedProtector.Unprotect(ephemeralProtectedPayload, out actualExpiration)); }
public void TestHandlerNoCookieNoClaim() { //SETUP var mocks = new MockHttpContextCookies(); var eProvider = new EphemeralDataProtectionProvider(); var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, "userid") }; //ATTEMPT var handler = new ImpersonationHandler(mocks.MockContext, eProvider, claims); //VERIFY handler.ImpersonationChange.ShouldBeFalse(); handler.GetUserIdForWorkingOutPermissions().ShouldEqual("userid"); handler.GetUserIdForWorkingDataKey().ShouldEqual("userid"); handler.AddOrRemoveImpersonationClaim(claims); claims.Count.ShouldEqual(1); }
static void Main(string[] args) { const string purpose = "Demonstration"; // instantiate the data protection system at this folder var dataProtectionProvider = new EphemeralDataProtectionProvider(); var protector = dataProtectionProvider.CreateProtector(purpose); Console.Write("Enter input: "); string input = Console.ReadLine(); // protect the payload string protectedPayload = protector.Protect(input); Console.WriteLine($"Protect returned: {protectedPayload}"); // unprotect the payload string unprotectedPayload = protector.Unprotect(protectedPayload); Console.WriteLine($"Unprotect returned: {unprotectedPayload}"); Console.ReadLine(); }