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
@@ -66,6 +66,7 @@ public sealed class AadResourceTypeTests
(SyncEntityType.Host, CryptoSpec.AadResourceType.Host),
(SyncEntityType.SshKey, CryptoSpec.AadResourceType.SshKey),
(SyncEntityType.Credential, CryptoSpec.AadResourceType.Credential),
(SyncEntityType.KnownHostKey, CryptoSpec.AadResourceType.KnownHostKey),
];
public static TheoryData<SyncEntityType, CryptoSpec.AadResourceType> Pinned
@@ -161,6 +162,9 @@ public sealed class AadResourceTypeTests
SyncEntityType.Credential => CredentialCipher.Seal(
NewCredential(), vaultKey, entityId, generation, version),
SyncEntityType.KnownHostKey => KnownHostKeyCipher.Seal(
NewKnownHost(), vaultKey, entityId, generation, version),
_ => throw new ArgumentOutOfRangeException(
nameof(wire),
wire,
@@ -256,6 +260,46 @@ public sealed class AadResourceTypeTests
SshKeyCipher.TryOpen(payload, vaultKey, entityId, itemVersion: 3).ShouldBeNull();
}
[Fact]
public void AKnownHostPayload_OpensAsNothingElse()
{
// The pairing table above is the load-bearing check; this is the cross-type refusal a reader expects
// to see spelled out, and it is the one that would notice a second cipher being pointed at
// AadResourceType.KnownHostKey by mistake.
var vaultKey = RandomNumberGenerator.GetBytes(32);
var entityId = Guid.CreateVersion7();
var sealed_ = KnownHostKeyCipher.Seal(
NewKnownHost(), vaultKey, entityId, keyGeneration: 1, itemVersion: 1);
HostCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
SshKeyCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
CredentialCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
KnownHostKeyCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldNotBeNull();
}
[Fact]
public void AKnownHostSealedAtOneVersion_DoesNotOpenAtAnother()
{
var vaultKey = RandomNumberGenerator.GetBytes(32);
var entityId = Guid.CreateVersion7();
var payload = KnownHostKeyCipher.Seal(
NewKnownHost(), vaultKey, entityId, keyGeneration: 1, itemVersion: 2);
KnownHostKeyCipher.TryOpen(payload, vaultKey, entityId, itemVersion: 3).ShouldBeNull();
}
private static KnownHostSecret NewKnownHost() => new()
{
Host = "db.internal",
Port = 22,
Algorithm = "ssh-ed25519",
Fingerprint = "SHA256:5cWZ1Zc2ZmEXAMPLEfingerprintvalue0123456789a",
};
private static CredentialSecret NewCredential() => new()
{
Label = "db-login",
@@ -31,7 +31,12 @@ internal sealed class FakeVaultServer : ISyncApi
{
/// <summary>The item types this fake knows, mirroring the server's own registry.</summary>
private static readonly SyncEntityType[] Supported =
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential];
[
SyncEntityType.Host,
SyncEntityType.SshKey,
SyncEntityType.Credential,
SyncEntityType.KnownHostKey,
];
private readonly Dictionary<(SyncEntityType Type, Guid EntityId), Row> rows = [];
private readonly List<LogEntry> log = [];
@@ -257,45 +262,81 @@ internal sealed class FakeVaultServer : ISyncApi
/// <summary>The per-type rules about which plaintext columns an item may carry.</summary>
/// <remarks>
/// A key's are stricter than a host's rather than merely different, and that asymmetry is the point:
/// the relay concession belongs to hosts alone, so a key arriving with an address is a client bug and
/// is refused with a reason instead of being quietly dropped.
/// One method per type, as the server has one class per type, because the differences are the interesting
/// part. Everything except a host is stricter rather than merely different: the relay concession belongs
/// to hosts alone, so anything else arriving with an address is a client bug and is refused with a reason
/// instead of being quietly dropped.
/// </remarks>
private static bool ValidateFields(
SyncEntityType entityType,
SyncPlaintextFields fields,
out string error)
out string error) => entityType switch
{
SyncEntityType.SshKey => ValidateKeyFields(fields, out error),
SyncEntityType.Credential => ValidateCredentialFields(fields, out error),
SyncEntityType.KnownHostKey => ValidateKnownHostFields(fields, out error),
_ => ValidateHostFields(fields, out error),
};
private static bool ValidateKeyFields(SyncPlaintextFields fields, out string error)
{
error = string.Empty;
if (entityType == SyncEntityType.SshKey)
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
{
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
{
error = "An SSH key has no relay target; relay fields may only be set on a host.";
return false;
}
return true;
error = "An SSH key has no relay target; relay fields may only be set on a host.";
return false;
}
if (entityType == SyncEntityType.Credential)
return true;
}
private static bool ValidateCredentialFields(SyncPlaintextFields fields, out string error)
{
error = string.Empty;
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
{
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
{
error = "A credential has no relay target; relay fields may only be set on a host.";
return false;
}
if (fields.PublicKeyFingerprint is not null)
{
error = "A credential has no public key.";
return false;
}
return true;
error = "A credential has no relay target; relay fields may only be set on a host.";
return false;
}
if (fields.PublicKeyFingerprint is not null)
{
error = "A credential has no public key.";
return false;
}
return true;
}
/// <remarks>
/// The type that does hold an address, and holds it inside the ciphertext. A pin arriving with one in the
/// clear would be the server being handed the list of endpoints a user reaches.
/// </remarks>
private static bool ValidateKnownHostFields(SyncPlaintextFields fields, out string error)
{
error = string.Empty;
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
{
error = "A known host key is not something the server dials; its address stays encrypted.";
return false;
}
if (fields.PublicKeyFingerprint is not null)
{
error = "A known host key's fingerprint stays inside its payload.";
return false;
}
return true;
}
private static bool ValidateHostFields(SyncPlaintextFields fields, out string error)
{
error = string.Empty;
if (!fields.RelayEnabled && (fields.Hostname is not null || fields.Port is not null))
{
error = "An address may only be supplied when relay is enabled.";
@@ -18,7 +18,12 @@ public sealed class ItemKindsTests
public void ThePullFilterNamesEveryTypeThisBuildSynchronises()
{
ItemKinds.SyncedTypes.ShouldBe(
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential]);
[
SyncEntityType.Host,
SyncEntityType.SshKey,
SyncEntityType.Credential,
SyncEntityType.KnownHostKey,
]);
}
[Fact]
@@ -0,0 +1,201 @@
using DodoSSH.Contracts;
using static DodoSSH.Client.Sync.Tests.SyncHarness;
namespace DodoSSH.Client.Sync.Tests;
/// <summary>
/// Known host keys through the two-machine harness.
/// </summary>
/// <remarks>
/// The first test here is the whole reason this item type exists: a host approved on the laptop is approved on
/// the desktop. Everything else is what the credential and key suites check per type — the cipher, what the
/// server is told, that the items cannot be confused with another type's — plus the two properties that are
/// specific to trust: that withdrawing it propagates, and that a clash between two fingerprints is reported
/// with both of them, unlike a clash between two passwords.
/// </remarks>
public sealed class KnownHostSyncTests : IAsyncLifetime
{
private SyncHarness harness = null!;
private static CancellationToken Token => TestContext.Current.CancellationToken;
/// <inheritdoc />
public async ValueTask InitializeAsync() => harness = await CreateAsync();
/// <inheritdoc />
public ValueTask DisposeAsync()
{
harness.Dispose();
return ValueTask.CompletedTask;
}
[Fact]
public async Task AHostApprovedOnOneMachine_IsApprovedOnTheOther()
{
// The point of the item type. Without it a user is asked to check the same fingerprint on every
// device, which is how people learn to approve host keys without reading them.
var entityId = await harness.First.CreateKnownHostAsync(
KnownHost("bastion.internal", port: 2222, fingerprint: "SHA256:approved-on-the-laptop"));
await harness.SettleAsync();
var seen = await harness.Second.FindKnownHostAsync(entityId);
seen.Secret.Host.ShouldBe("bastion.internal");
seen.Secret.Port.ShouldBe(2222);
seen.Secret.Algorithm.ShouldBe("ssh-ed25519");
seen.Secret.Fingerprint.ShouldBe("SHA256:approved-on-the-laptop");
seen.HasUnsyncedChanges.ShouldBeFalse();
}
[Fact]
public async Task TrustWithdrawnOnOneMachine_IsWithdrawnOnTheOther()
{
// The other half, and not a symmetry argument: a changed host key is refused with no way to continue,
// so a withdrawal that did not travel would leave a rebuilt server unreachable from every machine
// except the one that forgot its old key.
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
await harness.SettleAsync();
(await harness.Second.ListKnownHostsAsync()).Items.ShouldHaveSingleItem();
await harness.First.DeleteKnownHostAsync(entityId);
await harness.SettleAsync();
(await harness.Second.ListKnownHostsAsync()).Items.ShouldBeEmpty();
}
[Fact]
public async Task ThePull_AsksForKnownHostKeys()
{
// Derived from the registry rather than listed, so this cannot be forgotten — but a pin that
// reconciles perfectly and is never requested would work on one machine and exist nowhere else,
// which is exactly the failure the first test would then be unable to see.
await harness.First.SyncAsync();
harness.Server.LastPullTypes.ShouldNotBeNull().ShouldContain(SyncEntityType.KnownHostKey);
}
[Fact]
public async Task APinHandsTheServerNothingInPlaintext()
{
// The address especially. It is the one field here that the server is allowed to hold for a
// relay-enabled host, and putting it on this item as well would hand the operator the list of
// endpoints every user actually reaches — assembled out of values that are each harmless.
var entityId = await harness.First.CreateKnownHostAsync(KnownHost("bastion.internal"));
var queued = await harness.First.Outbox
.FindAsync(VaultId, SyncEntityType.KnownHostKey, entityId, Token);
queued.ShouldNotBeNull();
queued.Fields.ShouldBeNull("a pin tells the server nothing but its ciphertext");
await harness.SettleAsync();
var row = harness.Server.Find(entityId, SyncEntityType.KnownHostKey).ShouldNotBeNull();
row.Fields.RelayEnabled.ShouldBeFalse();
row.Fields.Hostname.ShouldBeNull();
row.Fields.Port.ShouldBeNull();
row.Fields.PublicKeyFingerprint.ShouldBeNull();
}
[Fact]
public async Task APinAndAHostSharingAnId_AreTwoItems()
{
// The cache keys on the type as well as the id, and each payload's AAD binds a different resource
// type. Arranged on the server because the repositories mint UUIDv7s and would never collide.
var sharedId = Guid.CreateVersion7();
harness.First.Keyring.TryGet(VaultId, out var vaultKey, out var generation).ShouldBeTrue();
harness.Server.ExternalUpsert(
sharedId,
HostCipher.Seal(Host("prod-db"), vaultKey.Span, sharedId, generation, itemVersion: 1),
new SyncPlaintextFields(),
SyncEntityType.Host);
harness.Server.ExternalUpsert(
sharedId,
KnownHostKeyCipher.Seal(
KnownHost(), vaultKey.Span, sharedId, generation, itemVersion: 1),
null,
SyncEntityType.KnownHostKey);
await harness.Second.SyncAsync();
(await harness.Second.ListAsync()).Items.ShouldHaveSingleItem()
.Secret.Label.ShouldBe("prod-db");
var pins = await harness.Second.ListKnownHostsAsync();
pins.Items.ShouldHaveSingleItem().Secret.Host.ShouldBe("db.internal");
pins.Unreadable.ShouldBe(0);
}
[Fact]
public async Task BothMachinesApprovedADifferentKey_TheDiscardedFingerprintIsReported()
{
// The deliberate contrast with the password merge, which reports that something differed and nothing
// more. A fingerprint is published by the operator so that it can be compared; a notice that withheld
// the value it dropped would leave the user with nothing to check it against.
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
await harness.SettleAsync();
await harness.First.UpdateKnownHostAsync(
entityId, KnownHost(fingerprint: "SHA256:seen-from-the-laptop"));
await harness.Second.UpdateKnownHostAsync(
entityId, KnownHost(fingerprint: "SHA256:seen-from-the-desktop"));
await harness.SettleAsync();
var first = (await harness.First.FindKnownHostAsync(entityId)).Secret;
// Converged, and on the value that reached the server first: every replica has to resolve a clash the
// same way or the two would push against each other for ever.
first.ShouldBe((await harness.Second.FindKnownHostAsync(entityId)).Secret);
first.Fingerprint.ShouldBe("SHA256:seen-from-the-laptop");
var details = await ConflictDetailsAsync();
details.ShouldContain(detail => detail.Contains("SHA256:seen-from-the-desktop", StringComparison.Ordinal));
details.ShouldContain(detail => detail.Contains("Fingerprint", StringComparison.Ordinal));
}
[Fact]
public async Task APinEditedElsewhereAfterBeingDeletedHere_IsCalledAKnownHostKey()
{
// The noun reaches a person. "This host key was edited elsewhere" would send them to look at the
// server they are connecting to, rather than at a decision they made about it.
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
await harness.SettleAsync();
await harness.First.UpdateKnownHostAsync(
entityId, KnownHost(fingerprint: "SHA256:still-the-one-i-approved"));
await harness.Second.DeleteKnownHostAsync(entityId);
await harness.SettleAsync();
(await harness.First.FindKnownHostAsync(entityId)).Secret.Fingerprint
.ShouldBe("SHA256:still-the-one-i-approved");
var details = await ConflictDetailsAsync();
details.ShouldContain(
detail => detail.Contains("This known host key was edited", StringComparison.Ordinal));
}
private async Task<IReadOnlyList<string>> ConflictDetailsAsync()
{
var first = await harness.First.ConflictsAsync();
var second = await harness.Second.ConflictsAsync();
return
[
.. first.Concat(second)
.Select(conflict => System.Text.Encoding.UTF8.GetString(conflict.Detail)),
];
}
}
@@ -39,6 +39,7 @@ internal sealed class SyncDevice : IDisposable
Hosts = new HostRepository(Items, Outbox, keyring);
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
Credentials = new CredentialRepository(Items, Outbox, keyring);
KnownHosts = new KnownHostRepository(Items, Outbox, keyring);
Engine = new SyncEngine(
server, Items, Outbox, SyncState, Conflicts, keyring, TimeProvider.System, options);
@@ -62,6 +63,8 @@ internal sealed class SyncDevice : IDisposable
internal CredentialRepository Credentials { get; }
internal KnownHostRepository KnownHosts { get; }
internal SyncEngine Engine { get; }
internal static async Task<SyncDevice> CreateAsync(
@@ -165,6 +168,29 @@ internal sealed class SyncDevice : IDisposable
Credentials.UpdateAsync(
SyncHarness.VaultId, entityId, credential, TestContext.Current.CancellationToken);
// ---- And again on known host keys ----
internal Task<ItemListing<KnownHostSecret>> ListKnownHostsAsync() =>
KnownHosts.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal async Task<VaultItem<KnownHostSecret>> FindKnownHostAsync(Guid entityId)
{
var listing = await ListKnownHostsAsync();
return listing.Items.SingleOrDefault(pin => pin.EntityId == entityId)
?? throw new InvalidOperationException($"{Name} cannot see known host key {entityId}.");
}
internal Task<Guid> CreateKnownHostAsync(KnownHostSecret knownHost) =>
KnownHosts.CreateAsync(SyncHarness.VaultId, knownHost, TestContext.Current.CancellationToken);
internal Task UpdateKnownHostAsync(Guid entityId, KnownHostSecret knownHost) =>
KnownHosts.UpdateAsync(
SyncHarness.VaultId, entityId, knownHost, TestContext.Current.CancellationToken);
internal Task DeleteKnownHostAsync(Guid entityId) =>
KnownHosts.DeleteAsync(SyncHarness.VaultId, entityId, TestContext.Current.CancellationToken);
internal Task<IReadOnlyList<StoredConflict>> ConflictsAsync() =>
Conflicts.ListAsync(SyncHarness.VaultId, false, TestContext.Current.CancellationToken);
@@ -315,6 +341,25 @@ internal sealed class SyncHarness : IDisposable
string? notes = null) =>
new() { Label = label, Password = password, Username = username, Notes = notes };
/// <summary>A pinned host key, varying only what a test is about.</summary>
/// <remarks>
/// The fingerprint is a plausible shape rather than a real digest. Nothing in the sync path hashes
/// anything or checks the encoding — <c>SshHostKeyFingerprint</c> does that, one layer down and in its own
/// suite — so a value that reads as one is worth more here than a genuine one.
/// </remarks>
internal static KnownHostSecret KnownHost(
string host = "db.internal",
int port = 22,
string algorithm = "ssh-ed25519",
string fingerprint = "SHA256:AAAAtestfingerprint0123456789abcdefghijklmno") =>
new()
{
Host = host,
Port = port,
Algorithm = algorithm,
Fingerprint = fingerprint,
};
internal static SshKeySecret Key(
string label,
string material = "deploy-key-material",