ktsu.CredentialCache 1.4.1

Prefix Reserved
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package ktsu.CredentialCache --version 1.4.1
                    
NuGet\Install-Package ktsu.CredentialCache -Version 1.4.1
                    
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="ktsu.CredentialCache" Version="1.4.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ktsu.CredentialCache" Version="1.4.1" />
                    
Directory.Packages.props
<PackageReference Include="ktsu.CredentialCache" />
                    
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 ktsu.CredentialCache --version 1.4.1
                    
#r "nuget: ktsu.CredentialCache, 1.4.1"
                    
#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 ktsu.CredentialCache@1.4.1
                    
#: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=ktsu.CredentialCache&version=1.4.1
                    
Install as a Cake Addin
#tool nuget:?package=ktsu.CredentialCache&version=1.4.1
                    
Install as a Cake Tool

ktsu.CredentialCache

A cross-platform credential cache for .NET that stores secrets in the host's native keyring.

License NuGet Version NuGet Version NuGet Downloads GitHub commit activity GitHub contributors GitHub Actions Workflow Status

Overview

CredentialCache keeps credentials in memory for fast lookup during the lifetime of a process and persists each one through an ICredentialStore whose default implementation delegates to the platform-native secret manager:

Platform Backing store Native API
Windows Credential Manager advapi32 — CredReadW / CredWriteW / CredDeleteW / CredEnumerateW
macOS Keychain Services Security.framework — SecKeychainAddGenericPassword and friends
Linux freedesktop.org Secret Service libsecret-1.so.0 — secret_password_store_sync / lookup_sync / clear_sync
Other / opt-out None InMemoryCredentialStore

Each persona's credential is stored as its own entry in the OS keyring scoped by a service name — the library never writes a plaintext blob to disk.

Installation

dotnet add package ktsu.CredentialCache

Requires .NET 9 or .NET 10.

Linux runtime prerequisites

The Linux store requires libsecret and a running Secret Service implementation (gnome-keyring, KWallet's secret-service bridge, KeePassXC, …). On Debian/Ubuntu:

sudo apt-get install libsecret-1-0 gnome-keyring

On headless or CI hosts you'll typically need a session bus and an unlocked keyring — see the cross-platform.yml workflow in this repo for the dbus-run-session + gnome-keyring-daemon incantation. If a Secret Service isn't available in your deployment, fall back to InMemoryCredentialStore (or roll your own ICredentialStore).

Quick start

using ktsu.CredentialCache;
using ktsu.CredentialCache.Storage;
using ktsu.Semantics.Strings;

// Pick the platform-native store explicitly...
ICredentialStore store = CredentialStoreFactory.CreateDefault("MyApp");
using CredentialCache cache = new(store);

// ...or just use the singleton, which calls CreateDefault() on first access.
CredentialCache singleton = CredentialCache.Instance;

PersonaGUID persona = CredentialCache.CreatePersonaGUID();

cache.AddOrReplace(persona, new CredentialWithUsernamePassword
{
    Username = SemanticString<CredentialUsername>.Create("alice"),
    Password = SemanticString<CredentialPassword>.Create("hunter2"),
});

if (cache.TryGet(persona, out Credential? stored)
    && stored is CredentialWithUsernamePassword creds)
{
    Console.WriteLine($"Hello, {creds.Username}");
}

cache.Remove(persona);

Pick your own service name

CredentialStoreFactory.CreateDefault(serviceName) scopes entries by a logical service name (defaults to "ktsu.CredentialCache"). If two applications share a host, pass per-app names so their keyring entries don't collide.

Credential types

The library ships with three concrete Credential subclasses:

Type Use it for
CredentialWithNothing Sentinel for "no credential required"
CredentialWithToken Opaque bearer or API token
CredentialWithUsernamePassword Classic username + password pair

Adding your own credential type

Credential is a polymorphic abstract class round-tripped through System.Text.Json. A subclass defined outside the library has to be registered once, at start-up, before a credential of that type is saved or loaded:

// 1. Add the subclass.
public sealed class CredentialWithCertificate : Credential
{
    public string Thumbprint { get; init; } = "";
}

// 2. Register it. The discriminator is written into every stored credential of this type and
//    identifies it when one is read back, so keep it stable once credentials have been saved.
CredentialSerialization.RegisterDerivedType<CredentialWithCertificate>("MyApp.CredentialWithCertificate");

// 3. Optional: register a factory so TryCreate<T> works.
public sealed class CertificateFactory : ICredentialFactory<CredentialWithCertificate>
{
    public CredentialWithCertificate Create() => new();
}
cache.RegisterCredentialFactory(new CertificateFactory());

If a subclass uses SemanticString<T> properties, they round-trip through ktsu.RoundTripStringJsonConverter automatically.

AddOrReplace refuses a subclass that was never registered with a CredentialStoreException naming the type, and leaves the cache and the store unchanged. It does this for every store, InMemoryCredentialStore included, so a test that uses the in-memory store fails the same way production would. Calling Save on a store directly refuses it the same way, with the same exception and message, from the in-memory store and each platform store. So do CredentialSerialization.Serialize and SerializeToString, which means a custom store built on them refuses it too.

Customising the backing store

ICredentialStore is a small CRUD interface (TryLoad / Save / Remove). Bring your own implementation when you need a different backend (HashiCorp Vault, an encrypted file, a test double):

public sealed class MyCustomStore : ICredentialStore { /* ... */ }

ICredentialStore store = new MyCustomStore();
CredentialCache.ConfigureStore(store); // must be called before first Instance access

For unit tests, use the in-memory store and skip the singleton entirely:

using CredentialCache cache = new(new InMemoryCredentialStore());

Enumerating stored personas

ICredentialStore deliberately has no EnumerateKeys method, because macOS Keychain and libsecret require substantially more native marshalling for enumeration than the simple key-value ops. The optional ISearchableCredentialStore interface adds it, and only the Windows and in-memory stores implement it:

if (cache.Store is ISearchableCredentialStore searchable)
{
    foreach (PersonaGUID key in searchable.EnumerateKeys())
    {
        // ...
    }
}
else
{
    // Track persona GUIDs yourself on macOS / Linux.
}

Platform notes

  • Windows Credential Manager caps the credential blob at 2560 bytes (5 * 512). The cap counts the serialized credential, which is UTF-8 JSON, so a non-ASCII character takes two to four bytes of it. Credentials larger than that throw CredentialStoreException — split or compress before storing.
  • macOS uses the user's default login keychain. The first access from an application prompts the user for permission, as with any keychain client.
  • Linux requires libsecret-1 plus an active Secret Service. Headless CI agents typically have neither — use InMemoryCredentialStore there, or set up dbus-run-session + gnome-keyring-daemon as the cross-platform.yml workflow does.
  • All native calls happen on the thread the API is invoked from. The library's in-memory cache is thread-safe (ConcurrentDictionary); the native APIs themselves are documented as thread-safe by their respective platform owners, but blocking calls (especially libsecret) are not cheap — treat Save / Remove as I/O, not as cheap accessors.
  • AddOrReplace, Remove, and the store-loading half of TryGet each update the cache and the store, so they hold a lock on the persona for the duration rather than relying on the dictionary alone. Concurrent calls for the same persona therefore run one at a time and the two always end up agreeing; concurrent calls for different personas are unaffected. Because that lock is held across a store call, a Remove and an AddOrReplace racing on one persona serialize at the speed of the native store — another reason to treat them as I/O.
  • All three native stores handle plaintext on the same terms: every copy the library owns is a byte array or an unmanaged buffer that is overwritten with zeros before it is released, and no secret is ever routed through a managed string, which is immutable and so cannot be scrubbed at all. A credential you hold yourself is a different matter — anything you read out of TryGet is an ordinary object on the managed heap and its lifetime is yours.

API summary

CredentialCache

Member Description
CredentialCache(ICredentialStore store) Construct an instance with an explicit store.
static Instance Process-wide singleton (lazy, thread-safe).
Store The backing store passed to the constructor.
static ConfigureStore(ICredentialStore) Override the singleton's store. Must precede first Instance access.
static ResetSingletonForTesting() Dispose the singleton and clear configuration. Tests only.
static CreatePersonaGUID() Allocates a new PersonaGUID.
TryGet(persona, out cred) Memory-cache lookup with fall-through to the backing store.
AddOrReplace(persona, cred) Persists eagerly through the store.
Remove(persona) Deletes from both the in-memory cache and the store.
RegisterCredentialFactory<T>(factory) Optional factory hook used by TryCreate<T>.
TryCreate<T>(out cred) Constructs a credential via a registered factory.
Dispose() Releases in-memory state. The OS store is left untouched.

ICredentialStore

Member Description
Name Diagnostic identifier (e.g. "Windows Credential Manager", "macOS Keychain", "Linux libsecret (Secret Service)", "InMemory").
TryLoad(persona, out cred) Load a single credential.
Save(persona, cred) Persist or overwrite a single credential.
Remove(persona) Delete a single credential.

ISearchableCredentialStore : ICredentialStore

Member Description
EnumerateKeys() Enumerate every persona key currently persisted (Windows, in-memory).

Don't dispose the singleton

CredentialCache.Instance returns a process-wide singleton. Calling Dispose() on it (e.g. via using var c = CredentialCache.Instance;) puts the singleton in a disposed state and the next consumer in the process gets ObjectDisposedException. If you need disposal semantics, construct your own instance with new CredentialCache(store).

License

MIT — see LICENSE.md.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  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 (3)

Showing the top 3 NuGet packages that depend on ktsu.CredentialCache:

Package Downloads
ktsu.ImGuiCredentialPopups

A .NET library providing ready-made Dear ImGui modal dialogs for collecting credentials. Ships username/password and token popups built on a shared CredentialPopup base, with masked input, automatic keyboard focus, and confirmation callbacks that hand back a ktsu.CredentialCache credential ready to store or use.

ktsu.GitIntegration

A .NET library that wraps the git command-line binary behind a fluent, strongly-typed interface for reading repository state — status, log, diff, branches, remotes, and revision resolution — and for mutating it — init, clone, staging, committing, branch creation and deletion, checkout, remote management, and remote sync via fetch, pull, and push — executed via ktsu.RunCommand with reproducible, copy-pasteable failures, locale-safe parsing, and a machine-readable per-reference account of every fetch and push, and that also unifies access to hosted Git providers behind a pluggable GitProvider abstraction with a GitHub implementation built on Octokit and credential resolution through ktsu.CredentialCache. Includes a set of semantic string types that replace stringly-typed Git identifiers — branch names, commit SHAs, ref names, remote names, author names and emails, repository names, and web URIs — with validated, compile-time-safe wrappers.

ktsu.KtsuTools.Core

KtsuTools is a unified developer tools suite that consolidates multiple ktsu-dev utilities into a single CLI application with consistent UX powered by Spectre.Console.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.2-pre.1 58 11/16/2026
1.4.1 166 11/14/2026
1.4.0 83 11/13/2026
1.3.63-pre.3 88 10/9/2026
1.3.63-pre.2 79 10/8/2026
1.3.63-pre.1 80 10/7/2026
1.3.62 1,837 10/7/2026
1.3.61 130 10/6/2026
1.3.60 264 10/6/2026
1.3.60-pre.3 75 10/5/2026
1.3.60-pre.2 77 10/2/2026
1.3.60-pre.1 72 9/30/2026
1.3.59 3,615 9/29/2026
1.3.58 236 9/29/2026
1.3.58-pre.1 73 9/28/2026
1.3.57 280 9/27/2026
1.3.56 144 9/26/2026
1.3.55 135 9/26/2026
1.3.54 128 9/25/2026
1.3.53 1,054 9/24/2026
Loading failed

## v1.4.1 (patch)

Changes since v1.4.0:

- Refuse a null non-nullable property in the in-memory store too [patch] (#212) (matt-edmondson)