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
+8 -8
View File
@@ -623,14 +623,14 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
new SyncPushRequest([KeyOperation(keyId, expectedVersion: null, envelope: [9, 8, 7])]));
var results = await pushed.Content.ReadContractAsync<SyncPushResponse>();
results.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
results!.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
var pulled = await client.PostContractAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, [SyncEntityType.SshKey]));
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
var change = page.Changes.ShouldHaveSingleItem();
var change = page!.Changes.ShouldHaveSingleItem();
change.EntityType.ShouldBe(SyncEntityType.SshKey);
change.EntityId.ShouldBe(keyId);
@@ -654,10 +654,10 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>()).Results.ShouldHaveSingleItem();
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results.ShouldHaveSingleItem();
result.Status.ShouldBe(SyncOperationStatus.Invalid);
result.Detail.ShouldContain("no relay target");
result.Detail.ShouldNotBeNull().ShouldContain("no relay target");
}
/// <remarks>
@@ -682,7 +682,7 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
KeyOperation(keyId, expectedVersion: null, envelope: [2, 2]),
]));
(await pushed.Content.ReadContractAsync<SyncPushResponse>()).Results
(await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
.ShouldAllBe(result => result.Status == SyncOperationStatus.Applied);
var pulled = await client.PostContractAsync(
@@ -691,7 +691,7 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
page.Changes.Count.ShouldBe(2);
page!.Changes.Count.ShouldBe(2);
page.Changes.Select(change => change.ChangeSequence)
.ShouldBeInOrder(Shouldly.SortDirection.Ascending);
@@ -733,7 +733,7 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
PlaintextFields: null),
]));
(await deleted.Content.ReadContractAsync<SyncPushResponse>()).Results
(await deleted.Content.ReadContractAsync<SyncPushResponse>())!.Results
.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
var pulled = await client.PostContractAsync(
@@ -741,7 +741,7 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
new SyncPullRequest(null, null, [SyncEntityType.SshKey]));
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
var last = page.Changes[^1];
var last = page!.Changes[^1];
last.Operation.ShouldBe(SyncOperation.Delete);
last.Payload.ShouldBeNull("a tombstone must not ship the key material it replaced");
+118 -31
View File
@@ -738,27 +738,22 @@ public sealed class ShellFlowTests : IAsyncLifetime
}
[Fact]
public async Task AddingAKey_DoesNotSelectItForAuthenticationByItself()
public async Task AddingAKey_BindsItToNothing()
{
// Loading or saving must not decide how the next connection authenticates. The alternative — the
// host list's habit of selecting the first row — would mean a key nobody chose being offered to a
// host, which is a credential leaving the vault by accident.
// Storing a key must not change how any host authenticates. The failure this rules out is a key
// nobody chose being offered to a host — a credential leaving the vault by accident.
await UnlockedAsync();
var vault = shell.Vault!;
await AddHostAsync(vault, "prod-db");
await AddKeyAsync(vault, "deploy");
vault.UseKeyAuthentication.ShouldBeFalse();
vault.Hosts.ShouldHaveSingleItem().Host.SshKeyId.ShouldBeNull();
vault.Hosts[0].Authentication.ShouldBe("password");
await vault.SyncCommand.ExecuteAsync(null);
vault.Keys.ShouldHaveSingleItem();
vault.SelectedKey.ShouldNotBeNull("saving selects the key it just saved, so it can be edited");
// But a reload that did not save anything leaves the selection alone rather than inventing one.
vault.SelectedKey = null;
await vault.SyncCommand.ExecuteAsync(null);
vault.SelectedKey.ShouldBeNull();
vault.Hosts.ShouldHaveSingleItem().Host.SshKeyId.ShouldBeNull();
}
[Fact]
@@ -912,32 +907,60 @@ public sealed class ShellFlowTests : IAsyncLifetime
vault.IsEditingKey.ShouldBeFalse();
}
// ---- Authenticating with a key ----
// ---- Binding a key to a host ----
[Fact]
public async Task ConnectingWithoutKeyAuthentication_UsesThePassword()
public async Task BindingAKeyToAHost_RoundTripsThroughTheEditorAndTheVault()
{
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy");
// A key exists and is even selected. Without the switch it must still be the password that is used.
var keyId = vault.Keys[0].EntityId;
await BindKeyAsync(vault, vault.Hosts[0], keyId);
vault.Hosts.ShouldHaveSingleItem().Host.SshKeyId.ShouldBe(keyId);
vault.Hosts[0].Authentication.ShouldBe("key");
// Through the server and back, which is what makes it a property of the host rather than of this
// machine — the whole reason it is a payload field and not a local preference.
await vault.SyncCommand.ExecuteAsync(null);
vault.Hosts.ShouldHaveSingleItem().Host.SshKeyId.ShouldBe(keyId);
// And it is offered back correctly when the editor reopens, including as the current selection.
vault.SelectedHost = vault.Hosts[0];
vault.EditSelectedHostCommand.Execute(null);
vault.EditorSelectedKey.ShouldNotBeNull().EntityId.ShouldBe(keyId);
vault.EditorKeyChoices[0].EntityId.ShouldBeNull("the password entry stays first");
}
[Fact]
public async Task AHostWithNoKey_UsesThePassword()
{
var vault = await ReadyToConnectAsync();
// A key exists in the vault and is even selected in the key list. An unbound host must still use
// the password: the list selection is for editing keys, not for deciding authentication.
await AddKeyAsync(vault, "deploy");
vault.SelectedKey = vault.Keys[0];
vault.ConnectPassword = "typed-in";
await ConnectWithRendererAsync(vault);
var credential = ssh.Requests.ShouldHaveSingleItem().Credential;
credential.ShouldBeOfType<SshPasswordCredential>().Password.ShouldBe("typed-in");
ssh.Requests.ShouldHaveSingleItem().Credential
.ShouldBeOfType<SshPasswordCredential>()
.Password.ShouldBe("typed-in");
}
[Fact]
public async Task ConnectingWithKeyAuthentication_HandsTheSshStackTheKeyAndItsPassphrase()
public async Task AHostBoundToAKey_HandsTheSshStackTheKeyAndItsPassphrase()
{
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy");
await BindKeyAsync(vault, vault.Hosts[0], vault.Keys[0].EntityId);
vault.SelectedKey = vault.Keys[0];
vault.UseKeyAuthentication = true;
vault.ConnectPassword = "should-not-be-used";
await ConnectWithRendererAsync(vault);
@@ -961,12 +984,9 @@ public sealed class ShellFlowTests : IAsyncLifetime
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy", passphrase: string.Empty);
var row = vault.Keys.ShouldHaveSingleItem();
row.Description.ShouldStartWith("no passphrase");
vault.SelectedKey = row;
vault.UseKeyAuthentication = true;
vault.Keys.ShouldHaveSingleItem().Description.ShouldStartWith("no passphrase");
await BindKeyAsync(vault, vault.Hosts[0], vault.Keys[0].EntityId);
await ConnectWithRendererAsync(vault);
ssh.Requests.ShouldHaveSingleItem().Credential
@@ -975,21 +995,76 @@ public sealed class ShellFlowTests : IAsyncLifetime
}
[Fact]
public async Task KeyAuthenticationWithNoKeyChosen_RefusesRatherThanFallingBackToThePassword()
public async Task AHostWhoseKeyHasBeenDeleted_RefusesRatherThanFallingBackToThePassword()
{
// The failure this prevents is silent: a user who asked for key authentication and got password
// authentication has sent a password to a host that was meant never to see one.
// A key deleted on another machine is ordinary, and this is what it must not cause: a host somebody
// deliberately set up for key-only access quietly starting to offer a password instead.
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy");
await BindKeyAsync(vault, vault.Hosts[0], vault.Keys[0].EntityId);
vault.SelectedKey = null;
vault.UseKeyAuthentication = true;
vault.SelectedKey = vault.Keys[0];
await vault.DeleteKeyCommand.ExecuteAsync(null);
vault.Keys.ShouldBeEmpty();
vault.SelectedHost = vault.Hosts[0];
vault.ConnectPassword = "must-not-be-sent";
await vault.ConnectCommand.ExecuteAsync(null);
ssh.Requests.ShouldBeEmpty("nothing should have been dialled at all");
vault.Status.ShouldContain("key");
vault.Status.ShouldContain("not in this vault");
}
[Fact]
public async Task EditingAHostWhoseKeyHasBeenDeleted_DoesNotQuietlyUnbindIt()
{
// The same failure one step removed, and the subtler one. Someone opens the host to change its port;
// if the picker had silently fallen back to "no key", saving would convert it to password
// authentication and nothing would ever have said so.
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy");
var keyId = vault.Keys[0].EntityId;
await BindKeyAsync(vault, vault.Hosts[0], keyId);
vault.SelectedKey = vault.Keys[0];
await vault.DeleteKeyCommand.ExecuteAsync(null);
vault.SelectedHost = vault.Hosts[0];
vault.EditSelectedHostCommand.Execute(null);
// The binding is still there, still selected, and says what is wrong with it.
var selected = vault.EditorSelectedKey.ShouldNotBeNull();
selected.EntityId.ShouldBe(keyId);
selected.Label.ShouldContain("no longer here");
vault.EditorPort = 2244;
await vault.SaveHostCommand.ExecuteAsync(null);
vault.Hosts.ShouldHaveSingleItem().Host.Port.ShouldBe(2244);
vault.Hosts[0].Host.SshKeyId.ShouldBe(keyId, "an unrelated edit must not drop the binding");
}
[Fact]
public async Task RemovingABinding_PutsTheHostBackOnAPassword()
{
var vault = await ReadyToConnectAsync();
await AddKeyAsync(vault, "deploy");
await BindKeyAsync(vault, vault.Hosts[0], vault.Keys[0].EntityId);
vault.SelectedHost = vault.Hosts[0];
vault.EditSelectedHostCommand.Execute(null);
vault.EditorSelectedKey = vault.EditorKeyChoices.Single(choice => choice.EntityId is null);
await vault.SaveHostCommand.ExecuteAsync(null);
vault.Hosts.ShouldHaveSingleItem().Host.SshKeyId.ShouldBeNull();
vault.Hosts[0].Authentication.ShouldBe("password");
vault.ConnectPassword = "typed-in";
await ConnectWithRendererAsync(vault);
ssh.Requests.ShouldHaveSingleItem().Credential.ShouldBeOfType<SshPasswordCredential>();
}
// ---- Helpers ----
@@ -1074,6 +1149,18 @@ public sealed class ShellFlowTests : IAsyncLifetime
await vault.SaveKeyCommand.ExecuteAsync(null);
}
/// <summary>Points a host at a key through the editor, the way a user would.</summary>
private static async Task BindKeyAsync(VaultViewModel vault, HostRowViewModel host, Guid keyId)
{
vault.SelectedHost = host;
vault.EditSelectedHostCommand.Execute(null);
vault.IsEditing.ShouldBeTrue("the host editor has to be open for the picker to be populated");
vault.EditorSelectedKey = vault.EditorKeyChoices.Single(choice => choice.EntityId == keyId);
await vault.SaveHostCommand.ExecuteAsync(null);
}
/// <summary>Connects with a renderer attached, which the data plane requires before a session opens.</summary>
private async Task ConnectWithRendererAsync(VaultViewModel vault)
{
@@ -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()
{
@@ -71,17 +71,19 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
var laptop = await UnlockAsync(laptopCache);
await using var laptopSession = laptop;
var host = BuildHost();
var entityId = await laptop.Hosts.CreateAsync(laptop.ActiveVaultId, host, Token);
// A second item type, in the same vault and the same outbox. Two of them is what makes this a test
// of the shared write path rather than of hosts: the server picks a table per type, the client picks
// a cipher per type, and the AAD binds a different resource type into each. All three of those are
// hand-kept mappings between enums that do not line up, and a swap between them encrypts, decrypts
// and stores perfectly on the machine that made it.
// The key first, because the host binds it. A second item type in the same vault and the same
// outbox is what makes this a test of the shared write path rather than of hosts: the server picks a
// table per type, the client picks a cipher per type, and the AAD binds a different resource type
// into each. All three are hand-kept mappings between enums that do not line up, and a swap between
// them encrypts, decrypts and stores perfectly on the machine that made it.
var key = BuildKey();
var keyId = await laptop.SshKeys.CreateAsync(laptop.ActiveVaultId, key, Token);
// Bound to the key, which also makes this host a schema-version-2 payload — so the slice covers a
// payload written at a version older clients will refuse to edit, through the real server.
var host = BuildHost(keyId);
var entityId = await laptop.Hosts.CreateAsync(laptop.ActiveVaultId, host, Token);
var pushed = await laptop.SyncAsync(connection.Sync, Token);
pushed.Pushed.ShouldBe(2);
pushed.NeedsAttention.ShouldBeFalse();
@@ -297,7 +299,7 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
/// </remarks>
private string ServerUrl => stack.ApiBaseUrl.ToString();
private HostSecret BuildHost() =>
private HostSecret BuildHost(Guid sshKeyId) =>
new()
{
Label = "e2e-target",
@@ -306,6 +308,7 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
Username = DevStack.SshUsername,
Notes = "created by the end-to-end slice",
Options = HostOptions.Create([new HostOption("ServerAliveInterval", "30")]),
SshKeyId = sshKeyId,
};
/// <remarks>