public async Task ConfigureSecretStore_WithDuplicateNames_MakesSubsetOfDuplicateSecretProviderNames() { // Arrange var name = $"duplicate-name-{Guid.NewGuid()}"; string secretName1 = "MySecret-1", secretName2 = "My-Secret2", secretName3 = "My-Secret3", secretName4 = $"My-Secret4"; string secretValue1 = $"secret-{Guid.NewGuid()}", secretValue2 = $"secret-{Guid.NewGuid()}", secretValue3 = $"secret-{Guid.NewGuid()}", secretValue4 = $"secret-{Guid.NewGuid()}"; var builder = new HostBuilder(); // Act builder.ConfigureSecretStore((config, stores) => { stores.AddProvider(new InMemorySecretProvider((secretName1, secretValue1)), options => options.Name = name) .AddProvider(new InMemorySecretProvider((secretName3, secretValue3)), options => options.Name = "some other name") .AddProvider(new InMemoryCachedSecretProvider((secretName2, secretValue2)), options => options.Name = name) .AddProvider(new InMemorySecretProvider((secretName4, secretValue4))); }); // Assert using (IHost host = builder.Build()) { var store = host.Services.GetRequiredService <ISecretStore>(); ISecretProvider provider = store.GetProvider(name); Assert.IsNotType <InMemoryCachedSecretProvider>(provider); Assert.Equal(secretValue1, await provider.GetRawSecretAsync(secretName1)); Assert.Equal(secretValue2, await provider.GetRawSecretAsync(secretName2)); await Assert.ThrowsAsync <SecretNotFoundException>(() => provider.GetRawSecretAsync(secretName3)); await Assert.ThrowsAsync <SecretNotFoundException>(() => provider.GetRawSecretAsync(secretName4)); } }
protected TableTransmitter(string tableName, ISecretProvider secretProvider, ILogger logger) { TableName = tableName; _secretProvider = secretProvider; _logger = logger; }
// We need the package from nuget Microsoft.Rest.ClientRuntime.Azure.Authentication and Microsoft.Azure.DataLake.Store public static void MainMethod() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; //tenantId = @"72f988bf-86f1-41af-91ab-2d7cd011db47";// For tenant Microsoft string tenantId = @"cdc5aeea-15c5-4db6-b079-fcadd2505dc2";// For tenant Torus string clientId = secretProvider.GetSecretAsync("datacop-prod", "AdlsAadAuthAppId").Result; string clientKey = secretProvider.GetSecretAsync("datacop-prod", "AdlsAadAuthAppSecret").Result; Console.WriteLine($"For AAD application 'AdlsAadAuthApp'"); Console.WriteLine($"clientId: {clientId}"); Console.WriteLine($"clientKey: {clientKey}"); dataLakeClient = new DataLakeClient(tenantId, clientId, clientKey); RunDemo(); clientId = secretProvider.GetSecretAsync("datacop-prod", "IDEAsBuildVNextAppId").Result; clientKey = secretProvider.GetSecretAsync("datacop-prod", "IDEAsBuildVNextAppSecret").Result; Console.WriteLine($"For AAD application 'IDEAsBuildVNextApp'"); Console.WriteLine($"clientId: {clientId}"); Console.WriteLine($"clientKey: {clientKey}"); dataLakeClient = new DataLakeClient(tenantId, clientId, clientKey); RunDemo(); }
/// <summary> /// Adds an <see cref="ISecretProvider"/> implementation to the secret store of the application. /// </summary> /// <param name="secretProvider">The provider which secrets are added to the secret store.</param> /// <returns> /// The extended secret store with the given <paramref name="secretProvider"/>. /// </returns> public SecretStoreBuilder AddProvider(ISecretProvider secretProvider) { Guard.NotNull(secretProvider, nameof(secretProvider)); SecretStoreSources.Add(new SecretStoreSource(secretProvider)); return(this); }
static void Main(string[] args) { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; //string connectionString = secretProvider.GetSecretAsync("datacop-prod", "IDEAsPortalPPEConnectionString").Result; string connectionString = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "SQLConnectionString").Result; var sqlDal = new SqlDataAccessLayer(connectionString); //string cmdText = "SELECT Date, CONVERT(decimal, SUM([Value])) AS MetricValue FROM [DataQuality].[CommercialActiveUsageStats] WITH (NOLOCK) WHERE Date = @Date AND DataRefreshState = 'Stable' AND DateAggregationType = 'RL28' AND [Key] IN ('Platform_web_Count') AND [Workload] IN ('Exchange') GROUP BY Date ORDER BY Date DESC"; string cmdText = @"SELECT count([userid]) as MetricValue FROM[dbo].[user_info] where[userid] > 3"; //Console.WriteLine(GetMetricValueAsDouble(sqlDal, "testName", CommandType.Text, cmdText, DateTime.UtcNow.AddDays(-1), 300).Result); cmdText = @"SELECT CAST(1 AS BIT) as MetricValue FROM[dbo].[user_info] where[userid] > 6"; cmdText = @"SELECT CASE WHEN EXISTS ( SELECT * FROM[dbo].[user_info] where[userid] = 2 ) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END as MetricValue"; Console.WriteLine(GetMetricValueAsBool(sqlDal, "testName", CommandType.Text, cmdText, DateTime.UtcNow.AddDays(-1), 300).Result); Console.ReadKey(); }
public MemoryCachedSecretProvider(ISecretProvider secretProvider, ITelemetryProvider telemetryProvider) { this.secretProvider = secretProvider; this.telemetryProvider = telemetryProvider; memoryCache = CreateMemoryCache(); }
public AzureServiceBusMultiThread() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; string serviceBusConnectionString = secretProvider.GetSecretAsync(KeyVaultName, "ServiceBusConnectionString").Result; queueClient = new QueueClient(serviceBusConnectionString, QueueName); }
public LoginInfo(string userName, string userPasswordHash, ISecretProvider secretProvider, ISecretPersistor secretPersistor) { UserName = userName; UserPasswordHash = userPasswordHash; SecretProvider = secretProvider; SecretPersistor = secretPersistor; }
public BlobImageMediaServiceProvider(ISecretProvider secretProvider, ILogger <BlobImageMediaServiceProvider> logger) { Guard.NotNull(secretProvider, nameof(secretProvider)); _logger = logger; _secretProvider = secretProvider; }
private async Task <string> GetAuthorizationSecretAsync(AuthorizationFilterContext context) { ISecretProvider userDefinedSecretProvider = context.HttpContext.RequestServices.GetService <ICachedSecretProvider>() ?? context.HttpContext.RequestServices.GetService <ISecretProvider>(); if (userDefinedSecretProvider is null) { throw new KeyNotFoundException( $"No configured {nameof(ICachedSecretProvider)} or {nameof(ISecretProvider)} implementation found in the request service container. " + "Please configure such an implementation (ex. in the Startup) of your application"); } Task <string> rawSecretAsync = userDefinedSecretProvider.GetRawSecretAsync(_secretName); if (rawSecretAsync is null) { throw new InvalidOperationException( $"Configured {nameof(ISecretProvider)} is not implemented correctly as it returns 'null' for a {nameof(Task)} value when calling {nameof(ISecretProvider.GetRawSecretAsync)}"); } string foundSecret = await rawSecretAsync; if (foundSecret is null) { throw new SecretNotFoundException(_secretName); } return(foundSecret); }
/// <summary> /// Creates an <see cref="ICachedSecretProvider" /> instance that will use a default <see cref="IMemoryCache"/> implementation /// to get SecretValues from the passed <paramref name="secretProvider"/>. /// </summary> /// <param name="secretProvider">An instantiated <see cref="ISecretProvider" /> that will only be called if the value is not cached</param> /// <param name="cachingDuration">The duration to cache secrets in memory</param> /// <returns>A secret provider that caches values</returns> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="cachingDuration"/> is not a positive time duration.</exception> public static ICachedSecretProvider WithCaching(this ISecretProvider secretProvider, TimeSpan cachingDuration) { Guard.NotNull(secretProvider, nameof(secretProvider), "Requires a secret provider instance to include caching while retrieving secrets"); Guard.NotLessThan(cachingDuration, TimeSpan.Zero, nameof(cachingDuration), "Requires a positive time duration in which the caching should take place"); return(new CachedSecretProvider(secretProvider, new CacheConfiguration(cachingDuration))); }
private static void Initialize(string keyVaultName) { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; // PPE resource: api://ead06413-cb7c-408e-a533-2cdbe58bf3a6 // Prod resource; api://9576eb06-ef2f-4f45-a131-e33d0e7ffb00 // For ideas-prod-c14 //Service = @"gdpr"; //VirtualCluster = @"ideas-prod-c14"; //WorkloadQueueName = @"gdpr"; //string tenantId = @"cdc5aeea-15c5-4db6-b079-fcadd2505dc2"; //string resource = @"api://9576eb06-ef2f-4f45-a131-e33d0e7ffb00"; //string clientId = secretProvider.GetSecretAsync(keyVaultName, "GdprClientId").Result; //string clientSecret = secretProvider.GetSecretAsync(keyVaultName, "GdprClientSecret").Result; // For ideas-prod-build-c14 Service = @"pls"; VirtualCluster = @"ideas-prod-build-c14"; WorkloadQueueName = @"build"; // The default value is "build". string tenantId = @"72f988bf-86f1-41af-91ab-2d7cd011db47"; string resource = @"api://d42d6163-88e5-4339-bbb3-28ec2fb3c574"; string clientId = secretProvider.GetSecretAsync(keyVaultName, "PlsAadAuthAppId").Result; string clientSecret = secretProvider.GetSecretAsync(keyVaultName, "PlsAadAuthAppSecret").Result; Token = AzureActiveDirectoryToken.GetAccessTokenV1Async(tenantId, clientId, clientSecret, resource).Result; }
private Constant() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; this.SQLAccountUserId = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "SQLAccountUserId").Result; this.SQLAccountPassword = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "SQLAccountPassword").Result; this.StorageAccountKey = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "StorageAccountKey").Result; }
public Configuration( ISecretProvider secretProvider = null, DatabricksClientWrapper databricksClientWrapper = null, DataLakeClient dataLakeClient = null) { this.DataLakeClient = dataLakeClient; this.DatabricksClientWrapper = databricksClientWrapper; }
public static X509Certificate2 GetCertificateFromBase64String() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; var bundle = secretProvider.GetSecretAsync("datacop-prod", "CosmosRedmondClientCert").Result; byte[] privateKeyBytes = Convert.FromBase64String(bundle); return(new X509Certificate2(privateKeyBytes, (string)null, X509KeyStorageFlags.MachineKeySet)); }
/// <summary> /// Initializes a new instance of the <see cref="DatabricksJobMetricsFunction"/> class. /// </summary> /// <param name="configuration">The application configuration to retrieve required runtime information for the Databricks connection and metric reporting.</param> /// <param name="secretProvider">The provider to retrieve secrets for the Databricks connection.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="configuration"/> or <paramref name="secretProvider"/> is <c>null</c>.</exception> public DatabricksJobMetricsFunction(IConfiguration configuration, ISecretProvider secretProvider) { Guard.NotNull(configuration, nameof(configuration), "Requires an application configuration instance to retrieve runtime information for the Databricks connection and metric reporting"); Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an secret provider instance to retrieve secrets for the Databricks connection"); _configuration = configuration; _secretProvider = secretProvider; }
/// <summary> /// Gets the registered named <see cref="ISecretProvider"/> from the secret store. /// </summary> /// <param name="name">The name that was used to register the <see cref="ISecretProvider"/> in the secret store.</param> /// <exception cref="ArgumentException">Thrown when the <paramref name="name"/> is blank.</exception> /// <exception cref="KeyNotFoundException">Thrown when there was no <see cref="ISecretProvider"/> found in the secret store with the given <paramref name="name"/>.</exception> public ISecretProvider GetProvider(string name) { Guard.NotNullOrWhitespace(name, nameof(name), "Requires a non-blank name to retrieve the registered named secret provider"); ISecretProvider subset = GetSingleOrSubsetSecretProvider(name); return(subset); }
protected override object OnExecute(CommandContext context) { if (context.Parameter is ISecretProvider) { _secret = (ISecretProvider)context.Parameter; } return(null); }
private static void Initialize(string keyVaultName) { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; string applicationId = secretProvider.GetSecretAsync(keyVaultName, "CloudScopeLogMonitorApplicationId").Result; string clientId = secretProvider.GetSecretAsync(keyVaultName, "BuildLogMonitorClientId").Result; string clientKey = secretProvider.GetSecretAsync(keyVaultName, "BuildLogMonitorClientKey").Result; cloudScopeLogProvider = new CloudScopeLogProvider(applicationId, clientId, clientKey); }
/// <summary> /// Initializes a new instance of DeviceActor /// </summary> public DeviceActor(ActorHost actorHost, MessageProcessor messageProcessor, ISecretProvider secretProvider) : base(actorHost) { Guard.NotNull(messageProcessor, nameof(messageProcessor)); Guard.NotNull(secretProvider, nameof(secretProvider)); _secretProvider = secretProvider; _messageProcessor = messageProcessor; }
public PortDetailsModel( IStoreWrapper dataStore, ISecretProvider secret, ILogger <PortDetailsModel> logger) { _dataStore = dataStore; _secret = secret; _logger = logger; }
/// <summary> /// Creating a new CachedSecretProvider with all required information /// </summary> /// <param name="secretProvider">The internal <see cref="ISecretProvider"/> used to retrieve the actual Secret Value, when not cached</param> /// <param name="cacheConfiguration">The <see cref="ICacheConfiguration"/> which defines how the cache works</param> /// <param name="memoryCache">A <see cref="IMemoryCache"/> implementation that can cache data in memory.</param> /// <exception cref="ArgumentNullException">The secretProvider and memoryCache parameters must not be null</exception> public CachedSecretProvider(ISecretProvider secretProvider, ICacheConfiguration cacheConfiguration, IMemoryCache memoryCache) { Guard.NotNull(secretProvider, nameof(secretProvider)); Guard.NotNull(memoryCache, nameof(memoryCache)); Guard.NotNull(cacheConfiguration, nameof(cacheConfiguration)); _secretProvider = secretProvider; _memoryCache = memoryCache; _cacheConfiguration = cacheConfiguration; }
/// <summary> /// Initializes a new instance of the <see cref="AuthorizedSecretProvider"/> class. /// </summary> /// <param name="permittedRole">The role that is required to access the <paramref name="secretProvider"/>.</param> /// <param name="authorization">The instance to determine if the <paramref name="permittedRole"/> is considered authorized.</param> /// <param name="secretProvider">The actual provider to access the secrets.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="authorization"/> or <paramref name="secretProvider"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="permittedRole"/> is outside the bounds of the enumeration.</exception> public AuthorizedSecretProvider(Role permittedRole, IRoleAuthorization authorization, ISecretProvider secretProvider) { Guard.NotNull(authorization, nameof(authorization), "Requires an instance to determine if the current role is considered authorized"); Guard.NotNull(secretProvider, nameof(secretProvider), "Requires an instance to access the authorized secrets"); Guard.For <ArgumentOutOfRangeException>(() => !Enum.IsDefined(typeof(Role), permittedRole), "Requires the role to be inside the bounds of the enumeration"); _permittedRole = permittedRole; _authorization = authorization; _secretProvider = secretProvider; }
public static void MainMethod() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; client_id = "83ac8948-e5e1-4bbd-97ea-798a13dc8bc6"; client_secret = secretProvider.GetSecretAsync("datacop-prod", "AADDataCopClientSecret").Result; resource = "83ac8948-e5e1-4bbd-97ea-798a13dc8bc6"; HttpClientDemo(); HttpWebRequestDemo(); }
/// <summary> /// Initializes a new instance of the <see cref="MutatedSecretNameSecretProvider"/> class. /// </summary> /// <param name="implementation">The actual <see cref="ISecretProvider"/> implementation to look up the secret.</param> /// <param name="mutateSecretName">The function to mutate the name of the secret before looking up the secret.</param> /// <param name="logger">The instance to log diagnostic messages during the secret name mutation.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="implementation"/> or the <paramref name="mutateSecretName"/> is <c>null</c>. /// </exception> public MutatedSecretNameSecretProvider(ISecretProvider implementation, Func <string, string> mutateSecretName, ILogger logger) { Guard.NotNull(implementation, nameof(implementation), "Requires an secret provider instance to pass the mutated secret name to"); Guard.NotNull(mutateSecretName, nameof(mutateSecretName), "Requires an transformation function to mutate the incoming secret name to something that the actual secret provider can understand"); _mutateSecretName = mutateSecretName; _implementation = implementation; Logger = logger ?? NullLogger <MutatedSecretNameSecretProvider> .Instance; }
public AccountController( UserManager <BotUser> userManager, SignInManager <BotUser> signInManager, RoleManager <BotUserRole> roleManager, ILoggerFactory loggerFactory, ISecretProvider secretProvider) { this._userManager = userManager; this._signInManager = signInManager; this._roleManager = roleManager; this._secretProvider = secretProvider; this._logger = loggerFactory.CreateLogger <AccountController>(); }
/// <summary> /// Initializes a new instance of the <see cref="SecretStoreSource"/> class. /// </summary> /// <param name="secretProvider">The secret provider to add to the secret store.</param> /// <param name="mutateSecretName">The optional mutation function to transform secret names.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> is <c>null</c>.</exception> public SecretStoreSource(ISecretProvider secretProvider, Func <string, string> mutateSecretName = null) { Guard.NotNull(secretProvider, nameof(secretProvider), "Requires a secret provider instance to register it in the secret store"); _secretProvider = secretProvider; if (secretProvider is ICachedSecretProvider cachedSecretProvider) { CachedSecretProvider = cachedSecretProvider; } MutateSecretName = mutateSecretName; }
/// <summary> /// Gets the registered named <see cref="ISecretProvider"/> from the secret store. /// </summary> /// <param name="name">The name that was used to register the <see cref="ISecretProvider"/> in the secret store.</param> /// <typeparam name="TSecretProvider">The concrete <see cref="ISecretProvider"/> type.</typeparam> /// <exception cref="ArgumentException">Thrown when the <paramref name="name"/> is blank.</exception> /// <exception cref="KeyNotFoundException"> /// Thrown when there was no <see cref="ISecretProvider"/> found in the secret store with the given <paramref name="name"/>, /// or there were multiple <see cref="ISecretProvider"/> instances registered with the same name. /// </exception> /// <exception cref="InvalidCastException">Thrown when the registered <see cref="ISecretProvider"/> cannot be cast to the specific <typeparamref name="TSecretProvider"/>.</exception> public TSecretProvider GetProvider <TSecretProvider>(string name) where TSecretProvider : ISecretProvider { Guard.NotNullOrWhitespace(name, nameof(name), "Requires a non-blank name to retrieve the registered named secret provider"); ISecretProvider provider = GetProvider(name); if (provider is TSecretProvider concreteProvider) { return(concreteProvider); } throw new InvalidCastException($"Cannot cast registered {nameof(ISecretProvider)} with name '{name}' to type '{typeof(TSecretProvider).Name}'"); }
/// <summary> /// Initializes a new instance of the <see cref="SecretStoreSource"/> class. /// </summary> /// <param name="secretProvider">The secret provider to add to the secret store.</param> /// <param name="options">The optional options to configure the <see cref="ISecretProvider"/>. in the secret store.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="secretProvider"/> is <c>null</c>.</exception> public SecretStoreSource(ISecretProvider secretProvider, SecretProviderOptions options) { Guard.NotNull(secretProvider, nameof(secretProvider), "Requires a secret provider instance to register it in the secret store"); _secretProvider = secretProvider; if (secretProvider is ICachedSecretProvider cachedSecretProvider) { CachedSecretProvider = cachedSecretProvider; } Options = options ?? new SecretProviderOptions(); }
// The doc link: https://docs.microsoft.com/en-us/azure/azure-monitor/platform/data-collector-api // https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/log-query-overview // Query doc: https://docs.microsoft.com/en-us/azure/azure-monitor/log-query/get-started-portal // Query url: https://ms.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/6f7fbe56-fb42-4e46-b14d-dfc86acf0e0f/resourceGroups/CSharpMVCWebAPIApplicationResourceGroup/providers/Microsoft.OperationalInsights/workspaces/CSharpMVCWebAPIApplication/logs // It will cost a long time to create a table when you send a log request to a new table first. public static void MainMethod() { ISecretProvider secretProvider = KeyVaultSecretProvider.Instance; string workspaceId = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "LogAnalyticsWorkspaceId").Result; string primaryKey = secretProvider.GetSecretAsync("csharpmvcwebapikeyvault", "LogAnalyticsPrimaryKey").Result; AzureMonitorLog azureMonitorLog = new AzureMonitorLog(workspaceId, primaryKey); // tagId is for separating different log locations string tagId = "9491c703-f581-4635-98b3-c2781ae59de2"; string message = "This is a test error log"; azureMonitorLog.LogErrorAsync(tagId, message).Wait(); }