private async Task AskForVaultUnseal(SecureString token) { using (var t = token.Insecure()) { var vaultClientSettings = new VaultClientSettings(endpoint, new TokenAuthMethodInfo(t.Value)); var vc = new VaultClient(vaultClientSettings); var healthStatus = await vc.V1.System.GetHealthStatusAsync(); if (healthStatus.Sealed && healthStatus.Initialized) { console.ForegroundColor = ConsoleColor.Yellow; console.WriteLine("Vault is currently sealed."); console.WriteLine("Please type `vault unseal` to begin unsealing the vault."); console.ResetColor(); } // TODO: Find a better way, this is necessary because the VaultProcess is outputting to the console. // However, without this hack the user won't know they can start typing. console.ForegroundColor = ConsoleColor.Cyan; console.Write($"{Environment.NewLine}tangram$ "); console.ResetColor(); } }
public async Task AddHashiCorpVault_WithWrongMutation_Fails() { // Arrange string secretPath = "secretpath"; string secretKey = "my-value", expected = "s3cr3t"; string userName = "******", password = "******"; var builder = new HostBuilder(); using (HashiCorpVaultTestServer server = await StartServerWithUserPassAsync(userName, password, DefaultDevMountPoint)) { await server.KeyValueV2.WriteSecretAsync( mountPoint : DefaultDevMountPoint, path : secretPath, data : new Dictionary <string, object> { [secretKey] = expected }); var authentication = new UserPassAuthMethodInfo(userName, password); var settings = new VaultClientSettings(server.ListenAddress.ToString(), authentication); // Act builder.ConfigureSecretStore((config, stores) => { stores.AddHashiCorpVault(settings, secretPath, options => options.KeyValueMountPoint = DefaultDevMountPoint, mutateSecretName: secretName => "Test-" + secretName); }); // Assert IHost host = builder.Build(); var provider = host.Services.GetRequiredService <ISecretProvider>(); await Assert.ThrowsAsync <SecretNotFoundException>(() => provider.GetRawSecretAsync(secretKey)); } }
private static (IVaultClient client, VaultClientSettings settings) GetClientAndSettings(VaultOptions options) { var settings = new VaultClientSettings(options.Url, GetAuthMethod(options)); var client = new VaultClient(settings); return(client, settings); }
/// <summary> /// <para> /// Adds the secrets of a HashiCorp Vault KeyValue engine to the secret store. /// </para> /// <para> /// See more information on HashiCorp: <a href="https://www.vaultproject.io/docs" />. /// </para> /// </summary> /// <param name="builder">The builder to add the HashiCorp secrets from the KeyValue Vault to.</param> /// <param name="settings"></param> /// <param name="secretPath">The secret path where the secret provider should look for secrets.</param> /// <param name="configureOptions">The function to set the additional options to configure the HashiCorp Vault KeyValue.</param> /// <param name="name">The unique name to register this HashiCorp provider in the secret store.</param> /// <param name="mutateSecretName">The optional function to mutate the secret name before looking it up.</param> /// <exception cref="ArgumentNullException"> /// Thrown when the <paramref name="builder"/>, <paramref name="settings"/> or <paramref name="secretPath"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="settings"/> doesn't have a valid Vault server URI or a missing authentication method, /// or the <paramref name="secretPath"/> is blank. /// </exception> public static SecretStoreBuilder AddHashiCorpVault( this SecretStoreBuilder builder, VaultClientSettings settings, string secretPath, Action <HashiCorpVaultOptions> configureOptions, string name, Func <string, string> mutateSecretName) { Guard.NotNull(builder, nameof(builder), "Requires a secret store builder to add the HashiCorp Vault secret provider"); Guard.NotNull(settings, nameof(settings), "Requires HashiCorp Vault settings to correctly connect to the running HashiCorp Vault"); Guard.NotNullOrWhitespace(settings.VaultServerUriWithPort, nameof(settings.VaultServerUriWithPort), "Requires a non-blank HashiCorp Vault settings to have a valid URI with HTTP port"); Guard.NotNull(settings.AuthMethodInfo, nameof(settings.AuthMethodInfo), "Requires the HashiCorp Vault settings to have an authentication method configured"); Guard.NotNullOrWhitespace(secretPath, nameof(secretPath), "Requires a secret path to look for secret values"); Guard.For <ArgumentException>(() => !Uri.IsWellFormedUriString(settings.VaultServerUriWithPort, UriKind.RelativeOrAbsolute), "Requires a HashiCorp Vault server URI with HTTP port"); var options = new HashiCorpVaultOptions(); configureOptions?.Invoke(options); return(AddHashiCorpVault(builder, settings, secretPath, options, configureSecretProviderOptions: secretProviderOptions => { secretProviderOptions.Name = name; secretProviderOptions.MutateSecretName = mutateSecretName; })); }
public void AddHashiCorp_WithoutKeyValueMountPoint_Throws(string keyValueMountPoint) { // Arrange var builder = new HostBuilder(); var userName = Guid.NewGuid().ToString(); var password = Guid.NewGuid().ToString(); var settings = new VaultClientSettings("https://vault.uri:456", new UserPassAuthMethodInfo(userName, password)); // Act builder.ConfigureSecretStore((config, stores) => { stores.AddHashiCorpVault( settings: settings, secretPath: "secret/path", configureOptions: options => { options.KeyValueVersion = VaultKeyValueSecretEngineVersion.V2; options.KeyValueMountPoint = keyValueMountPoint; }, name: null, mutateSecretName: null); }); // Assert Assert.ThrowsAny <ArgumentException>(() => builder.Build()); }
public Polymath(VaultClientSettings vaultClientSettings, ICredentials credentials = null) { VaultClientSettings = vaultClientSettings; #if NET45 var handler = new WebRequestHandler(); // not the best place, but a very convenient place to add cert of certauthmethod. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Cert) { var certAuthMethodInfo = vaultClientSettings.AuthMethodInfo as CertAuthMethodInfo; handler.ClientCertificates.Add(certAuthMethodInfo.ClientCertificate); } #else var handler = new HttpClientHandler(); // not the best place, but a very convenient place to add cert of certauthmethod. if (vaultClientSettings.AuthMethodInfo?.AuthMethodType == AuthMethodType.Cert) { var certAuthMethodInfo = vaultClientSettings.AuthMethodInfo as CertAuthMethodInfo; handler.ClientCertificates.Add(certAuthMethodInfo.ClientCertificate); } #endif handler.Credentials = credentials; vaultClientSettings.PostProcessHttpClientHandlerAction?.Invoke(handler); _httpClient = new HttpClient(handler); ConfigureHttpClient(); _lazyVaultToken = GetLazyVaultToken(); }
public static IEnumerable <KeyValuePair <string, string> > Read(VaultClientSettings clientSettings) { var vaultClient = new VaultClient(clientSettings); var secrets = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("thingspeak", mountPoint: "blog-demo").Result; return(secrets.Data.Data.Select(x => new KeyValuePair <string, string>(x.Key, x.Value.ToString()))); }
static async Task Main(string[] args) { // limited permissions. hidden in env variables, typically injected var roleId = Environment.GetEnvironmentVariable("ROLEID"); var secretId = Environment.GetEnvironmentVariable("VAULTSECRET"); IVaultClient vaultClient = null; try{ // Get the approle token IAuthMethodInfo authMethod = new AppRoleAuthMethodInfo(roleId, secretId); var vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod); vaultClient = new VaultClient(vaultClientSettings); } catch (Exception e) { // Failed to get Vault token Console.WriteLine(String.Format("An error occurred authenticating: {0}", e.Message)); throw; } try{ //Get the secret and print it Secret <Dictionary <string, object> > kv1Secret = await vaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync("data/testdata/universe", "secret"); Dictionary <string, object> dataDictionary = kv1Secret.Data; JsonDocument jsonObj = JsonDocument.Parse(dataDictionary["data"].ToString()); Console.WriteLine(String.Format("The answer is {0}.", jsonObj.RootElement.GetProperty("theanswer"))); } catch (Exception e) { //Failed to get the secret or format it. Console.WriteLine(String.Format("An error pulling or parsing the secret: {0}", e.Message)); throw; } }
private async void Button_Click_1(object sender, RoutedEventArgs e) { CancelAddButton.IsEnabled = false; AddKeyButton.IsEnabled = false; AddKeyButton.Content = "Processing..."; IAuthMethodInfo authMethod = new TokenAuthMethodInfo(Properties.Settings.Default.VaultToken); var vaultClientSettings = new VaultClientSettings(Properties.Settings.Default.VaultURL, authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); TOTPCreateKeyRequest createKeyRequest = new TOTPCreateKeyRequest { AccountName = ProductBox.Text, Algorithm = "SHA1", Period = "30", Issuer = VendorBox.Text, KeyGenerationOption = new TOTPNonVaultBasedKeyGeneration { AccountName = ProductBox.Text, Issuer = VendorBox.Text, Key = SecretBox.Text, }, }; Secret <TOTPCreateKeyResponse> createResponse = await vaultClient.V1.Secrets.TOTP.CreateKeyAsync(Guid.NewGuid().ToString(), createKeyRequest); this.DialogResult = true; this.Close(); }
public void CreateProvider_WithInvalidVaultUri_Throws() { var settings = new VaultClientSettings("not a valid vault URI", new UserPassAuthMethodInfo("username", "password")); Assert.ThrowsAny <ArgumentException>( () => new HashiCorpSecretProvider(settings, secretPath: "secret/path", options: new HashiCorpVaultOptions(), logger: null)); }
public void CreateProvider_WithoutAuthenticationMethod_Throws() { var settings = new VaultClientSettings("https://vault.server:245", authMethodInfo: null); Assert.ThrowsAny <ArgumentException>( () => new HashiCorpSecretProvider(settings, secretPath: "secret/path", options: new HashiCorpVaultOptions(), logger: null)); }
public void CreateProvider_WithoutSecretPaths_Throws() { var settings = new VaultClientSettings("https://vault.server:245", new UserPassAuthMethodInfo("username", "password")); Assert.ThrowsAny <ArgumentException>( () => new HashiCorpSecretProvider(settings, secretPath: null, options: new HashiCorpVaultOptions(), logger: null)); }
private IVaultClient CreateVaultClient() { var authMethod = new TokenAuthMethodInfo(_configuration["VAULT_TOKEN_ID"]); var vaultClientSettings = new VaultClientSettings(_configuration["VAULT_ADDRESS"], authMethod); return(new VaultClient(vaultClientSettings)); }
/// <inheritdoc/> public override void Load() { try { IAuthMethodInfo authMethod; if (!string.IsNullOrEmpty(this._source.Options.VaultRoleId) && !string.IsNullOrEmpty(this._source.Options.VaultSecret)) { authMethod = new AppRoleAuthMethodInfo( this._source.Options.VaultRoleId, this._source.Options.VaultSecret); } else { authMethod = new TokenAuthMethodInfo(this._source.Options.VaultToken); } var vaultClientSettings = new VaultClientSettings(this._source.Options.VaultAddress, authMethod) { UseVaultTokenHeaderInsteadOfAuthorizationHeader = true, }; IVaultClient vaultClient = new VaultClient(vaultClientSettings); using var ctx = new JoinableTaskContext(); var jtf = new JoinableTaskFactory(ctx); jtf.RunAsync( async() => { await this.LoadVaultDataAsync(vaultClient).ConfigureAwait(true); }).Join(); } catch (Exception e) when(e is VaultApiException || e is System.Net.Http.HttpRequestException) { this._logger?.Log(LogLevel.Error, e, "Cannot load configuration from Vault"); } }
private static VaultClient CreateBootstrappingVaultClient(VaultSettings configuration) { var authMethod = new VaultSharp.V1.AuthMethods.Token.TokenAuthMethodInfo(configuration.BootstrapToken); var settings = new VaultClientSettings(configuration.VaultEndpointUri, authMethod); return(new VaultClient(settings)); }
public VaultClientFactory(FileArgsBase args) { if (args == null) { throw new ArgumentNullException(nameof(args)); } if (String.IsNullOrEmpty(args.VaultRoleId)) { throw new ArgumentException("Vault Rold Id missing", nameof(args.VaultRoleId)); } if (String.IsNullOrEmpty(args.VaultSecretId)) { throw new ArgumentException("Vault Secret Id missing", nameof(args.VaultSecretId)); } if (String.IsNullOrEmpty(args.VaultUri)) { throw new ArgumentException("Vault VaultUri missing", nameof(args.VaultUri)); } IAuthMethodInfo authMethod = new AppRoleAuthMethodInfo(args.VaultRoleId, secretId: args.VaultSecretId); _vaultClientSettings = new VaultClientSettings(args.VaultUri, authMethod) { VaultServiceTimeout = TimeSpan.FromMinutes(5) }; }
public static IDictionary <string, object> Read(VaultClientSettings clientSettings) { var vaultClient = new VaultClient(clientSettings); var secrets = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("thingspeak", mountPoint: "blog-demo").Result; return(secrets.Data.Data); }
public async Task AuthenticateWithUserPassKeyValueV2_GetNotFoundSecret_Fails() { // Arrange string secretPath = "mysecret"; string secretName = "my-value"; string expected = "s3cr3t"; string userName = "******"; string password = "******"; using (HashiCorpVaultTestServer server = await StartServerWithUserPassAsync(userName, password, DefaultDevMountPoint)) { await server.KeyValueV2.WriteSecretAsync( mountPoint : DefaultDevMountPoint, path : secretPath, data : new Dictionary <string, object> { ["unknown-prefix-" + secretName] = expected }); var authentication = new UserPassAuthMethodInfo(userName, password); var settings = new VaultClientSettings(server.ListenAddress.ToString(), authentication); var provider = new HashiCorpSecretProvider(settings, secretPath, new HashiCorpVaultOptions { KeyValueMountPoint = DefaultDevMountPoint, KeyValueVersion = VaultKeyValueSecretEngineVersion.V2 }, NullLogger <HashiCorpSecretProvider> .Instance); // Act string actual = await provider.GetRawSecretAsync(secretName); // Assert Assert.Null(actual); } }
/// <summary> /// <para> /// Adds the secrets of a HashiCorp Vault KeyValue engine to the secret store. /// </para> /// <para> /// See more information on HashiCorp: <a href="https://www.vaultproject.io/docs" />. /// </para> /// </summary> /// <param name="builder">The builder to add the HashiCorp secrets from the KeyValue Vault to.</param> /// <param name="vaultServerUriWithPort">The URI that points to the running HashiCorp Vault.</param> /// <param name="roleName"> /// The name of the role in the Kubernetes authentication. /// Role types have specific entities that can perform login operations against this endpoint. /// Constraints specific to the role type must be set on the role. These are applied to the authenticated entities attempting to login. /// </param> /// <param name="jsonWebToken">The service account JWT used to access the TokenReview API to validate other JWTs during login.</param> /// <param name="secretPath">The secret path where the secret provider should look for secrets.</param> /// <param name="configureOptions"></param> /// <param name="name">The unique name to register this HashiCorp provider in the secret store.</param> /// <param name="mutateSecretName">The optional function to mutate the secret name before looking it up.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="builder"/>.</exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="vaultServerUriWithPort"/> is blank or doesn't represent a valid URI, /// or the <paramref name="jsonWebToken"/> is blank, /// or the <paramref name="secretPath"/> is blank. /// </exception> public static SecretStoreBuilder AddHashiCorpVaultWithKubernetes( this SecretStoreBuilder builder, string vaultServerUriWithPort, string roleName, string jsonWebToken, string secretPath, Action <HashiCorpVaultKubernetesOptions> configureOptions, string name, Func <string, string> mutateSecretName) { Guard.NotNull(builder, nameof(builder), "Requires a secret store builder to add the HashiCorp Vault secret provider"); Guard.NotNullOrWhitespace(vaultServerUriWithPort, nameof(vaultServerUriWithPort), "Requires a valid HashiCorp Vault URI with HTTP port to connect to the running HashiCorp Vault"); Guard.NotNullOrWhitespace(jsonWebToken, nameof(jsonWebToken), "Requires a valid Json Web Token (JWT) during the Kubernetes authentication procedure"); Guard.NotNullOrWhitespace(secretPath, nameof(secretPath), "Requires a path where the HashiCorp Vault secrets are stored"); Guard.For <ArgumentException>(() => !Uri.IsWellFormedUriString(vaultServerUriWithPort, UriKind.RelativeOrAbsolute), "Requires a HashiCorp Vault server URI with HTTP port"); var options = new HashiCorpVaultKubernetesOptions(); configureOptions?.Invoke(options); IAuthMethodInfo authenticationMethod = new KubernetesAuthMethodInfo(options.KubernetesMountPoint, roleName, jsonWebToken); var settings = new VaultClientSettings(vaultServerUriWithPort, authenticationMethod); return(AddHashiCorpVault(builder, settings, secretPath, options, configureSecretProviderOptions: secretProviderOptions => { secretProviderOptions.Name = name; secretProviderOptions.MutateSecretName = mutateSecretName; })); }
/// <summary> /// <para> /// Adds the secrets of a HashiCorp Vault KeyValue engine to the secret store. /// </para> /// <para> /// See more information on HashiCorp: <a href="https://www.vaultproject.io/docs" />. /// </para> /// </summary> /// <param name="builder">The builder to add the HashiCorp secrets from the KeyValue Vault to.</param> /// <param name="vaultServerUriWithPort">The URI that points to the running HashiCorp Vault.</param> /// <param name="username">The username of the UserPass authentication method.</param> /// <param name="password">The password of the UserPass authentication method.</param> /// <param name="secretPath">The secret path where the secret provider should look for secrets.</param> /// <param name="configureOptions">The optional function to set the additional options to configure the HashiCorp Vault KeyValue.</param> /// <param name="name">The unique name to register this HashiCorp provider in the secret store.</param> /// <param name="mutateSecretName">The optional function to mutate the secret name before looking it up.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="builder"/> or <paramref name="secretPath"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"> /// Thrown when the <paramref name="vaultServerUriWithPort"/> is blank or doesn't represent a valid URI, /// or the <paramref name="username"/> or <paramref name="password"/> is blank, /// or the <paramref name="secretPath"/> is blank. /// </exception> public static SecretStoreBuilder AddHashiCorpVaultWithUserPass( this SecretStoreBuilder builder, string vaultServerUriWithPort, string username, string password, string secretPath, Action <HashiCorpVaultUserPassOptions> configureOptions, string name, Func <string, string> mutateSecretName) { Guard.NotNull(builder, nameof(builder), "Requires a secret store builder to add the HashiCorp Vault secret provider"); Guard.NotNullOrWhitespace(vaultServerUriWithPort, nameof(vaultServerUriWithPort), "Requires a valid HashiCorp Vault URI with HTTP port to connect to the running HashiCorp Vault"); Guard.NotNullOrWhitespace(username, nameof(username), "Requires a username for the UserPass authentication during connecting with the HashiCorp Vault"); Guard.NotNullOrWhitespace(password, nameof(password), "Requires a password for the UserPass authentication during connecting with the HashiCorp Vault"); Guard.NotNullOrWhitespace(secretPath, nameof(secretPath), "Requires a path where the HashiCorp Vault secrets are stored"); Guard.For <ArgumentException>(() => !Uri.IsWellFormedUriString(vaultServerUriWithPort, UriKind.RelativeOrAbsolute), "Requires a HashiCorp Vault server URI with HTTP port"); var options = new HashiCorpVaultUserPassOptions(); configureOptions?.Invoke(options); IAuthMethodInfo authenticationMethod = new UserPassAuthMethodInfo(options.UserPassMountPoint, username, password); var settings = new VaultClientSettings(vaultServerUriWithPort, authenticationMethod); return(AddHashiCorpVault(builder, settings, secretPath, options, configureSecretProviderOptions: secretProviderOptions => { secretProviderOptions.Name = name; secretProviderOptions.MutateSecretName = mutateSecretName; })); }
public Polymath(VaultClientSettings vaultClientSettings, HttpClient httpClient) { VaultClientSettings = vaultClientSettings; _httpClient = httpClient; ConfigureHttpClient(); _lazyVaultToken = GetLazyVaultToken(); }
public static IVaultClient GetVaultClient(string token, string vaultUri) { IAuthMethodInfo authMethod = new TokenAuthMethodInfo(token); var vaultClientSettings = new VaultClientSettings(vaultUri, authMethod); IVaultClient vaultClient = new VaultSharp.VaultClient(vaultClientSettings); return(vaultClient); }
private VaultClient CreateVaultUserClient() { var tokenClaim = User.FindFirst(VaultClaims.ClientToken); var settings = new VaultClientSettings(_vaultSettings.VaultEndpointUri, new TokenAuthMethodInfo(tokenClaim.Value)); var vaultClient = new VaultClient(settings); return(vaultClient); }
private IVaultClient CreateCreate(Uri address, IAuthMethodInfo authMethodInfo, string?expectedHostname) { var settings = new VaultClientSettings(address.ToString(), authMethodInfo) { MyHttpClientProviderFunc = CreateHttpClientHandler(expectedHostname) }; return(new VaultClient(settings)); }
public AppRoleVaultSharpService(IOptions <VaultSettings> options) { var configuration = options.Value; var authMethod = new AppRoleAuthMethodInfo(configuration.AppRoleId, configuration.AppRoleSecret); var settings = new VaultClientSettings(configuration.VaultEndpointUri, authMethod); VaultClient = new VaultClient(settings); }
public async Task Seal(SecureString token) { using (var t = token.Insecure()) { var vaultClientSettings = new VaultClientSettings(endpoint, new TokenAuthMethodInfo(t.Value)); var vc = new VaultClient(vaultClientSettings); await vc.V1.System.SealAsync(); } }
public async Task <Secret <ListInfo> > GetListAsync(string path) { var t = serviceToken.client_token; var vaultClientSettings = new VaultClientSettings(endpoint, new TokenAuthMethodInfo(t)); var vc = new VaultClient(vaultClientSettings); return(await vc.V1.Secrets.KeyValue.V1.ReadSecretPathsAsync(path)); }
private async Task LoadDataAsync(string secretPath, string jsonData) { var authMethod = new TokenAuthMethodInfo("root"); var vaultClientSettings = new VaultClientSettings("http://localhost:8200", authMethod); IVaultClient vaultClient = new VaultClient(vaultClientSettings); var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonData); await vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(secretPath, dictionary).ConfigureAwait(false); }
public VaultSrnProvider(IConfiguration options) { _mountPoint = options["MountPoint"]; // Instantiate the client var authMethod = new TokenAuthMethodInfo(options["Token"]); var settings = new VaultClientSettings(options["Url"], authMethod); _client = new VaultClient(settings); _engine = _client.V1.Secrets.KeyValue.V2; }
public static IConfigurationBuilder AddVault(this IConfigurationBuilder builder, string vaultUrl, string roleId, string secretId) { var buildConfig = builder.Build(); var vaultClientSettings = new VaultClientSettings(vaultUrl, new AppRoleAuthMethodInfo(roleId, secretId)); var vaultClient = new VaultClient(vaultClientSettings); var secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("settings/", null, "paymentservice/").Result; var dataDictionary = secret.Data.Data.Select(x => new KeyValuePair <string, string>(x.Key, x.Value.ToString())); return(builder.AddInMemoryCollection(dataDictionary)); }