Elvia.Configuration 8.0.0-beta2

This is a prerelease version of Elvia.Configuration.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Elvia.Configuration --version 8.0.0-beta2
                    
NuGet\Install-Package Elvia.Configuration -Version 8.0.0-beta2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Elvia.Configuration" Version="8.0.0-beta2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Elvia.Configuration" Version="8.0.0-beta2" />
                    
Directory.Packages.props
<PackageReference Include="Elvia.Configuration" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Elvia.Configuration --version 8.0.0-beta2
                    
#r "nuget: Elvia.Configuration, 8.0.0-beta2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Elvia.Configuration@8.0.0-beta2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Elvia.Configuration&version=8.0.0-beta2&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Elvia.Configuration&version=8.0.0-beta2&prerelease
                    
Install as a Cake Tool

libraries-elvia-config-lib

Get secrets from Hashicorp Vault.

Supports - in order:

  • Vault Token
  • Kubernetes
  • Approle (role-id)
  • Entra ID

See CHANGELOG.md for breaking changes and release history.

Usage

using Elvia.Configuration;
using Elvia.Configuration.HashiVault;

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddHashiVaultSecrets();

// Alternative using Configuration
var env = builder.Configuration.EnsureHasValue("shared:kv:info:environment");
Console.WriteLine(env);

// Alternative using static methods
var env2 = await HashiVault.EnsureHasValueAsync("shared/kv/info/environment");
Console.WriteLine(env2);

// Optional cancellation: async HashiVault methods and IVaultClient secret, transit,
// signing and TOTP methods take an optional CancellationToken as last parameter
var env3 = await HashiVault.EnsureHasValueAsync("shared/kv/info/environment", cancellationToken);

See https://elvia.atlassian.net/wiki/spaces/Utviklerhandbok/pages/1944912100/Use+of+Hashicorp+Vault+from+dotnet+core

Per-provider Vault options

Use AddHashiVaultSecretsWithOptions to override settings without changing process environment variables or the shared static HashiVault client. Supply a logger factory configured by your application (it can be created before the host is built):

using var vaultLoggerFactory = LoggerFactory.Create(logging => logging.AddConsole());

builder.Configuration.AddHashiVaultSecretsWithOptions(options =>
{
    options.VaultAddress = "https://vault.example";
    options.VaultToken = tokenFromSecureSource;
    options.CacheTtl = TimeSpan.FromSeconds(10);
    options.DebugEnabled = false;
    options.TimeProvider = TimeProvider.System;
    options.LoggerFactory = vaultLoggerFactory;
});

The callback runs once at registration and its options are copied. Each built root owns its independent client and HTTP transport. The supplied TimeProvider and LoggerFactory remain caller-owned; keep the logger factory alive until the configuration root has been disposed. DebugEnabled is per provider (default false) and does not modify HashiVault.DebugEnabled. The clock defaults to TimeProvider.System and controls Vault leases and cache expiry. The provider remains lazy; registration/build does not log in or preload secrets, but building the root can log configuration diagnostics.

Vault diagnostics use source-generated, structured ILogger events in the Elvia.Configuration.HashiVault.Client.* categories. Authentication method and connection selection are Debug; fallback to the default Vault address, unsupported GitHub authentication, KV v1 fallback after a mount-metadata 403, and token-cache/browser-response problems are Warning. Tokens, role IDs, JWTs and Vault response bodies are not included in diagnostics. Each component keeps a logger internally; logging is configured once through options, not through logging parameters or warning callbacks on Vault operations. The factory and loggers are never stored globally or disposed by the library. An unset LoggerFactory uses NullLogger and is silent by default, including warnings. DebugEnabled = true additionally writes diagnostics to the console, independently of logger filters; it can duplicate configured console logging. The legacy static HashiVault.DebugEnabled switch still enables console diagnostics for static APIs (including Google credential-file warnings). Default token-cache and Google credential-file loggers read that switch at each log event; per-provider diagnostics remain isolated from it. The browser-based Entra ID login flow and its success/error pages are unchanged. The AddConsole() example requires the application's Microsoft.Extensions.Logging.Console package; the library only adds a direct dependency on Microsoft.Extensions.Logging.Abstractions.

Explicit option values override the corresponding environment variables; null string options fall back to environment values and then existing cluster/local defaults. Empty strings explicitly override environment values as empty. Supported mappings:

Option Environment variable
VaultAddress VAULT_ADDR
VaultToken VAULT_TOKEN
RoleId ROLE_ID
MountPath, Role MOUNT_PATH, ROLE
ServiceAccountPath SERVICE_ACCOUNT_PATH
KubernetesNamespace KUBERNETES_NAMESPACE
VaultCaCert VAULT_CACERT
ElviaEnvironment ELVIA_ENVIRONMENT

CacheTtl = null retains ELVIA_VAULT_CACHE_TTL_SECONDS and its five-second default; an explicit non-negative duration takes precedence, including over an invalid environment value. Zero disables secret caching. The separate mount metadata TTL remains one hour. Authentication order and address/CA precedence over cluster settings are unchanged.

The distinct method name preserves source compatibility: existing AddHashiVaultSecrets(), AddHashiVaultSecrets(null) and injected-factory calls remain unambiguous and unchanged.

Authentication and environment variables

Authentication uses the first applicable method in this order:

  1. VAULT_TOKEN selects Vault token authentication.
  2. Kubernetes service-account authentication is selected in an Atlas cluster, that is a Kubernetes pod with the mounted service-account files and ELVIA_ENVIRONMENT set.
  3. ROLE_ID selects AppRole authentication.
  4. Outside Atlas, including Kubernetes pods without ELVIA_ENVIRONMENT (for example elvia-runner), Entra ID is the local-development fallback, and https://vault.dev-elvia.io is the default address when VAULT_ADDR is not set. A configured GITHUB_TOKEN is not supported and does not select an authentication method.

The same selection logic validates the configuration when a client is created and chooses the method at login. VAULT_ADDR is only required when VAULT_TOKEN or ROLE_ID authentication is selected, and explicit MOUNT_PATH together with ROLE bypasses service-account name parsing.

When using the options API, a non-null option takes precedence over its corresponding environment variable. Null string options use the environment variable, then the library's defaults. The static API reads the process environment directly. These are all environment variables read by the library:

Environment variable Purpose / options mapping
VAULT_ADDR Vault URL; VaultAddress
VAULT_TOKEN Vault token authentication; VaultToken
ROLE_ID AppRole authentication; RoleId
MOUNT_PATH Kubernetes auth mount override; MountPath
ROLE Kubernetes auth role override; Role
SERVICE_ACCOUNT_PATH Kubernetes service-account token file; ServiceAccountPath
KUBERNETES_NAMESPACE Kubernetes namespace; KubernetesNamespace
KUBERNETES_SERVICE_HOST Kubernetes-injected in-cluster API host; no options override
KUBERNETES_SERVICE_PORT Kubernetes-injected in-cluster API port; no options override
VAULT_CACERT Path to the Vault CA certificate file; VaultCaCert
ELVIA_ENVIRONMENT Atlas environment marker; ElviaEnvironment
ELVIA_VAULT_CACHE_TTL_SECONDS Secret-cache lifetime in seconds; CacheTtl
GITHUB_TOKEN Detected only to report that the removed GitHub auth method is unsupported

VAULT_ADDR overrides the Atlas ConfigMap hostname, and VAULT_CACERT selects a Vault CA file instead of the ConfigMap CA. Kubernetes settings in the vault ConfigMap are read once per client. The default service-account token path is /var/run/secrets/kubernetes.io/serviceaccount/token.

Entra ID is intended for local development and is blocked when VAULT_ADDR targets the production Vault host vault.elvia.io. For production, configure a Vault token with VAULT_TOKEN or HashiVaultOptions.VaultToken.

The local Entra ID token cache is stored per Vault host at <LocalApplicationData>/Elvia/Vault/token-{host}.json (for example, under the user's local application data directory on Windows). On Linux and macOS, the cache directory and file use owner-only permissions.

Vault paths and key matching

Vault paths can be written with / separators or as configuration keys with : separators. For example, the static API path system/kv/path/key corresponds to the configuration key system:kv:path:key. The path is system/kv/path, and key is the field in that secret; kv is the KV engine segment. Use / paths with the static HashiVault methods and : keys when reading from IConfiguration.

KV v1 and v2 mounts are both supported. The client checks the mount's KV version and uses the corresponding Vault API path; successful mount-version checks are cached for one hour. If Vault denies mount metadata access, the client falls back to KV v1.

Configuration key matching is case-insensitive. Hyphens and underscores are treated as equivalent, and matching also tries forms with separators removed. For example, client-id, client_id, and clientid can resolve to the same Vault field.

Lookup and cache behavior

The configuration provider is lazy: registering it or building a root does not preload secrets. The first lookup, and a refresh after cache expiry, can make synchronous network calls to Vault. Successful secret dictionaries are cached per client and dictionary path for five seconds by default. Set ELVIA_VAULT_CACHE_TTL_SECONDS to a non-negative integer before client creation to change the TTL; 0 disables secret caching, while negative or invalid values fail at client creation. Concurrent lookups of one dictionary share a load. Failures and missing values are not cached, and expired values are not served after a failed refresh. The mount-version metadata cache is separate.

Additional Vault operations

The static HashiVault API includes listing and configuration-section helpers. Transit and TOTP operations are available on an independent IVaultClient created by the static factory:

var names = await HashiVault.ListSecretsAsync("system/kv/path");
var section = HashiVault.GetSection("system:kv:path");
var value = section["key"];

var client = HashiVault.CreateVaultClient();
try
{
    var ciphertext = await client.EncryptText("transit", "key", "secret text");
    var isValid = await client.VerifyTotp("user-id", "123456");
}
finally
{
    (client as IDisposable)?.Dispose();
}

ListSecrets lists names in a Vault folder; GetSection exposes a Vault path as an IConfigurationSection. Transit clients also support decrypting, base64 encryption/decryption, and signing/verifying signatures. TOTP clients can register a user (returning a URL and base64 QR code) and verify a code. Reuse the client and dispose it after its operations complete.

To load a Google service-account key from Vault, call the static configuration extension:

builder.Configuration.UseGoogleServiceAccount(
    "mdmx/kv/gcp-serviceaccounts/ingress-structuredata");

This reads the service-account-key field, writes credentials to an absolute process-specific temporary file (not the working directory), and sets GOOGLE_APPLICATION_CREDENTIALS to that file. The file is cleaned up on process exit on a best-effort basis.

Errors

Secret lookups such as EnsureHasValue and GetGenericSecret throw ConfigurationException. Configuration errors are reported directly (for example Not configured: {path}), while unexpected failures are wrapped once with the original error as InnerException. Vault login failures throw VaultAuthenticationException, which derives from ConfigurationException; the underlying cause, such as a Vault response and its status code, is available as InnerException.

Vault client lifetime

Reuse clients rather than creating one per request. Connections are pooled and renewed after five minutes to pick up DNS changes; requests include Elvia.Configuration/{AssemblyInformationalVersion} as their User-Agent. Configured CA validation and hostname checks still apply.

The static HashiVault methods share a process-lifetime client. HashiVault.CreateVaultClient() instead returns an independent, caller-owned client: after all its operations have completed, dispose it via IDisposable:

var client = HashiVault.CreateVaultClient();
using var lifetime = (IDisposable)client;
var secret = await client.GetGenericSecret("shared/kv/info/environment");

Disposing a configuration root built with the default AddHashiVaultSecrets() factory disposes its Vault client. Clients returned by HashiVault.CreateVaultClient() or by an injected IVaultClientFactory are caller-owned; the configuration provider does not dispose them. Providers over the shared static client do not own it. Finish outstanding reads before disposal.

Kubernetes cluster settings

Service account routing metadata supports both legacy and projected JWT claim formats. The library only decodes the payload to select the Vault role/mount; it does not validate the JWT signature, issuer or expiry. Vault authenticates the original, unchanged token.

The library no longer references System.IdentityModel.Tokens.Jwt or Microsoft.IdentityModel.Protocols.OpenIdConnect directly. Applications using those APIs must add their own explicit package references, even if another dependency currently provides them transitively.

When using Atlas cluster configuration, each Vault client reads the named ConfigMap vault in namespace vault once and reuses vault_hostname, vault_cacert (base64) and vault_base_mountpoint, including on re-authentication. The service account needs RBAC get permission on configmaps/vault; list permission is not required. A missing required ConfigMap causes an explanatory ConfigurationException.

This read uses a direct HTTPS GET /api/v1/namespaces/vault/configmaps/vault, without the KubernetesClient package. Atlas detection requires ELVIA_ENVIRONMENT in addition to in-cluster detection: KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT and the mounted token and ca.crt files under /var/run/secrets/kubernetes.io/serviceaccount/. A Kubernetes pod without ELVIA_ENVIRONMENT is not treated as Atlas. The API request uses that token and trusts only that CA, with hostname validation. Outside Atlas the ConfigMap is not read. The Kubernetes API connection cannot be configured explicitly. SERVICE_ACCOUNT_PATH selects the JWT used for Vault login, not the Kubernetes API token. The temporary Kubernetes HTTP client is disposed after reading the map. HTTP errors propagate, and redirects are rejected rather than followed.

Existing overrides retain priority: VAULT_ADDR overrides the cluster hostname, VAULT_CACERT selects a CA file instead of the cluster CA, and MOUNT_PATH together with ROLE overrides convention-based Kubernetes authentication. Without vault_base_mountpoint, the auth mount defaults to kubernetes/{namespace}/{serviceAccount}. Create a new client to pick up changed cluster settings.

Vault secret cache

Successful secret dictionaries are parsed once and cached per client and dictionary path. The default TTL is 5 seconds (previously 2 seconds); rotated secrets become visible on the first lookup after expiry. Set ELVIA_VAULT_CACHE_TTL_SECONDS before creating the client to override this TTL with a non-negative integer number of seconds (digits only, up to 2147483647). An unset variable uses 5 seconds; 0 disables secret caching, including the underlying raw-response cache for dictionary/secret lookups. Negative or invalid values cause a ConfigurationException at client creation.

Concurrent lookups of the same dictionary share one load when caching is enabled. Failures and missing data are not cached, and expired values are not served on errors. Canceling a lookup cancels only that caller's wait, not a shared load; with caching disabled, cancellation is passed through to the Vault request. Returned dictionaries are independent, mutable copies; modifying one does not change cached secrets. Key matching keeps the existing ordered, case-insensitive -/_ and separator-removal matching.

Mount KV-version metadata retains its separate one-hour cache. The provider remains lazy: the first lookup and refresh after expiry can still make synchronous network calls.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (13)

Showing the top 5 NuGet packages that depend on Elvia.Configuration:

Package Downloads
Elvia.Edna.Events

Publish and consume events on Elvia's Kafka platform (EDNA) with schema registry support, OpenTelemetry tracing and metrics, and Meldingsportalen message logging.

Elvia.KvalitetsportalLogger

Library for KvalitetsportalLogger.

Elvia.Mdmx.Apps.Shared

Shared library for MDMx applications.

Elvia.Elvid.Bff.UserClient

Package Description

Elvia.Edna.Dataproduct

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
8.0.0 564 11/16/2026
8.0.0-beta2 257 10/27/2026
8.0.0-beta1 127 10/15/2026
7.0.1-preview.1-54 56 11/15/2026
7.0.1-preview.1-53 60 11/14/2026
7.0.1-preview.1-52 56 11/12/2026
7.0.1-preview.1-51 53 11/11/2026
7.0.1-preview.1-50 66 10/31/2026
7.0.1-preview.1-49 62 10/30/2026
7.0.1-preview.1-48 60 10/30/2026
7.0.1-preview.1-47 68 10/29/2026
7.0.1-preview.1-46 73 10/23/2026
7.0.1-preview.1-45 64 10/20/2026
7.0.1-preview.1-44 76 10/14/2026
7.0.1-preview.1-40 72 9/28/2026
7.0.1-preview.1-39 81 9/22/2026
7.0.1-preview.1-38 96 9/19/2026
7.0.1-preview.1-37 85 9/19/2026
7.0.1-preview.1-36 80 9/18/2026
7.0.1-preview.1-35 85 9/16/2026
Loading failed