public void expiration_should_be_greater_than_zero() { { var subject = new KeyManagementOptions { KeyActivationDelay = TimeSpan.FromMinutes(1), KeyExpiration = TimeSpan.FromMinutes(0), KeyRetirement = TimeSpan.FromMinutes(3) }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { KeyActivationDelay = TimeSpan.FromMinutes(1), KeyExpiration = -TimeSpan.FromMinutes(1), KeyRetirement = TimeSpan.FromMinutes(3) }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } }
public void expiration_should_be_greater_than_zero() { { var subject = new KeyManagementOptions { PropagationTime = TimeSpan.FromMinutes(1), RotationInterval = TimeSpan.FromMinutes(0), RetentionDuration = TimeSpan.FromMinutes(3) }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { PropagationTime = TimeSpan.FromMinutes(1), RotationInterval = -TimeSpan.FromMinutes(1), RetentionDuration = TimeSpan.FromMinutes(2) }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } }
public void Configure_WithRegistryPolicyResolver_SetsValuesFromResolver() { // Arrange var registryEntries = new Dictionary <string, object>() { ["KeyEscrowSinks"] = String.Join(" ;; ; ", new Type[] { typeof(MyKeyEscrowSink1), typeof(MyKeyEscrowSink2) }.Select(t => t.AssemblyQualifiedName)), ["EncryptionType"] = "managed", ["DefaultKeyLifetime"] = 1024 // days }; var options = new KeyManagementOptions() { AuthenticatedEncryptorConfiguration = null }; // Act RunTest(registryEntries, options); // Assert Assert.Collection( options.KeyEscrowSinks, k => Assert.IsType <MyKeyEscrowSink1>(k), k => Assert.IsType <MyKeyEscrowSink2>(k)); Assert.Equal(TimeSpan.FromDays(1024), options.NewKeyLifetime); Assert.NotNull(options.AuthenticatedEncryptorConfiguration); Assert.IsType <ManagedAuthenticatedEncryptorConfiguration>(options.AuthenticatedEncryptorConfiguration); Assert.Collection( options.AuthenticatedEncryptorFactories, f => Assert.IsType <CngGcmAuthenticatedEncryptorFactory>(f), f => Assert.IsType <CngCbcAuthenticatedEncryptorFactory>(f), f => Assert.IsType <ManagedAuthenticatedEncryptorFactory>(f), f => Assert.IsType <AuthenticatedEncryptorFactory>(f)); }
public void ExpectBuilderAdditions(bool withClient) { var services = new List <ServiceDescriptor>(); builder.Setup(x => x.Services).Returns(svcCollection.Object); svcCollection.Setup(x => x.GetEnumerator()).Returns(() => services.GetEnumerator()); svcCollection.Setup(x => x.Add(It.IsAny <ServiceDescriptor>())) .Callback <ServiceDescriptor>(sd => { services.Add(sd); }); var config = new KmsXmlEncryptorConfig("keyId"); // Repeat call to ensure cumulative calls work if (withClient) { builder.Object.ProtectKeysWithAwsKms(client.Object, config); builder.Object.ProtectKeysWithAwsKms(client.Object, config); } else { builder.Object.ProtectKeysWithAwsKms(config); builder.Object.ProtectKeysWithAwsKms(config); } Assert.Equal(withClient ? 1 : 0, services.Count(x => x.ServiceType == typeof(IAmazonKeyManagementService))); // IConfigureOptions is designed & expected to be present multiple times, so expect two after two calls Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>))); Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>))); Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).Lifetime); Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).Lifetime); provider.Setup(x => x.GetService(typeof(IAmazonKeyManagementService))).Returns(client.Object); if (withClient) { Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).Lifetime); Assert.Same(client.Object, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).ImplementationInstance); } // Ensure we run equivalent config for the actual configuration object var configureObject = services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).ImplementationInstance; var optionsObject = new KmsXmlEncryptorConfig(); ((IConfigureOptions <KmsXmlEncryptorConfig>)configureObject).Configure(optionsObject); provider.Setup(x => x.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object); provider.Setup(x => x.GetService(typeof(IOptions <KmsXmlEncryptorConfig>))).Returns(snapshot.Object); provider.Setup(x => x.GetService(typeof(IOptions <DataProtectionOptions>))).Returns(dpSnapshot.Object); loggerFactory.Setup(x => x.CreateLogger(typeof(KmsXmlEncryptor).FullName)).Returns(repository.Create <ILogger <KmsXmlEncryptor> >().Object); snapshot.Setup(x => x.Value).Returns(optionsObject); var dbOptions = new DataProtectionOptions(); dpSnapshot.Setup(x => x.Value).Returns(dbOptions); var configure = services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).ImplementationFactory(provider.Object); var options = new KeyManagementOptions(); ((IConfigureOptions <KeyManagementOptions>)configure).Configure(options); Assert.IsType <KmsXmlEncryptor>(options.XmlEncryptor); }
private static ICacheableKeyRingProvider SetupCreateCacheableKeyRingTestAndCreateKeyManager( IList <string> callSequence, IEnumerable <CancellationToken> getCacheExpirationTokenReturnValues, IEnumerable <IReadOnlyCollection <IKey> > getAllKeysReturnValues, IEnumerable <Tuple <DateTimeOffset, DateTimeOffset, IKey> > createNewKeyCallbacks, IEnumerable <Tuple <DateTimeOffset, IEnumerable <IKey>, DefaultKeyResolution> > resolveDefaultKeyPolicyReturnValues, KeyManagementOptions keyManagementOptions = null) { var getCacheExpirationTokenReturnValuesEnumerator = getCacheExpirationTokenReturnValues.GetEnumerator(); var mockKeyManager = new Mock <IKeyManager>(MockBehavior.Strict); mockKeyManager.Setup(o => o.GetCacheExpirationToken()) .Returns(() => { callSequence.Add("GetCacheExpirationToken"); getCacheExpirationTokenReturnValuesEnumerator.MoveNext(); return(getCacheExpirationTokenReturnValuesEnumerator.Current); }); var getAllKeysReturnValuesEnumerator = getAllKeysReturnValues.GetEnumerator(); mockKeyManager.Setup(o => o.GetAllKeys()) .Returns(() => { callSequence.Add("GetAllKeys"); getAllKeysReturnValuesEnumerator.MoveNext(); return(getAllKeysReturnValuesEnumerator.Current); }); if (createNewKeyCallbacks != null) { var createNewKeyCallbacksEnumerator = createNewKeyCallbacks.GetEnumerator(); mockKeyManager.Setup(o => o.CreateNewKey(It.IsAny <DateTimeOffset>(), It.IsAny <DateTimeOffset>())) .Returns <DateTimeOffset, DateTimeOffset>((activationDate, expirationDate) => { callSequence.Add("CreateNewKey"); createNewKeyCallbacksEnumerator.MoveNext(); Assert.Equal(createNewKeyCallbacksEnumerator.Current.Item1, activationDate); Assert.Equal(createNewKeyCallbacksEnumerator.Current.Item2, expirationDate); return(createNewKeyCallbacksEnumerator.Current.Item3); }); } var resolveDefaultKeyPolicyReturnValuesEnumerator = resolveDefaultKeyPolicyReturnValues.GetEnumerator(); var mockDefaultKeyResolver = new Mock <IDefaultKeyResolver>(MockBehavior.Strict); mockDefaultKeyResolver.Setup(o => o.ResolveDefaultKeyPolicy(It.IsAny <DateTimeOffset>(), It.IsAny <IEnumerable <IKey> >())) .Returns <DateTimeOffset, IEnumerable <IKey> >((now, allKeys) => { callSequence.Add("ResolveDefaultKeyPolicy"); resolveDefaultKeyPolicyReturnValuesEnumerator.MoveNext(); Assert.Equal(resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item1, now); Assert.Equal(resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item2, allKeys); return(resolveDefaultKeyPolicyReturnValuesEnumerator.Current.Item3); }); return(CreateKeyRingProvider(mockKeyManager.Object, mockDefaultKeyResolver.Object, keyManagementOptions)); }
public void ExpectBuilderAdditionsConfig(bool withClient) { var services = new List <ServiceDescriptor>(); builder.Setup(x => x.Services).Returns(svcCollection.Object); svcCollection.Setup(x => x.GetEnumerator()).Returns(() => services.GetEnumerator()); svcCollection.Setup(x => x.Add(It.IsAny <ServiceDescriptor>())) .Callback <ServiceDescriptor>(sd => { services.Add(sd); }); // An empty collection seems to be enough to run what is eventually ConfigurationBinder.Bind, since there is no way to mock the options configure call // ReSharper disable once CollectionNeverUpdated.Local var configChildren = new List <IConfigurationSection>(); Mock <IConfiguration> configMock = repository.Create <IConfiguration>(); configMock.Setup(x => x.GetChildren()).Returns(configChildren); // Repeat call to ensure cumulative calls work if (withClient) { builder.Object.PersistKeysToAwsS3(client.Object, configMock.Object); builder.Object.PersistKeysToAwsS3(client.Object, configMock.Object); } else { builder.Object.PersistKeysToAwsS3(configMock.Object); builder.Object.PersistKeysToAwsS3(configMock.Object); provider.Setup(x => x.GetService(typeof(IAmazonS3))).Returns(client.Object); } Assert.Equal(1, services.Count(x => x.ServiceType == typeof(IMockingWrapper))); // IConfigureOptions is designed & expected to be present multiple times, so expect two after two calls Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>))); Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <S3XmlRepositoryConfig>))); Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IMockingWrapper)).Lifetime); Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).Lifetime); Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <S3XmlRepositoryConfig>)).Lifetime); // Ensure we run equivalent config for the actual configuration object var configureObject = services.First(x => x.ServiceType == typeof(IConfigureOptions <S3XmlRepositoryConfig>)).ImplementationInstance; var optionsObject = new S3XmlRepositoryConfig(); ((IConfigureOptions <S3XmlRepositoryConfig>)configureObject).Configure(optionsObject); provider.Setup(x => x.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object); provider.Setup(x => x.GetService(typeof(IOptions <S3XmlRepositoryConfig>))).Returns(snapshot.Object); loggerFactory.Setup(x => x.CreateLogger(typeof(S3XmlRepository).FullName)).Returns(repository.Create <ILogger <S3XmlRepository> >().Object); snapshot.Setup(x => x.Value).Returns(optionsObject); var configure = services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).ImplementationFactory(provider.Object); var options = new KeyManagementOptions(); ((IConfigureOptions <KeyManagementOptions>)configure).Configure(options); Assert.IsType <S3XmlRepository>(options.XmlRepository); }
public void InitializationSynchronizationDelay_should_be_greater_than_or_equal_to_zero() { var subject = new KeyManagementOptions { InitializationSynchronizationDelay = -TimeSpan.FromMinutes(1), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); }
public void keycacheduration_should_be_greater_than_or_equal_to_zero() { var subject = new KeyManagementOptions { KeyCacheDuration = -TimeSpan.FromMinutes(1), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); }
public KeyRingProvider( IKeyManager keyManager, IOptions <KeyManagementOptions> keyManagementOptions, IDefaultKeyResolver defaultKeyResolver, ILoggerFactory loggerFactory) { _keyManagementOptions = new KeyManagementOptions(keyManagementOptions.Value); // clone so new instance is immutable _keyManager = keyManager; CacheableKeyRingProvider = this; _defaultKeyResolver = defaultKeyResolver; _logger = loggerFactory.CreateLogger <KeyRingProvider>(); // We will automatically refresh any unknown keys for 2 minutes see https://github.com/dotnet/aspnetcore/issues/3975 AutoRefreshWindowEnd = DateTime.UtcNow.AddMinutes(2); }
private static void RunTest(Dictionary <string, object> regValues, KeyManagementOptions options) { WithUniqueTempRegKey(registryKey => { foreach (var entry in regValues) { registryKey.SetValue(entry.Key, entry.Value); } var policyResolver = new RegistryPolicyResolver( registryKey, activator: SimpleActivator.DefaultWithoutServices); var setup = new KeyManagementOptionsSetup(NullLoggerFactory.Instance, policyResolver); setup.Configure(options); }); }
private static KeyRingProvider CreateKeyRingProvider(ICacheableKeyRingProvider cacheableKeyRingProvider) { var mockEncryptorFactory = new Mock <IAuthenticatedEncryptorFactory>(); mockEncryptorFactory.Setup(m => m.CreateEncryptorInstance(It.IsAny <IKey>())).Returns(new Mock <IAuthenticatedEncryptor>().Object); var options = new KeyManagementOptions(); options.AuthenticatedEncryptorFactories.Add(mockEncryptorFactory.Object); return(new KeyRingProvider( keyManager: null, keyManagementOptions: Options.Create(options), defaultKeyResolver: null, loggerFactory: NullLoggerFactory.Instance) { CacheableKeyRingProvider = cacheableKeyRingProvider }); }
/// <summary> /// Constructor for KeyManager /// </summary> /// <param name="options"></param> /// <param name="store"></param> /// <param name="cache"></param> /// <param name="protector"></param> /// <param name="clock"></param> /// <param name="newKeyLock"></param> /// <param name="logger"></param> /// <param name="httpContextAccessor"></param> public KeyManager( KeyManagementOptions options, ISigningKeyStore store, ISigningKeyStoreCache cache, ISigningKeyProtector protector, ISystemClock clock, INewKeyLock newKeyLock, ILogger <KeyManager> logger, IHttpContextAccessor httpContextAccessor = null) { options.Validate(); _options = options; _store = store; _cache = cache; _protector = protector; _clock = clock; _newKeyLock = newKeyLock; _logger = logger; _httpContextAccessor = httpContextAccessor; }
// copy ctor internal KeyManagementOptions(KeyManagementOptions other) { if (other != null) { AutoGenerateKeys = other.AutoGenerateKeys; _newKeyLifetime = other._newKeyLifetime; XmlEncryptor = other.XmlEncryptor; XmlRepository = other.XmlRepository; AuthenticatedEncryptorConfiguration = other.AuthenticatedEncryptorConfiguration; foreach (var keyEscrowSink in other.KeyEscrowSinks) { KeyEscrowSinks.Add(keyEscrowSink); } foreach (var encryptorFactory in other.AuthenticatedEncryptorFactories) { AuthenticatedEncryptorFactories.Add(encryptorFactory); } } }
/// <summary> /// Constructor for KeyManager /// </summary> /// <param name="options"></param> /// <param name="store"></param> /// <param name="cache"></param> /// <param name="protector"></param> /// <param name="clock"></param> /// <param name="newKeyLock"></param> /// <param name="logger"></param> /// <param name="issuerNameService"></param> public KeyManager( KeyManagementOptions options, ISigningKeyStore store, ISigningKeyStoreCache cache, ISigningKeyProtector protector, ISystemClock clock, INewKeyLock newKeyLock, ILogger <KeyManager> logger, IIssuerNameService issuerNameService) { options.Validate(); _options = options; _store = store; _cache = cache; _protector = protector; _clock = clock; _newKeyLock = newKeyLock; _logger = logger; _issuerNameService = issuerNameService; }
public void retirement_should_be_longer_than_expiration() { { var subject = new KeyManagementOptions { KeyActivationDelay = TimeSpan.FromMinutes(1), KeyExpiration = TimeSpan.FromMinutes(10), KeyRetirement = TimeSpan.FromMinutes(10), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { KeyActivationDelay = TimeSpan.FromMinutes(1), KeyExpiration = TimeSpan.FromMinutes(10), KeyRetirement = TimeSpan.FromMinutes(9), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { KeyActivationDelay = TimeSpan.FromMinutes(1), KeyExpiration = TimeSpan.FromMinutes(10), KeyRetirement = TimeSpan.FromMinutes(20), }; Action a = () => subject.Validate(); a.Should().NotThrow <Exception>(); } }
public void retirement_should_be_longer_than_expiration() { { var subject = new KeyManagementOptions { PropagationTime = TimeSpan.FromMinutes(1), RotationInterval = TimeSpan.FromMinutes(10), RetentionDuration = TimeSpan.FromMinutes(0), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { PropagationTime = TimeSpan.FromMinutes(1), RotationInterval = TimeSpan.FromMinutes(10), RetentionDuration = -TimeSpan.FromMinutes(1), }; Action a = () => subject.Validate(); a.Should().Throw <Exception>(); } { var subject = new KeyManagementOptions { PropagationTime = TimeSpan.FromMinutes(1), RotationInterval = TimeSpan.FromMinutes(10), RetentionDuration = TimeSpan.FromMinutes(20), }; Action a = () => subject.Validate(); a.Should().NotThrow <Exception>(); } }
public void Configure_SetsExpectedValues() { // Arrange var setup = new KeyManagementOptionsSetup(NullLoggerFactory.Instance); var options = new KeyManagementOptions() { AuthenticatedEncryptorConfiguration = null }; // Act setup.Configure(options); // Assert Assert.Empty(options.KeyEscrowSinks); Assert.NotNull(options.AuthenticatedEncryptorConfiguration); Assert.IsType <AuthenticatedEncryptorConfiguration>(options.AuthenticatedEncryptorConfiguration); Assert.Collection( options.AuthenticatedEncryptorFactories, f => Assert.IsType <CngGcmAuthenticatedEncryptorFactory>(f), f => Assert.IsType <CngCbcAuthenticatedEncryptorFactory>(f), f => Assert.IsType <ManagedAuthenticatedEncryptorFactory>(f), f => Assert.IsType <AuthenticatedEncryptorFactory>(f)); }
/// <summary> /// Ctor /// </summary> /// <param name="isOptions"></param> /// <param name="keyManagerOptions"></param> public ClientConfigurationValidator(IdentityServerOptions isOptions, KeyManagementOptions keyManagerOptions = null) : base(isOptions) { _keyManagerOptions = keyManagerOptions; }
private static ICacheableKeyRingProvider CreateKeyRingProvider(IKeyManager keyManager, IDefaultKeyResolver defaultKeyResolver, KeyManagementOptions keyManagementOptions = null) { var mockEncryptorFactory = new Mock <IAuthenticatedEncryptorFactory>(); mockEncryptorFactory.Setup(m => m.CreateEncryptorInstance(It.IsAny <IKey>())).Returns(new Mock <IAuthenticatedEncryptor>().Object); keyManagementOptions = keyManagementOptions ?? new KeyManagementOptions(); keyManagementOptions.AuthenticatedEncryptorFactories.Add(mockEncryptorFactory.Object); return(new KeyRingProvider( keyManager: keyManager, keyManagementOptions: Options.Create(keyManagementOptions), defaultKeyResolver: defaultKeyResolver, loggerFactory: NullLoggerFactory.Instance)); }
internal static RsaSecurityKey CreateRsaSecurityKey(this KeyManagementOptions options) { return(CryptoHelper.CreateRsaSecurityKey(options.RsaKeySize)); }
/// <summary> /// Constructor for DataProtectionKeyProtector. /// </summary> /// <param name="options"></param> /// <param name="dataProtectionProvider"></param> public DataProtectionKeyProtector(KeyManagementOptions options, IDataProtectionProvider dataProtectionProvider) { _options = options; _dataProtectionProvider = dataProtectionProvider.CreateProtector(nameof(DataProtectionKeyProtector)); }
internal static bool IsRetired(this KeyManagementOptions options, TimeSpan age) { return(age >= options.KeyRetirementAge); }
internal static bool IsExpired(this KeyManagementOptions options, TimeSpan diff) { return(diff >= options.KeyExpiration); }
internal static bool IsWithinInitializationDuration(this KeyManagementOptions options, TimeSpan age) { return(age <= options.InitializationDuration); }
internal static bool IsExpired(this KeyManagementOptions options, TimeSpan age) { return(age >= options.RotationInterval); }
/// <summary> /// Constructor for KeyManagerKeyStore. /// </summary> /// <param name="keyManager"></param> /// <param name="options"></param> public AutomaticKeyManagerKeyStore(IKeyManager keyManager, KeyManagementOptions options) { _keyManager = keyManager; _options = options; }
internal static bool IsRetired(this KeyManagementOptions options, TimeSpan diff) { return(diff >= options.KeyRetirement); }