/// <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 (IVaultClient client, VaultClientSettings settings) GetClientAndSettings(VaultOptions options) { var settings = new VaultClientSettings(options.Url, GetAuthMethod(options)); var client = new VaultClient(settings); return(client, settings); }
public async Task CanRequestSealStatus() { var vault = new VaultClient(_uri, _token); var response = await vault.SealStatusAsync(); Assert.NotNull(response); Assert.Equal(false, response.Sealed); }
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 static async Task <LeaderStatus> GetLeaderAsync(this VaultClient client, SystemBackendOptions options = null) { return(await((IProtocolSource)client).Protocol .SendGetAsync <LeaderStatus>("sys/leader", options: options)); }
public static async Task DoSealAsync(this VaultClient client, SystemBackendOptions options = null) { await((IProtocolSource)client).Protocol .SendPutAsync <NoContentResponse>("sys/seal", options: options); }
public static async Task <KeyStatus> GetKeyStatusAsync(this VaultClient client, SystemBackendOptions options = null) { return(await((IProtocolSource)client).Protocol .SendGetAsync <KeyStatus>("sys/key-status", options: options)); }
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 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; } }
public static async Task <ReadResponse <Dictionary <string, object> > > UnwrapData( this VaultClient client, string token = null, SystemBackendOptions options = null) { return(await UnwrapData <Dictionary <string, object> >(client, token, options)); }
/// <summary> /// Creates a new orphan token. /// A root token is not required to create an orphan token /// (otherwise set with the no_parent option). /// </summary> /// <remarks> /// Certain options are only available when called by a root token. /// </remarks> public static async Task <ReadResponse <EmptyData> > CreateOrphanTokenAsync(this VaultClient client, CreateParameters createParameters = null, TokenAuthOptions options = null) { return(await CreateTokenAsync(client, true, null, createParameters, options : options)); }
/// <summary> /// Update an existing user. /// </summary> /// <param name="client"></param> /// <param name="username">The username of the user to update.</param> /// <param name="password">The password for the user.</param> /// <param name="policies">List of policies. If set to empty, only the default policy will be applicable to the user.</param> /// <param name="ttl">The lease duration which decides login expiration.</param> /// <param name="maxTtl">Maximum duration after which login should expire.</param> /// <param name="options"></param> /// <returns></returns> public static async Task UpdateUserpassUserAsync(this VaultClient client, string username, string password = null, string[] policies = null, Duration?ttl = null, Duration?maxTtl = null, UserpassAuthOptions options = null) { if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } var payload = new UserData { Password = password, Ttl = ttl, MaxTtl = maxTtl, }; if (policies?.Length > 0) { payload.Policies = string.Join(",", policies); } var mountName = options?.MountName ?? DefaultMountName; await((IProtocolSource)client).Protocol .SendPostAsync <NoContentResponse>( $"auth/{mountName}/users/{username}", payload, options: options); }
public async Task CanUseAppIdAuthentication() { var vault = new VaultClient(_uri, _appId); await vault.WriteSecretAsync("foo", new Dictionary <string, object> { { "foo", "bar" } }); }
/// <summary> /// Registers a new plugin, or updates an existing one with the supplied name. /// </summary> /// <param name="client"></param> /// <param name="name">Specifies the name for this plugin. The name is what is used to /// look up plugins in the catalog.</param> /// <param name="sha256">This is the SHA256 sum of the plugin's binary. Before a plugin /// is run it's SHA will be checked against this value, if they do not match the /// plugin can not be run.</param> /// <param name="command">Specifies the command used to execute the plugin. This is /// relative to the plugin directory. Example: <c>>myplugin --my_flag=1<c>></param> /// <param name="args"></param> /// <param name="options"></param> /// <remarks> /// <para> /// <b><i>sudo required – This operation requires sudo capability in addition to any /// path-specific capabilities.</i></b> /// </para> /// </remarks> public static async Task RegisterPluginAsync( this VaultClient client, string name, string sha256, string command, string[] args = null, SystemBackendOptions options = null) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (string.IsNullOrEmpty(sha256)) { throw new ArgumentNullException(nameof(sha256)); } if (string.IsNullOrEmpty(command)) { throw new ArgumentNullException(nameof(command)); } name = name.TrimStart('/'); await client.WriteAsync($"sys/plugins/catalog/{name}", new RegisterPluginRequest { Sha256 = sha256, Command = command, Args = args, }, options : options); }
public ExplorerForm(Uri baseUri, IAuthenticationMethod auth) { InitializeComponent(); _client = new VaultClient(baseUri, auth); secretDataGridView.DataSource = _secretValues; mountsListBox.DataSource = _mounts; }
public void ServiceClient_AuthTokenSet_Authenticate() { // Arrange var vaultClientUriFake = A.Fake <IVaultClientUri>(); var httpAuthFake = A.Fake <IVaultAuth>(); A.CallTo(() => httpAuthFake.AuthToken).Returns("AUTH12345"); var httpClientFake = A.Fake <IVaultHttpClient>(); A.CallTo(() => vaultClientUriFake.ServiceClient).Returns(httpClientFake); A.CallTo(() => httpClientFake.AddHeader("X-Vault-Token", "AUTH12345")); var client = new VaultClient(vaultClientUriFake, httpAuthFake); // Act var serviceClient = client.ServiceClient; // Assert serviceClient.Should().Be(httpClientFake); A.CallTo(() => httpAuthFake.AuthToken).MustHaveHappened(); A.CallTo(() => vaultClientUriFake.ServiceClient).MustHaveHappened(); A.CallTo(() => httpClientFake.AddHeader("X-Vault-Token", "AUTH12345")); }
public async Task CanChangeAuthenticationMethod() { var vault = new VaultClient(_uri, _token); await vault.WriteSecretAsync("foo", new Dictionary<string, object> { { "foo", "bar" } }); await vault.AuthenticateAsync(_appId); await vault.WriteSecretAsync("foo", new Dictionary<string, object> { { "foo", "bar" } }); }
public static async Task UpdateUserpassUserPasswordAsync(this VaultClient client, string username, string password, UserpassAuthOptions options = null) { if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } var payload = new UserData { Password = password, }; var mountName = options?.MountName ?? DefaultMountName; await((IProtocolSource)client).Protocol .SendPostAsync <NoContentResponse>( $"auth/{mountName}/users/{username}/password", payload, options: options); }
/// <summary> /// Mounts a new secret backend at the given path. /// </summary> /// <param name="client"></param> /// <param name="path">Specifies the path where the secret backend will be mounted.</param> /// <param name="type">Specifies the type of the backend, such as <c>aws</c>.</param> /// <param name="description">Specifies the human-friendly description of the mount.</param> /// <param name="config">Specifies configuration options for this mount.</param> /// <param name="local">Specifies if the secret backend is a local mount only. /// Local mounts are not replicated nor (if a secondary) removed by replication.</param> /// <param name="options"></param> /// <remarks> /// <para> /// This <c>config</c> an object with these possible values: /// <list> /// <item>default_lease_ttl</item> /// <item>max_lease_ttl</item> /// <item>force_no_cache</item> /// <item>plugin_name</item> /// </list> /// These control the default and maximum lease time-to-live, and force disabling /// backend caching respectively. If set on a specific mount, this overrides the /// global defaults. /// </para><para> /// <b><i>The <c>local</c> option is allowed in Vault open-source, but relevant functionality /// is only supported in Vault Enterprise.</i></b> /// </para> public static async Task MountBackendAsync( this VaultClient client, string path, string type, string description = null, Dictionary <string, object> config = null, bool?local = null, SystemBackendOptions options = null) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(type)) { throw new ArgumentNullException(nameof(type)); } path = path.Trim('/'); await((IProtocolSource)client).Protocol.SendPostAsync <NoContentResponse>( $"sys/mounts/{path}", new MountBackendRequest { Type = type, Description = description, Config = config, Local = local, }, options: options); }
/// <summary> /// Create a new user. Honors the capabilities inside ACL policies. /// </summary> /// <param name="client"></param> /// <param name="username">The username for the user.</param> /// <param name="password">The password for the user, required when creating the user.</param> /// <param name="policies">List of policies. If set to empty, only the default policy will be applicable to the user.</param> /// <param name="ttl">The lease duration which decides login expiration.</param> /// <param name="maxTtl">Maximum duration after which login should expire.</param> /// <param name="options"></param> /// <returns></returns> public static async Task CreateUserpassUserAsync(this VaultClient client, string username, string password, string[] policies = null, Duration?ttl = null, Duration?maxTtl = null, UserpassAuthOptions options = null) { if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username)); } if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } // Create is the same as Update, only the initial password is required await UpdateUserpassUserAsync(client, username, password : password, policies : policies, ttl : ttl, maxTtl : maxTtl, options : options); }
public async Task AuthUserPass_LoginWithNewClient_LogsInSuccessfully() { using (var server = new VaultTestServer()) { var client = server.TestClient(); var mountPoint = Guid.NewGuid().ToString(); await client.Sys.EnableAuth(mountPoint, "userpass", "Userpass Mount"); var username = Guid.NewGuid().ToString(); var password = Guid.NewGuid().ToString(); var usersRequest = new UsersRequest { Password = password, Policies = new List <string> { "default" }, Ttl = "1h", MaxTtl = "2h" }; await client.Auth.Write($"{mountPoint}/users/{username}", usersRequest); var loginRequest = new LoginRequest { Password = usersRequest.Password }; var newClient = new VaultClient(new UriBuilder(server.ListenAddress).Uri); var loginResponse = await newClient.Auth.Write <LoginRequest, NoData>($"{mountPoint}/login/{username}", loginRequest); Assert.Equal(username, loginResponse.Auth.Metadata["username"]); Assert.Equal(usersRequest.Policies, loginResponse.Auth.Policies); Assert.NotNull(loginResponse.Auth.ClientToken); } }
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 static async Task GetSecretsAsync(this ICakeContext context, string url, string token, string path, string output ) { if (context == null) { throw new ArgumentNullException(nameof(context)); } try { var client = new VaultClient(new VaultClientSettings(url, new TokenAuthMethodInfo(token))); var secrets = await client.V1.Secrets.KeyValue.V2.ReadSecretAsync(path); var data = JsonConvert.SerializeObject(secrets.Data.Data); File.WriteAllText(output, data); } catch (Exception e) { context.Log.Error(e.Message); context.Log.Error(e.StackTrace); throw; } }
public VaultConfigurationTests(VaultFixture fixture) { _authMethod = new TokenAuthMethodInfo(fixture.Api.Token); _uri = fixture.Api.Url; _engineName = "kv"; _vaultClient = new VaultClient(new VaultClientSettings(_uri, _authMethod)); }
/// <summary> /// Lists the plugins in the catalog. /// </summary> public static async Task <ReadResponse <KeysData> > ListPluginsAsync( this VaultClient client, SystemBackendOptions options = null) { return(await client.ListAsync <ReadResponse <KeysData> >("sys/plugins/catalog", on404 : resp => null, options : options)); }
private async Task LoadAsync() { VaultClient vaultClient = new VaultClient(new VaultOptions { Address = this.address, Token = this.token }); await this.Recurse(vaultClient, this.serviceName); }
public Endpoint(VaultClient client, string basePath = null) { _client = client; var path = basePath != null ? $"/{basePath}" : ""; _uriBasePath = $"{UriRootPath}{path}"; }
public async Task CanGetMounts() { var vault = new VaultClient(_uri, _token); var mounts = await vault.GetMountsAsync(); Assert.NotNull(mounts); Assert.True(mounts.Count >= 1); }
/// <summary> /// Creates a new token against the specified role name. /// This may override options set during the call. /// </summary> /// <remarks> /// Certain options are only available when called by a root token. /// </remarks> public static async Task <ReadResponse <EmptyData> > CreateRoleTokenAsync(this VaultClient client, string roleName, CreateParameters createParameters = null, TokenAuthOptions options = null) { return(await CreateTokenAsync(client, false, roleName, createParameters, options : options)); }
private int countItem(VaultClient vaultClient) { int itemCount = vaultClient.GetItemRevisionCount("COMMENT = 'RES-2' AND FOLDERGUID = 'XXXXXXX'"); Console.WriteLine("Count is " + itemCount.ToString()); return(itemCount); }
async Task<string> IAuthenticationMethod.GetTokenAsync(VaultClient server) { var parameters = new { app_id = _appId, user_id = _userId, }; var lease = await server.PostAsync<Lease>("auth/" + _path + "/login", parameters).ConfigureAwait(false); return lease.Auth.ClientToken; }
public async Task CanSealAndUnseal() { var vault = new VaultClient(_uri, _token); var response = await vault.SealStatusAsync(); Assert.False(response.Sealed, "Vault was already sealed"); await vault.SealAsync(); response = await vault.SealStatusAsync(); Assert.True(response.Sealed, "The Vault did not seal"); response = await vault.UnsealAsync(Configuration.UnsealKey); Assert.False(response.Sealed, "The Vault did not unseal"); }
Task<string> IAuthenticationMethod.GetTokenAsync(VaultClient server) { return Task.FromResult(_token); }
public async Task CanUseAppIdAuthentication() { var vault = new VaultClient(_uri, _appId); await vault.WriteSecretAsync("foo", new Dictionary<string, object> { { "foo", "bar" } }); }
public async Task CanWriteAndReadSecrets() { var path = "secret/foo"; var expectedValue = Guid.NewGuid().ToString(); var obj = new Dictionary<string, object>() { { "Value", expectedValue } }; var vault = new VaultClient(_uri, _token); await vault.WriteSecretAsync(path, obj); var result = await vault.LeaseAsync(path); Assert.NotNull(result); Assert.Equal(expectedValue, result.Data["Value"]); }
/// <summary> /// Creates an instance of the vault client, with the provided <see cref="IAuthenticationInfo" /> used to authenticate and authorize the user. /// This is the typical client you would need for your consuming applications. /// <para> /// If you need an instance of an administrative/root user based <see cref="IVaultClient" />, pass a <see cref="IAuthenticationInfo" /> with a root policy mapping. /// If you need an instance of an unauthenticated <see cref="IVaultClient" />, pass a <value>null</value> value for <see cref="IAuthenticationInfo" />. /// An unauthenticated client can do very few operations. e.g. Check seal status, initialization status etc. /// </para><para>var vaultClient = VaultClientFactory.CreateVaultClient(new Uri("http://127.0.0.1:8200", new GitHubAuthenticationInfo(personalAccessToken: "YOUR_TOKEN"));</para><para>var administrativeVaultClient = VaultClientFactory.CreateVaultClient(new Uri("http://127.0.0.1:8200", new TokenAuthenticationInfo(token: "ROOT_POLICY_TOKEN"));</para><para>var unauthenticatedVaultClient = VaultClientFactory.CreateVaultClient(new Uri("http://127.0.0.1:8200", authenticationInfo: null));</para> /// </summary> /// <param name="vaultServerUriWithPort"><para>[required]</para> /// The vault server URI with port.</param> /// <param name="authenticationInfo"><para>[optional]</para> /// The authentication information. e.g. GitHub, AppId, LDAP etc.</param> /// <param name="continueAsyncTasksOnCapturedContext"><para>[optional]</para> /// if set to <c>true</c> [continue asynchronous tasks on captured context].</param> /// <param name="serviceTimeout"><para>[optional]</para> /// The timeout value for the Vault Service calls. Do not specify a value, if you want to go with the default timeout values.</param> /// <param name="postHttpClientInitializeAction"><para>[optional]</para> /// A post-processing delegate on the <see cref="HttpClient"/> instance used by the library. /// This can be used to setup any custom message handlers, proxy settings etc. /// Please note that the delegate will get an instance of <see cref="HttpClient"/> that is initialized with the address /// and timeout settings. /// </param> /// <returns> /// An instance of the <see cref="IVaultClient" /> interface implementation. /// </returns> public static IVaultClient CreateVaultClient(Uri vaultServerUriWithPort, IAuthenticationInfo authenticationInfo, bool continueAsyncTasksOnCapturedContext = false, TimeSpan? serviceTimeout = null, Action<HttpClient> postHttpClientInitializeAction = null) { IVaultClient vaultClient = new VaultClient(vaultServerUriWithPort, authenticationInfo, continueAsyncTasksOnCapturedContext, serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction); return vaultClient; }
public async Task WritingSecretsThrowsAVaultExceptionWhenNotAuthorized() { var badToken = new TokenAuthentication(Guid.NewGuid().ToString()); var vault = new VaultClient(_uri, badToken); await Assert.ThrowsAsync<VaultException>(() => vault.WriteSecretAsync("foo", EMPTY_SECRET)); }