Keep host key trust in the vault, and make it withdrawable
ci / build and test (ubuntu) (push) Canceled after 0s
ci / build (windows) (push) Canceled after 0s

A fingerprint approved once is now approved on every machine and survives a
restart, because host key trust is a vault item type rather than a dictionary
that dies with the process. InMemoryKnownHostStore was what shipped, so the user
was asked to verify a fingerprint on every single connection — which is the gap
most likely to train somebody to click through the one warning that actually
matters. A warning that appears when nothing is wrong teaches that nothing is
ever wrong.

The fourth item type, and like the third it cost no sync logic: a row, an EF
configuration, a migration, a server kind; a secret, a codec, a merge, a cipher,
a repository facade and a session property. One row in the client registry. The
reconciler, the mirror, the repository, the outbox and the pull filter were not
touched. SyncEntityType.KnownHostKey and AadResourceType.KnownHostKey were
already reserved, so neither the contract nor docs/crypto.md changed.

One item per (host, port, algorithm), because a server legitimately offers
several host keys and which one gets negotiated is not ours to predict. Pinning
per endpoint would make an algorithm change indistinguishable from an attack.

The label is derived rather than stored, which is the one place this type
departs from the other three. A user never names a pin — there is nothing to
name it after but the three fields it already has — and a stored label is a
second copy of data that can disagree with the first after a merge. Relabel
returns the secret unchanged, and says why.

The store answers the handshake without touching the disk. SshNetConnectionFactory
calls FindAsync from inside SSH.NET's synchronous HostKeyReceived event, over
.GetAwaiter().GetResult(), which cannot be avoided; doing SQLite I/O plus an AEAD
open per lookup there would put the handshake behind the cache. So decryption
happens in OpenAsync and RefreshAsync — on unlock and after each sync pass,
exactly where the host and key lists already reload — and FindAsync is a
dictionary read under a lock with no await inside it.

That snapshot is where the one real bug in this change lived. Install originally
merged the live pins over the freshly loaded snapshot, to protect a TrustAsync
that had landed while the read was in flight. It would also have resurrected
every pin the user had just forgotten, and stopped a withdrawal made on another
machine from ever taking effect — the store would have healed the deletion back
into existence on every refresh. Replacing wholesale and discarding the read
instead is correct because writes are the rare case: every write bumps a
generation counter, and a refresh whose stamp is stale throws itself away rather
than winning. Nothing found this but reading the method again; it is the kind of
mistake that passes every test written before it, because the test that catches
it is the one the bug tells you to write.

Forgetting is new, and persistence is what made it mandatory rather than
convenient. A mismatch is a hard refusal with no way to continue — deliberately,
and that stays — so pinning a key permanently is also a way to make a
legitimately rebuilt server permanently unreachable. Before this change the pin
died at exit and the problem solved itself; now it does not.

ForgetAsync drops every algorithm for an endpoint, and it is reachable from the
host editor rather than from the warning. Putting it on the mismatch banner would
have made it two clicks from "this may be an attack" to "connect anyway", which
is the affordance the hard refusal exists to deny. The banner already promised
the key could be removed in the host's settings; that promise is now true and
points at the button.

Trust recorded on another machine becomes visible at the next sync pass, not
immediately, and that is a decision rather than an oversight. The failure it
produces is a first-contact prompt for a host a colleague approved a minute ago:
answerable, and self-correcting on the next pass. The opposite trade — polling
the vault on the handshake thread to close a one-minute window — buys nothing
and costs the property above. The dangerous direction is not reachable at all: a
pin recorded here enters the snapshot as part of recording it, so a refresh can
never discard a local trust decision.

The server learns nothing, and this is the item type where the temptation was
real. A plaintext host column would let a known-hosts screen sort and page
without decrypting anything, and it would hand the operator the map of every
user's estate — assembled, as these things are, out of facts that are each
individually harmless. A host row concedes an address only when relay is
switched on and the database refuses to store one otherwise (ADR 0004); there is
no equivalent excuse here. The table has no column to put one in, and the EF
configuration says so where somebody adding it would be standing.

Two things about the migration in this commit are worth knowing, because both
came out of getting it wrong.

It was hand-written first, including its .Designer.cs, and that version is not
what is here. Verifying it turned up something that had been quietly assumed:
Migration_AppliedCleanly_WithNoPendingModelChanges does not check the model
snapshot. It asserts that migrations applied and that none are pending, which a
wrong snapshot satisfies perfectly — the snapshot only matters as the diff base
for the *next* migrations add, so an incorrect one passes the whole suite and
corrupts the following migration instead. The real check is to generate a
throwaway migration and confirm its Up and Down come out empty. They did, and
the generated designer was byte-identical to the transcribed one across all 1255
lines, so the hand-written work was in fact correct.

Then dotnet ef migrations remove --no-build deleted the wrong migration. With
--no-build the tool reads the previously compiled assembly rather than the files
on disk, and the probe had just changed which migration was last, so it removed
AddKnownHostKeyItem and reverted the snapshot. That turned out to leave exactly
the right diff base, so the migration here is EF's own output rather than a
transcription — a better outcome than the one that was interrupted, arrived at
by accident. Never pass --no-build to migrations remove.

Mutation tested, all three sabotages detected: dropping the algorithm from
KnownHostIdentity.For, merging instead of replacing in Install, and pointing
KnownHostKeyCipher at PortForward — which is what a cast from the wire enum's 10
would silently produce. Each is caught both by an assertion about the mechanism
and by a behavioural test that never mentions it; the resource-type sabotage is
caught by the table from d10a38d and nothing else, which is what that table is
for.

The end-to-end slice now approves the real sshd's host key through the vault,
pushes it, and reads it back on the second simulated machine — including a check
that the server learned no address, and that the second machine answers null for
an algorithm never offered.

845 tests green. Zero warnings, dotnet format clean.

Three things are deliberately not fixed. A tombstone queued over a create that
was never pushed is refused by the server as Invalid and parked; that is
pre-existing for all four item types, and the fix belongs in
VaultItemRepository.DeleteAsync rather than here. Deleting a host, or changing
its address, orphans its pins — both are correct as trust decisions, since a pin
describes an endpoint and not a bookmark, but nothing surfaces the leftovers.
And there is no interface listing pins at all: trust is created at the connect
prompt and withdrawn in the host editor. A known-hosts list is where the orphans
would become visible, and it wants the vault column rework first, for the same
reason the credential editor does.
This commit is contained in:
2026-07-30 11:00:39 +02:00
parent d10a38d8e6
commit 211eba0666
38 changed files with 4363 additions and 95 deletions
@@ -0,0 +1,351 @@
using DodoSSH.Client.Domain;
using DodoSSH.Client.Ssh;
using DodoSSH.Client.Storage;
using DodoSSH.Contracts;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Session.Tests;
/// <summary>
/// Host key trust that outlives the process, and the snapshot the SSH handshake reads it from.
/// </summary>
/// <remarks>
/// <para>
/// The first test is the whole point of the feature: approve a fingerprint, lock the vault, unlock it again,
/// and the host is still trusted. It runs with no server at all — the pin is in the outbox and the local
/// cache, which is exactly the situation a user is in on a laptop that has not been online since.
/// </para>
/// <para>
/// The rest are the properties that would each be a security bug rather than an inconvenience: that a pin
/// answers for the one algorithm it was recorded for, that a locked vault answers "not pinned" rather than
/// something optimistic, and that withdrawing trust reaches every pin for the endpoint.
/// </para>
/// </remarks>
public sealed class VaultKnownHostStoreTests : IAsyncLifetime
{
private const string Passphrase = "correct horse battery staple";
private const string ServerUrl = "https://dodossh.example";
/// <remarks>
/// Far below the shipped profile, as in <see cref="SessionLifecycleTests"/>: nothing here attacks a wrap,
/// and every test in this suite pays for at least one unlock.
/// </remarks>
private static readonly Argon2Profile CheapProfile =
Argon2Profile.FromStoredParameters(memoryKibibytes: 8 * 1024, passes: 1, parallelism: 1);
private readonly FakeAccountServer server = new();
private readonly StubKeyBinding keyBinding = new();
private ClientCacheFactory caches = null!;
private static CancellationToken Token => TestContext.Current.CancellationToken;
/// <inheritdoc />
public async ValueTask InitializeAsync()
{
caches = ClientCacheFactory.ForMemory($"known-hosts-{Guid.CreateVersion7():N}");
await caches.MigrateAsync(TestContext.Current.CancellationToken);
await Provisioner().EnrollAsync(ServerUrl, Passphrase, "laptop", "Personal", Token);
}
/// <inheritdoc />
public ValueTask DisposeAsync()
{
caches.Dispose();
return ValueTask.CompletedTask;
}
[Fact]
public async Task AHostTrustedOnceIsStillTrustedAfterALockAndUnlock()
{
// The gap this closes. With trust in memory the user is asked to check the same fingerprint on every
// launch, which is how people learn to approve host keys without reading them.
var store = new VaultKnownHostStore();
await using (var first = await UnlockAsync())
{
await store.OpenAsync(first, Token);
await store.TrustAsync(Presented(), Token);
}
store.Close();
await using var second = await UnlockAsync();
await store.OpenAsync(second, Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token))
.ShouldBe("SHA256:approved");
}
[Fact]
public async Task AnUnvisitedHost_HasNoPin()
{
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
}
[Fact]
public async Task APinAnswersForOneAlgorithmOnly()
{
// A server legitimately offers several host keys, and which one is negotiated can change between
// connections. A pin that answered for all of them would either accept a key nobody approved or
// report a mismatch for an ordinary server.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(algorithm: "ssh-ed25519"), Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
(await store.FindAsync("db.internal", 2222, "ssh-ed25519", Token)).ShouldBeNull();
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
}
[Fact]
public async Task AHostNameIsMatchedWithoutRegardToCase()
{
// DNS is case-insensitive, so DB.internal and db.internal are one machine. Treating them as two would
// ask the user to approve the same server twice, and leave two pins where a withdrawal has to find
// both.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(host: "DB.internal"), Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
// And the value stored is the one that was dialled, not a lower-cased rewrite of it.
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
listing.Items.ShouldHaveSingleItem().Secret.Host.ShouldBe("DB.internal");
}
[Fact]
public async Task ReApprovingTheSameKey_QueuesNothingFurther()
{
// Re-trusting an identical fingerprint used to be a dictionary write that cost nothing. It is now an
// outbox operation, and queueing one would push a modification to every other machine for a decision
// that had not changed.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(), Token);
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
var entityId = listing.Items.ShouldHaveSingleItem().EntityId;
var before = await session.Outbox
.FindAsync(session.ActiveVaultId, SyncEntityType.KnownHostKey, entityId, Token);
var operationId = before.ShouldNotBeNull().OperationId;
await store.TrustAsync(Presented(), Token);
// Asserted on the operation rather than on a count of pending changes, and the difference is the
// whole test: queueing an identical write coalesces onto the same outbox row, so a count stays at one
// either way. What would move is the operation id, which is re-minted whenever the payload is
// rewritten — so this is what tells a redundant write from no write at all.
var after = await session.Outbox
.FindAsync(session.ActiveVaultId, SyncEntityType.KnownHostKey, entityId, Token);
after.ShouldNotBeNull().OperationId.ShouldBe(operationId);
(await session.KnownHosts.ListAsync(session.ActiveVaultId, Token)).Items.ShouldHaveSingleItem();
}
[Fact]
public async Task ApprovingANewKeyForAKnownHost_ReplacesThePinRatherThanAddingOne()
{
// What happens after a server is rebuilt and its old pin has been forgotten. Two items for one
// endpoint would leave the endpoint's trust depending on which of them a lookup happened to see.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(), Token);
await store.TrustAsync(Presented(fingerprint: "SHA256:rebuilt"), Token);
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
listing.Items.ShouldHaveSingleItem().Secret.Fingerprint.ShouldBe("SHA256:rebuilt");
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:rebuilt");
}
[Fact]
public async Task ForgettingAHost_TakesEveryAlgorithmWithIt()
{
// The user's decision is about the machine, not about one of the keys it offers. Leaving one behind
// would mean a rebuilt server that still refuses to connect for a reason they believe they have
// already dealt with.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(algorithm: "ssh-ed25519"), Token);
await store.TrustAsync(Presented(algorithm: "rsa-sha2-512"), Token);
await store.TrustAsync(Presented(host: "other.internal"), Token);
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(2);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
// And nothing else was touched.
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
}
[Fact]
public async Task ForgettingAHostThatWasNeverApproved_SaysSoRatherThanFailing()
{
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(0);
}
[Fact]
public async Task AForgottenPinStaysForgottenAcrossALockAndUnlock()
{
// The refresh that follows a withdrawal replaces the snapshot rather than merging into it. Merging
// would have made a forgotten pin reappear, which is the failure that matters here: the user would be
// told the host key had changed after explicitly saying it had.
var store = new VaultKnownHostStore();
await using (var first = await UnlockAsync())
{
await store.OpenAsync(first, Token);
await store.TrustAsync(Presented(), Token);
await store.ForgetAsync("db.internal", 22, Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
}
store.Close();
await using var second = await UnlockAsync();
await store.OpenAsync(second, Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
}
[Fact]
public async Task ALockedVaultAnswersNotPinnedRatherThanSomethingOptimistic()
{
// Reachable when a vault is locked while a handshake is in flight. Refusing the connection is the safe
// direction; the alternative would be answering a host key question out of a vault that is closed.
var store = new VaultKnownHostStore();
await using var session = await UnlockAsync();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(), Token);
store.IsOpen.ShouldBeTrue();
store.Close();
store.IsOpen.ShouldBeFalse();
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
}
[Fact]
public async Task ALockedVaultRefusesToRecordOrWithdrawTrust()
{
// Loudly rather than silently. A pin accepted into nothing would leave the user believing they had
// approved a host, and a withdrawal accepted into nothing would leave one they believe is gone.
var store = new VaultKnownHostStore();
await Should.ThrowAsync<InvalidOperationException>(
async () => await store.TrustAsync(Presented(), Token));
await Should.ThrowAsync<InvalidOperationException>(
async () => await store.ForgetAsync("db.internal", 22, Token));
// And a refresh with nothing behind it is a no-op rather than a throw: a synchronisation pass may
// finish after the vault was locked, and that is ordinary rather than exceptional.
await store.RefreshAsync(Token);
}
[Fact]
public async Task ARefreshPicksUpAPinRecordedElsewhere()
{
// Stands in for a pin arriving from another machine: something reached the vault that this store's
// snapshot predates. Written through the repository directly, which is what a pull followed by a
// listing amounts to.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await session.KnownHosts.CreateAsync(
session.ActiveVaultId,
new KnownHostSecret
{
Host = "bastion.internal",
Port = 22,
Algorithm = "ssh-ed25519",
Fingerprint = "SHA256:approved-on-the-desktop",
},
Token);
(await store.FindAsync("bastion.internal", 22, "ssh-ed25519", Token))
.ShouldBeNull("the snapshot is only re-read when it is told to be");
await store.RefreshAsync(Token);
(await store.FindAsync("bastion.internal", 22, "ssh-ed25519", Token))
.ShouldBe("SHA256:approved-on-the-desktop");
}
[Fact]
public async Task ARefreshKeepsWhatWasApprovedHere()
{
// The mistake that would matter. A pass that re-read the vault must not drop a pin recorded on this
// machine, or the user would be asked again about a host they had just approved.
await using var session = await UnlockAsync();
var store = new VaultKnownHostStore();
await store.OpenAsync(session, Token);
await store.TrustAsync(Presented(), Token);
await store.RefreshAsync(Token);
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
}
// ---- Helpers ----
private static HostKeyPresentation Presented(
string host = "db.internal",
int port = 22,
string algorithm = "ssh-ed25519",
string fingerprint = "SHA256:approved") =>
new(host, port, algorithm, fingerprint);
private SessionOpener Opener() => new(caches, TimeProvider.System);
private AccountProvisioner Provisioner() =>
new(server, keyBinding, caches, TimeProvider.System, CheapProfile);
private async Task<VaultSession> UnlockAsync()
{
var outcome = await Opener().UnlockAsync(Passphrase, Token);
outcome.IsUnlocked.ShouldBeTrue(outcome.Message);
return outcome.Session!;
}
}