Bind an SSH key to a host instead of picking one per connection

A host now names the key it authenticates with, or none, as a field in its
encrypted payload — so the choice follows the host to every machine rather than
being made again each time somebody connects. The per-connection "Use key"
switch it replaces was a stopgap for not having this, and keeping both would
have left two mechanisms answering one question.

This is the first payload schema version bump, and it does not work the obvious
way. A host is written at the *lowest* schema version that can represent it: one
that binds a key is written at 2, one that does not is still written at 1, byte
for byte as it was before the field existed. The version is what makes an older
client refuse to edit an item, so stamping 2 unconditionally would mean
upgrading a single machine and renaming a single host made that host uneditable
on every machine that had not upgraded yet. Confining the cost to the hosts that
actually use the field is the difference between a team noticing a bump and a
team being blocked by one. HostSecretCodec states the rule so the next field
added follows it, and a test pins the version-1 bytes against a literal rather
than against the codec, because the claim is about history: every host already in
every vault has to re-encode to what it encoded before, or the first sync after
an upgrade would push the whole vault as changed.

A binding is an item id, not a copy of the key — a second copy of a private key
is one that goes stale — which means the reference can dangle when the key is
deleted on another machine. Both places that meets are handled the same way, by
refusing rather than falling back:

- Connecting to a host whose key is gone is refused outright. A host somebody
  deliberately set up for key-only access must not quietly start offering a
  password.
- Opening such a host in the editor keeps the binding, selected, labelled as
  missing. The quieter version of the same failure is someone editing the port
  and saving, silently converting the host to password authentication with
  nothing ever having said so.

Two things this found by being falsified:

- The merge was untested for the new field, and "just take the server's value"
  passed the entire suite — a local binding change would have been discarded with
  no conflict recorded. HostSecretMergeTests already had a test written for
  exactly this class of omission; it simply had not been extended.

- Adding a nullable field exposed a defect in HostSecretMerge.Field: it
  short-circuited when the discarded value was null, so the formatter never ran
  for the one case where null is a value rather than an absence, and a field
  whose absence has a name could not report it. Now the formatter always runs,
  and "no key" appears in the conflict log where an empty string used to.

Also fixes eight nullable warnings in SyncEndpointTests left by the server-side
SSH key commit, which had omitted the null-forgiving operator the rest of that
file uses. They were invisible until an unrelated change forced the project to
recompile.

The end-to-end slice now binds its host to its key, so a schema-version-2
payload goes through the real API, the real PostgreSQL and back out on a second
machine.

745 tests green. Zero warnings, dotnet format clean.
This commit is contained in:
2026-07-29 20:42:51 +02:00
parent e3fd3e1728
commit 70b3290a77
12 changed files with 523 additions and 105 deletions
@@ -7,6 +7,9 @@ internal static class HostFactory
internal static Guid Relay { get; } = Guid.Parse("0192f0c8-2222-7c3d-8e4f-5a6b7c8d9e02");
/// <summary>A vault SSH key id, for the hosts that bind one.</summary>
internal static Guid DeployKey { get; } = Guid.Parse("0192f0c8-3333-7c3d-8e4f-5a6b7c8d9e03");
internal static HostSecret Host(
string label = "prod-db",
string hostname = "db.internal",
@@ -15,7 +18,8 @@ internal static class HostFactory
string? notes = null,
Guid[]? jumps = null,
(string Name, string Value)[]? options = null,
bool relayEnabled = false) =>
bool relayEnabled = false,
Guid? sshKeyId = null) =>
new()
{
Label = label,
@@ -28,5 +32,6 @@ internal static class HostFactory
? HostOptions.Empty
: HostOptions.Create(options.Select(o => new HostOption(o.Name, o.Value))),
RelayEnabled = relayEnabled,
SshKeyId = sshKeyId,
};
}
@@ -17,6 +17,8 @@ public sealed class HostSecretCodecTests
[Fact]
public void AFullHost_RoundTrips()
{
// Every field, which is what makes the version assertion below meaningful: a host carrying the
// newest field is the only kind written at the newest version.
var host = Host(
label: "prod-db",
hostname: "db.internal",
@@ -24,7 +26,9 @@ public sealed class HostSecretCodecTests
username: "deploy",
notes: "primary replica",
jumps: [Bastion, Relay],
options: [("ServerAliveInterval", "30"), ("Compression", "yes")]);
options: [("ServerAliveInterval", "30"), ("Compression", "yes")],
relayEnabled: true,
sshKeyId: DeployKey);
HostSecretCodec.TryDecode(HostSecretCodec.Encode(host), out var document).ShouldBeTrue();
@@ -34,6 +38,64 @@ public sealed class HostSecretCodecTests
document.IsReadOnly.ShouldBeFalse();
}
// ---- The schema version is content-dependent ----
[Fact]
public void AHostWithNoKey_IsStillWrittenAtVersionOne()
{
// The compatibility rule, and the reason it is worth having. The version is what makes an older
// client refuse to edit an item, so stamping the newest one on every write would mean upgrading one
// machine and renaming one host made that host uneditable everywhere else. A host that uses nothing
// new stays readable and writable by the older build.
HostSecretCodec.TryDecode(HostSecretCodec.Encode(Host()), out var document).ShouldBeTrue();
document.ShouldNotBeNull();
document.SchemaVersion.ShouldBe(HostSecretCodec.BaseSchemaVersion);
}
[Fact]
public void AHostThatBindsAKey_IsWrittenAtTheVersionThatIntroducedIt()
{
HostSecretCodec
.TryDecode(HostSecretCodec.Encode(Host(sshKeyId: DeployKey)), out var document)
.ShouldBeTrue();
document.ShouldNotBeNull();
document.SchemaVersion.ShouldBe(HostSecretCodec.SshKeyIdSchemaVersion);
document.Host.SshKeyId.ShouldBe(DeployKey);
}
[Fact]
public void AddingTheKeyField_DidNotChangeTheBytesOfAHostWithoutOne()
{
// Pinned against a literal rather than against the codec, because the claim is about history: every
// host already in every vault must re-encode to what it encoded before SshKeyId existed, or the
// first sync after an upgrade would push the entire vault as changed. Byte-for-byte, so a new field
// that serialised ahead of these — or a null that serialised as null — would fail here.
var bytes = HostSecretCodec.Encode(Host(username: null, notes: null));
Encoding.UTF8.GetString(bytes).ShouldBe(
"""
{"schemaVersion":1,"label":"prod-db","hostname":"db.internal","port":22,"jumpHostIds":[],"options":{},"relayEnabled":false}
""");
}
[Fact]
public void AHostBoundToAKeyByANewerClient_IsReadableButNotWritableHere()
{
// What an older build sees. Simulated by a version past this one rather than by an older codec,
// since the mechanism is the comparison and not the field: read the item, refuse to re-encode it.
var payload = Encoding.UTF8.GetBytes(
"""
{"schemaVersion":99,"label":"prod-db","hostname":"db.internal","port":22,"certificateId":"something this build has never heard of"}
""");
HostSecretCodec.TryDecode(payload, out var document).ShouldBeTrue();
document.ShouldNotBeNull();
document.IsReadOnly.ShouldBeTrue();
}
[Fact]
public void AMinimalHost_RoundTrips()
{
@@ -55,6 +55,7 @@ public sealed class HostSecretMergeTests
JumpHostIds = JumpChain.Create([Bastion]),
Options = HostOptions.Create([new HostOption("Compression", "yes")]),
RelayEnabled = true,
SshKeyId = DeployKey,
};
var result = HostSecretMerge.Merge(ancestor, local, ancestor);
@@ -63,6 +64,59 @@ public sealed class HostSecretMergeTests
result.HasConflicts.ShouldBeFalse();
}
[Fact]
public void ARemovedKeyBinding_IsNotResurrectedByTheOtherSide()
{
// The other direction, and the one a two-way diff gets wrong: null is a value here, not an absence.
// A host deliberately put back on a password must not silently regain its key because the server's
// copy still names one.
var ancestor = Host(sshKeyId: DeployKey);
var local = ancestor with { SshKeyId = null };
var result = HostSecretMerge.Merge(ancestor, local, ancestor);
result.Merged.SshKeyId.ShouldBeNull();
result.HasConflicts.ShouldBeFalse();
}
[Fact]
public void TwoSidesBindingDifferentKeys_NamesBothIdsInTheConflict()
{
// An id is not a secret — it names a vault item rather than being the key — so both are shown. The
// user cannot tell which of two keys was dropped otherwise.
var other = Guid.Parse("0192f0c8-4444-7c3d-8e4f-5a6b7c8d9e04");
var ancestor = Host();
var local = ancestor with { SshKeyId = DeployKey };
var remote = ancestor with { SshKeyId = other };
var result = HostSecretMerge.Merge(ancestor, local, remote);
result.Merged.SshKeyId.ShouldBe(other);
var conflict = result.Conflicts.ShouldHaveSingleItem();
conflict.Field.ShouldBe(nameof(HostSecret.SshKeyId));
conflict.Kept.ShouldBe(other.ToString());
conflict.Discarded.ShouldBe(DeployKey.ToString());
}
[Fact]
public void ABindingClashingWithItsRemoval_SaysWhichSideHadNoKey()
{
// "no key" rather than a blank, for the same reason a clashing port is reported as a number: a
// conflict entry whose discarded value is empty reads as a bug in the conflict log.
var ancestor = Host(sshKeyId: DeployKey);
var local = ancestor with { SshKeyId = null };
var remote = ancestor with { SshKeyId = Relay };
var result = HostSecretMerge.Merge(ancestor, local, remote);
var conflict = result.Conflicts.ShouldHaveSingleItem();
conflict.Field.ShouldBe(nameof(HostSecret.SshKeyId));
conflict.Kept.ShouldBe(Relay.ToString());
conflict.Discarded.ShouldBe("no key");
}
[Fact]
public void AClashingScalar_TakesRemoteAndNamesTheFieldItDiscarded()
{