Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add health cheks vault #2249

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion AspNetCore.Diagnostics.HealthChecks.sln
Original file line number Diff line number Diff line change
Expand Up @@ -305,12 +305,16 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.AzureServiceBu
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.Qdrant", "src\HealthChecks.Qdrant\HealthChecks.Qdrant.csproj", "{D8C3C460-7814-43C9-943D-3D79E1BC1C3C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HealthChecks.Qdrant.Tests", "test\HealthChecks.Qdrant.Tests\HealthChecks.Qdrant.Tests.csproj", "{7ECFCB71-4627-4671-9222-2C91EB8FB882}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.Qdrant.Tests", "test\HealthChecks.Qdrant.Tests\HealthChecks.Qdrant.Tests.csproj", "{7ECFCB71-4627-4671-9222-2C91EB8FB882}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.Milvus", "src\HealthChecks.Milvus\HealthChecks.Milvus.csproj", "{17913EAF-3B12-495B-80EA-9EB975FBE6BA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.Milvus.Tests", "test\HealthChecks.Milvus.Tests\HealthChecks.Milvus.Tests.csproj", "{D49CF52C-9D21-4D98-8A15-A2B259E9C003}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HealthChecks.Vault", "src\HealthChecks.Vault\HealthChecks.Vault.csproj", "{A4780D7C-0035-44BC-83D1-3CFB264F5A17}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HealthChecks.Vault.Tests", "test\HealthChecks.Vault.Tests\HealthChecks.Vault.Tests.csproj", "{A423ACC8-6AD9-4446-89BD-39CFF6C1D677}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -869,6 +873,14 @@ Global
{D49CF52C-9D21-4D98-8A15-A2B259E9C003}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D49CF52C-9D21-4D98-8A15-A2B259E9C003}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D49CF52C-9D21-4D98-8A15-A2B259E9C003}.Release|Any CPU.Build.0 = Release|Any CPU
{A4780D7C-0035-44BC-83D1-3CFB264F5A17}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A4780D7C-0035-44BC-83D1-3CFB264F5A17}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A4780D7C-0035-44BC-83D1-3CFB264F5A17}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A4780D7C-0035-44BC-83D1-3CFB264F5A17}.Release|Any CPU.Build.0 = Release|Any CPU
{A423ACC8-6AD9-4446-89BD-39CFF6C1D677}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A423ACC8-6AD9-4446-89BD-39CFF6C1D677}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A423ACC8-6AD9-4446-89BD-39CFF6C1D677}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A423ACC8-6AD9-4446-89BD-39CFF6C1D677}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1012,6 +1024,8 @@ Global
{7ECFCB71-4627-4671-9222-2C91EB8FB882} = {FF4414C2-8863-4ADA-8A1D-4B9F25C361FE}
{17913EAF-3B12-495B-80EA-9EB975FBE6BA} = {2A3FD988-2BB8-43CF-B3A2-B70E648259D4}
{D49CF52C-9D21-4D98-8A15-A2B259E9C003} = {FF4414C2-8863-4ADA-8A1D-4B9F25C361FE}
{A4780D7C-0035-44BC-83D1-3CFB264F5A17} = {2A3FD988-2BB8-43CF-B3A2-B70E648259D4}
{A423ACC8-6AD9-4446-89BD-39CFF6C1D677} = {FF4414C2-8863-4ADA-8A1D-4B9F25C361FE}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2B8C62A1-11B6-469F-874C-A02443256568}
Expand Down
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="System.Text.RegularExpressions" Version="4.3.1" />
<PackageVersion Include="System.Threading.Channels" Version="8.0.0" />
<PackageVersion Include="Testcontainers" Version="4.0.0" />
<PackageVersion Include="VaultSharp" Version="1.17.5.1" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions src/HealthChecks.UI/assets/1ae4e3706fe3f478fcc1.woff2

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using HealthChecks.Vault;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using VaultSharp;


namespace Microsoft.Extensions.DependencyInjection;


/// <summary>
/// Extension methods to configure vault services.
/// </summary>
public static class VaultHealthChecksBuilderExtension
{
private const string NAME = "vault";

/// <summary>
/// Add a health check for vault services.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="clientFactory">
/// An optional factory to obtain <see cref="IVaultClient" /> instance.
/// When not provided, <see cref="IVaultClient" /> is simply resolved from <see cref="IServiceProvider"/>.</param>
/// <param name="name">The health check name. Optional. If <c>null</c> the type name 'vault' will be used for the name.</param>
/// <param name="failureStatus">
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
/// </param>
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
/// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
/// <returns>The specified <paramref name="builder"/>.</returns>
public static IHealthChecksBuilder AddVault(
this IHealthChecksBuilder builder,
Func<IServiceProvider, IVaultClient>? clientFactory = default,
string? name = null,
HealthStatus? failureStatus = default,
IEnumerable<string>? tags = default,
TimeSpan? timeout = default)
{
return builder.Add(new HealthCheckRegistration(
name ?? NAME,
sp => new VaultHealthChecks(clientFactory?.Invoke(sp) ?? sp.GetRequiredService<IVaultClient>()),
failureStatus,
tags,
timeout));
}
}
12 changes: 12 additions & 0 deletions src/HealthChecks.Vault/HealthChecks.Vault.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(DefaultLibraryTargetFrameworks)</TargetFrameworks>
<PackageTags>$(PackageTags);Vault</PackageTags>
<Description>HealthChecks.Vault is the health check package for Hashicorp Vault.</Description>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="VaultSharp"></PackageReference>
</ItemGroup>

</Project>
35 changes: 35 additions & 0 deletions src/HealthChecks.Vault/VaultHealthChecks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using VaultSharp;

namespace HealthChecks.Vault;

public class VaultHealthChecks : IHealthCheck
{
private readonly IVaultClient _vaultClient;

public VaultHealthChecks(IVaultClient vaultClient)
{
_vaultClient = Guard.ThrowIfNull(vaultClient);
}

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
var healthStatus = await _vaultClient.V1.System
.GetHealthStatusAsync()
.ConfigureAwait(false);

if (healthStatus.Initialized && healthStatus.Sealed)
return new HealthCheckResult(context.Registration.FailureStatus, description: "Vault is initialized but sealed.");
else if (!healthStatus.Initialized)
return new HealthCheckResult(context.Registration.FailureStatus, description: "Vault is not initialized.");

return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using VaultSharp;
using VaultSharp.V1.AuthMethods;
using VaultSharp.V1.AuthMethods.Token;

namespace HealthChecks.Vault.Tests.DependencyInjection;

public class vault_registration_should
{
[Fact]
public void add_health_check_when_properly_configured()
{
var services = new ServiceCollection();
services.AddHealthChecks()
.AddVault(Factory);

using var serviceProvider = services.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>();

var registration = options.Value.Registrations.First();
var check = registration.Factory(serviceProvider);

registration.Name.ShouldBe("vault");
check.ShouldBeOfType<VaultHealthChecks>();
}

[Fact]
public void add_named_health_check_when_properly_configured()
{
var services = new ServiceCollection();
services.AddHealthChecks()
.AddVault(clientFactory: Factory, name: "vault");

using var serviceProvider = services.BuildServiceProvider();
var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>();

var registration = options.Value.Registrations.First();
var check = registration.Factory(serviceProvider);

registration.Name.ShouldBe("vault");
check.ShouldBeOfType<VaultHealthChecks>();
}

private IVaultClient Factory(IServiceProvider _)
{
IAuthMethodInfo authMethod = new TokenAuthMethodInfo("token");
return new VaultClient(new VaultClientSettings("http://localhost:8200", authMethod));
}
}
40 changes: 40 additions & 0 deletions test/HealthChecks.Vault.Tests/Fixtures/VaultContainerFixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using DotNet.Testcontainers.Containers;
using DotNet.Testcontainers.Builders;

namespace HealthChecks.Vault.Tests.Fixtures;

public class VaultContainerFixture : IAsyncLifetime
{
public string RootToken { get; } = "root";

private readonly IContainer _container;

public string GetConnectionString()
{
if (_container is null)
throw new InvalidOperationException("container is not initialized");
return $"http://localhost:{_container.GetMappedPublicPort(8200)}";
}

public VaultContainerFixture()
{
_container = new ContainerBuilder()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this repo we typically configure the containers from github workflow level, here you can find some examples of how we do that:

https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_cd.yml
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_cd_preview.yml
https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/.github/workflows/healthchecks_redis_ci.yml

could you please do that for this project as well (we need that to be able to run the tests in the CI) and remove the dependency to Testcontainers?

I am not saying that Testcontainers are bad (it actually looks very neat), we just use a different approach in this repo and I would prefer for all of the health checks to implement the same pattern.

.WithImage("hashicorp/vault:1.18")
.WithPortBinding(8200, true)
.WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8200)))
.WithEnvironment("VAULT_DEV_ROOT_TOKEN_ID", RootToken)
.WithEnvironment("VAULT_LOCAL_CONFIG", "{\"backend\": {\"file\": {\"path\": \"/vault/file\"}}, \"default_lease_ttl\": \"168h\", \"max_lease_ttl\": \"720h\"}")
.WithCommand($"server -dev -dev-root-token-id={RootToken}")
.Build();
}

public async Task InitializeAsync() => await _container.StartAsync();

public async Task DisposeAsync()
{
if (_container != null)
{
await _container.StopAsync();
}
}
}
109 changes: 109 additions & 0 deletions test/HealthChecks.Vault.Tests/Functional/HealthChecksVaultTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System.Net;
using VaultSharp;
using VaultSharp.V1.AuthMethods;
using VaultSharp.V1.AuthMethods.Token;

namespace HealthChecks.Vault.Tests.Functional;

public class vault_healthcheck_should : IClassFixture<Fixtures.VaultContainerFixture>
{
private readonly Fixtures.VaultContainerFixture _vaultContainerFixture;

public vault_healthcheck_should(Fixtures.VaultContainerFixture vaultContainerFixture)
{
_vaultContainerFixture = vaultContainerFixture;
}

[Fact]
public async Task be_healthy_when_vault_is_available_using_client_factory()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services
.AddHealthChecks()
.AddVault(
clientFactory: sp =>
{
var vaultAddress = _vaultContainerFixture.GetConnectionString();
var rootToken = _vaultContainerFixture.RootToken;
IAuthMethodInfo authMethod = new TokenAuthMethodInfo(rootToken);
var vaultClientSettings = new VaultClientSettings(vaultAddress, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
return vaultClient;
}, tags: new string[] { "vault" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("vault")
});
});

using var server = new TestServer(webHostBuilder);

using var response = await server.CreateRequest("/health").GetAsync();

response.StatusCode.ShouldBe(HttpStatusCode.OK);
}

[Fact]
public async Task be_healthy_when_vault_is_available_using_singleton()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
var vaultAddress = _vaultContainerFixture.GetConnectionString();
var rootToken = _vaultContainerFixture.RootToken;
IAuthMethodInfo authMethod = new TokenAuthMethodInfo(rootToken);
var vaultClientSettings = new VaultClientSettings(vaultAddress, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);

services
.AddSingleton(vaultClient)
.AddHealthChecks()
.AddVault(tags: new string[] { "vault" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("vault")
});
});

using var server = new TestServer(webHostBuilder);

using var response = await server.CreateRequest("/health").GetAsync();

response.StatusCode.ShouldBe(HttpStatusCode.OK);
}

[Fact]
public async Task be_unhealthy_when_vault_is_unavailable()
{
var webHostBuilder = new WebHostBuilder()
.ConfigureServices(services =>
{
services
.AddHealthChecks()
.AddVault(
clientFactory: sp => new VaultClient(new VaultClientSettings("http://localhost:8200", new TokenAuthMethodInfo("root"))), tags: new string[] { "vault" });
})
.Configure(app =>
{
app.UseHealthChecks("/health", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("vault")
});
});

using var server = new TestServer(webHostBuilder);

using var response = await server.CreateRequest("/health").GetAsync();

response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
}
}

6 changes: 6 additions & 0 deletions test/HealthChecks.Vault.Tests/HealthChecks.Vault.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\src\HealthChecks.Vault\HealthChecks.Vault.csproj" />
<PackageReference Include="Testcontainers"/>
</ItemGroup>
</Project>
15 changes: 15 additions & 0 deletions test/HealthChecks.Vault.Tests/HealthChecks.Vault.approved.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace HealthChecks.Vault
{
public class VaultHealthChecks : Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck
{
public VaultHealthChecks(VaultSharp.IVaultClient vaultClient) { }
public System.Threading.Tasks.Task<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult> CheckHealthAsync(Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context, System.Threading.CancellationToken cancellationToken = default) { }
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class VaultHealthChecksBuilderExtension
{
public static Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder AddVault(this Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder builder, System.Func<System.IServiceProvider, VaultSharp.IVaultClient>? clientFactory = null, string? name = null, Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus? failureStatus = default, System.Collections.Generic.IEnumerable<string>? tags = null, System.TimeSpan? timeout = default) { }
}
}