Public Access
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:
@@ -128,14 +128,14 @@ skipped and cannot be recovered from the server. You can then add a host and ope
|
||||
admin console is at `http://localhost:18080` (`admin` / `admin`).
|
||||
|
||||
You can also add an SSH key, which is stored in the vault like a host and synced the same way: paste the
|
||||
private key, tick **Use key** next to Connect, and the selected key authenticates instead of a password.
|
||||
private key, then edit a host and pick that key from its **key** dropdown. From then on that host
|
||||
authenticates with it — on every machine, since the choice travels inside the host's encrypted payload —
|
||||
and its password box disappears.
|
||||
|
||||
Three of M1's known gaps are visible immediately, so they are worth expecting rather than diagnosing:
|
||||
password authentication asks for the password every time, because credentials are not a synced entity type
|
||||
yet (keys are — passwords are not); a key is chosen per connection rather than remembered per host, because
|
||||
binding one to a host needs a new field on the host payload and so a schema version bump; and unlock asks
|
||||
for the passphrase on every launch, because no device key is registered. Host key trust also lasts one
|
||||
session, because known hosts do not live in the vault yet.
|
||||
yet (keys are — passwords are not); host key trust lasts one session, because known hosts do not live in the
|
||||
vault yet; and unlock asks for the passphrase on every launch, because no device key is registered.
|
||||
|
||||
### End-to-end verification
|
||||
|
||||
@@ -203,10 +203,15 @@ off-Windows.
|
||||
|
||||
Known gaps in the client, stated rather than implied by the interface: credentials are not a synced
|
||||
entity type yet, so password authentication still asks for the password each time — SSH keys *are*
|
||||
synced, and are the way to connect without typing anything; a key is picked per connection rather than
|
||||
bound to a host, which needs a field on the host payload and therefore a schema version bump; known host
|
||||
keys live in memory for one session instead of in the vault; and no device key is registered, so the
|
||||
passphrase is needed on every launch until the OS keystore is wired.
|
||||
synced, and binding one to a host is the way to connect without typing anything; known host keys live in
|
||||
memory for one session instead of in the vault; and no device key is registered, so the passphrase is
|
||||
needed on every launch until the OS keystore is wired.
|
||||
|
||||
Binding a key introduced the first payload schema version bump, and it is worth knowing how it behaves:
|
||||
a host is written at the *lowest* schema version that can represent it, so only hosts that actually bind
|
||||
a key are written at version 2 and become read-only on an older build. Hosts that do not are still
|
||||
written at version 1, byte-identically to before the field existed — which is what keeps upgrading one
|
||||
machine from making a team's whole vault uneditable everywhere else.
|
||||
- **M2 — full personal vault**, robust sync, relay.
|
||||
- **M3 — teams**, sharing, ACLs.
|
||||
- **M4 — hardening and ops**, packaging, self-hosting guide.
|
||||
|
||||
@@ -36,10 +36,42 @@ internal sealed class HostRowViewModel(VaultItem<HostSecret> host)
|
||||
|
||||
internal bool IsReadOnly => host.IsReadOnly;
|
||||
|
||||
/// <summary>How this host authenticates, in one word.</summary>
|
||||
/// <remarks>
|
||||
/// Worth a word in the list because the two behave differently at the moment of connecting: one needs
|
||||
/// the password box filled in and the other does not, and a user staring at an empty password box on a
|
||||
/// key-authenticated host has no other way to know it is not needed.
|
||||
/// </remarks>
|
||||
internal string Authentication => host.Secret.SshKeyId is null ? "password" : "key";
|
||||
|
||||
/// <summary>A short marker for the row, so the list says what it knows without a tooltip.</summary>
|
||||
internal string Badge => ItemBadge.For(host.IsBlocked, host.IsReadOnly, host.HasUnsyncedChanges);
|
||||
}
|
||||
|
||||
/// <summary>An entry in the host editor's key picker.</summary>
|
||||
/// <param name="EntityId">The key's item id, or null for password authentication.</param>
|
||||
/// <param name="Label">What to show.</param>
|
||||
/// <remarks>
|
||||
/// A sentinel entry rather than a nullable selection, because a ComboBox with nothing selected and a
|
||||
/// ComboBox meaning "no key" look identical and are not the same thing — the first is a host whose binding
|
||||
/// has not been decided, the second is a decision.
|
||||
/// </remarks>
|
||||
internal sealed record SshKeyChoice(Guid? EntityId, string Label)
|
||||
{
|
||||
/// <summary>The "use a password" entry, always first.</summary>
|
||||
internal static SshKeyChoice None { get; } = new(null, "Password (no key)");
|
||||
|
||||
/// <summary>
|
||||
/// A stand-in for a key the host names and the vault no longer has.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Kept in the list, and kept selected, so that opening a host to change its port does not silently
|
||||
/// convert it to password authentication on save. The id is preserved; only the label admits the
|
||||
/// problem.
|
||||
/// </remarks>
|
||||
internal static SshKeyChoice Missing(Guid entityId) => new(entityId, "(a key that is no longer here)");
|
||||
}
|
||||
|
||||
/// <summary>One SSH key, as a row in the list.</summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -147,10 +179,10 @@ internal sealed class ConflictRowViewModel(ConflictNotice notice)
|
||||
/// than a design choice, and the interface says so rather than implying the vault holds more than it does.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>A key is chosen per connection, not per host.</b> Binding a key to a host is the better answer and it
|
||||
/// is not free: it means a new field on <c>HostSecret</c>, which means bumping the payload schema version,
|
||||
/// which makes every host written afterwards read-only on an older build. Worth doing deliberately rather
|
||||
/// than as a side effect of adding keys, so for now this works the way <c>ssh -i</c> does.
|
||||
/// <b>A key belongs to a host.</b> Each host names the key it authenticates with, or none, and that choice
|
||||
/// is a field in its encrypted payload — so it follows the host to every machine rather than being made
|
||||
/// again per connection. The cost is a payload schema version, paid only by hosts that actually bind a key:
|
||||
/// see <c>HostSecretCodec.CurrentSchemaVersion</c>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed partial class VaultViewModel(
|
||||
@@ -227,6 +259,20 @@ internal sealed partial class VaultViewModel(
|
||||
[ObservableProperty]
|
||||
private bool editorRelayEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// What the key picker offers: password, then every key in the vault.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Rebuilt when the editor opens rather than kept in step with the key list. A background sync could
|
||||
/// pull a new key while a host is being edited, and having the picker's contents change under the user
|
||||
/// mid-edit is worse than the list being a minute stale — the two editors cannot be open at once, so
|
||||
/// the only way to add a key is to close this one anyway.
|
||||
/// </remarks>
|
||||
internal ObservableCollection<SshKeyChoice> EditorKeyChoices { get; } = [];
|
||||
|
||||
[ObservableProperty]
|
||||
private SshKeyChoice? editorSelectedKey;
|
||||
|
||||
/// <summary>The item being edited, or null when creating.</summary>
|
||||
private Guid? editingEntityId;
|
||||
|
||||
@@ -269,16 +315,8 @@ internal sealed partial class VaultViewModel(
|
||||
[ObservableProperty]
|
||||
private string connectPassword = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Whether to authenticate with the selected key rather than a password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An explicit switch rather than "use the key if one happens to be selected". The key list's selection
|
||||
/// exists to edit and delete keys, and letting it silently change how the next connection authenticates
|
||||
/// would make clicking a row to rename it alter what Connect does.
|
||||
/// </remarks>
|
||||
[ObservableProperty]
|
||||
private bool useKeyAuthentication;
|
||||
/// <summary>Whether the selected host authenticates with a key, so the password box can say so.</summary>
|
||||
internal bool SelectedHostUsesAKey => SelectedHost?.Host.SshKeyId is not null;
|
||||
|
||||
[ObservableProperty]
|
||||
private HostKeyPresentation? pendingHostKey;
|
||||
@@ -545,6 +583,7 @@ internal sealed partial class VaultViewModel(
|
||||
EditorUsername = string.Empty;
|
||||
EditorNotes = string.Empty;
|
||||
EditorRelayEnabled = false;
|
||||
BuildKeyChoices(boundKeyId: null);
|
||||
IsEditing = true;
|
||||
Status = "Adding a host.";
|
||||
}
|
||||
@@ -573,6 +612,7 @@ internal sealed partial class VaultViewModel(
|
||||
EditorUsername = row.Host.Username ?? string.Empty;
|
||||
EditorNotes = row.Host.Notes ?? string.Empty;
|
||||
EditorRelayEnabled = row.Host.RelayEnabled;
|
||||
BuildKeyChoices(row.Host.SshKeyId);
|
||||
IsEditing = true;
|
||||
Status = $"Editing {row.Label}.";
|
||||
}
|
||||
@@ -796,12 +836,13 @@ internal sealed partial class VaultViewModel(
|
||||
return;
|
||||
}
|
||||
|
||||
if (UseKeyAuthentication && SelectedKey is null)
|
||||
if (TryBuildCredential(row.Host) is not { } credential)
|
||||
{
|
||||
// Refused rather than quietly falling back to the password box. Silently authenticating a
|
||||
// different way than the user asked for is how a password reaches a host that was meant to
|
||||
// only ever see a key.
|
||||
Status = "Choose a key to authenticate with, or turn key authentication off.";
|
||||
// Refused rather than quietly falling back to the password box. A host set up for key-only
|
||||
// access that silently starts offering a password is the failure worth ruling out — the user
|
||||
// asked for one thing and got another, and the host is the last place that would say so.
|
||||
Status = $"'{row.Label}' authenticates with an SSH key that is not in this vault any more. "
|
||||
+ "Edit the host to choose another key, or set it back to a password.";
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -810,7 +851,7 @@ internal sealed partial class VaultViewModel(
|
||||
|
||||
await RunAsync(
|
||||
$"Connecting to {row.Label}…",
|
||||
() => OpenSessionAsync(row, cancellationToken)).ConfigureAwait(true);
|
||||
() => OpenSessionAsync(row, credential, cancellationToken)).ConfigureAwait(true);
|
||||
}
|
||||
|
||||
/// <summary>Pins the offered host key and retries.</summary>
|
||||
@@ -891,7 +932,10 @@ internal sealed partial class VaultViewModel(
|
||||
/// output at a terminal that was never created. That wait is bounded and takes this command's token, so
|
||||
/// a renderer that never arrives ends as a message rather than as a window stuck on "Connecting…".
|
||||
/// </remarks>
|
||||
private async Task OpenSessionAsync(HostRowViewModel row, CancellationToken cancellationToken)
|
||||
private async Task OpenSessionAsync(
|
||||
HostRowViewModel row,
|
||||
SshCredential credential,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -901,7 +945,7 @@ internal sealed partial class VaultViewModel(
|
||||
row.Host.Hostname,
|
||||
row.Host.Port,
|
||||
row.Host.Username!,
|
||||
BuildCredential());
|
||||
credential);
|
||||
|
||||
await workspace
|
||||
.OpenSessionAsync(request, TerminalSize.Default, cancellationToken)
|
||||
@@ -937,27 +981,36 @@ internal sealed partial class VaultViewModel(
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How the next connection authenticates.
|
||||
/// How this host authenticates, or null when it names a key the vault does not have.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The key material is handed over as UTF-8 bytes, which is what <c>PrivateKeyFile</c> reads from a
|
||||
/// <c>MemoryStream</c> — so the key reaches SSH.NET without ever becoming a file on disk. The
|
||||
/// passphrase goes with it: a key stored in the vault together with its passphrase is the whole point
|
||||
/// of a vault, and <c>SshKeySecret</c> says why.
|
||||
/// of a vault, and <c>SshKeySecret</c> says why. It is passed straight through with no empty-to-null
|
||||
/// check, because <c>SshKeySecret.Passphrase</c> cannot hold an empty string.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The passphrase is passed straight through, with no empty-to-null check, because
|
||||
/// <c>SshKeySecret.Passphrase</c> cannot hold an empty string — it normalises one to null on the way in.
|
||||
/// Null is a refusal, not a fallback, and the caller must treat it as one. A dangling reference means a
|
||||
/// key was deleted on another machine — plausible, and no reason to start sending a password to a host
|
||||
/// somebody deliberately set up not to accept one.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private SshCredential BuildCredential()
|
||||
private SshCredential? TryBuildCredential(HostSecret host)
|
||||
{
|
||||
if (!UseKeyAuthentication || SelectedKey is not { } row)
|
||||
if (host.SshKeyId is not { } keyId)
|
||||
{
|
||||
return new SshPasswordCredential(ConnectPassword);
|
||||
}
|
||||
|
||||
if (Keys.FirstOrDefault(row => row.EntityId == keyId) is not { } key)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new SshPrivateKeyCredential(
|
||||
Encoding.UTF8.GetBytes(row.Key.PrivateKeyPem), row.Key.Passphrase);
|
||||
Encoding.UTF8.GetBytes(key.Key.PrivateKeyPem), key.Key.Passphrase);
|
||||
}
|
||||
|
||||
private HostSecret BuildHost() =>
|
||||
@@ -969,8 +1022,42 @@ internal sealed partial class VaultViewModel(
|
||||
Username = string.IsNullOrWhiteSpace(EditorUsername) ? null : EditorUsername.Trim(),
|
||||
Notes = string.IsNullOrWhiteSpace(EditorNotes) ? null : EditorNotes,
|
||||
RelayEnabled = EditorRelayEnabled,
|
||||
|
||||
// Whatever the picker holds, including the id of a key that has gone missing. Reading it from
|
||||
// the picker rather than carrying the original through is what lets a binding be removed at all,
|
||||
// and preserving a missing id is what stops an unrelated edit removing one by accident.
|
||||
SshKeyId = EditorSelectedKey?.EntityId,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Fills the key picker, keeping whatever the host is currently bound to selectable.
|
||||
/// </summary>
|
||||
/// <param name="boundKeyId">The key the host names, or null for password authentication.</param>
|
||||
/// <remarks>
|
||||
/// A bound key that is no longer in the vault gets a placeholder entry rather than being dropped. Without
|
||||
/// one the picker would open on "Password (no key)", and someone editing the host's port would convert it
|
||||
/// to password authentication by saving — which is the quiet version of the failure the connect path
|
||||
/// refuses outright.
|
||||
/// </remarks>
|
||||
private void BuildKeyChoices(Guid? boundKeyId)
|
||||
{
|
||||
EditorKeyChoices.Clear();
|
||||
EditorKeyChoices.Add(SshKeyChoice.None);
|
||||
|
||||
foreach (var key in Keys)
|
||||
{
|
||||
EditorKeyChoices.Add(new SshKeyChoice(key.EntityId, key.Label));
|
||||
}
|
||||
|
||||
if (boundKeyId is { } bound && EditorKeyChoices.All(choice => choice.EntityId != bound))
|
||||
{
|
||||
EditorKeyChoices.Add(SshKeyChoice.Missing(bound));
|
||||
}
|
||||
|
||||
EditorSelectedKey = EditorKeyChoices.FirstOrDefault(choice => choice.EntityId == boundKeyId)
|
||||
?? SshKeyChoice.None;
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The private key is not trimmed. Its armour is whitespace-significant and a client that tidied it up
|
||||
/// would eventually tidy a format it did not fully understand — the same reason
|
||||
@@ -1129,6 +1216,9 @@ internal sealed partial class VaultViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnSelectedHostChanged(HostRowViewModel? value) =>
|
||||
OnPropertyChanged(nameof(SelectedHostUsesAKey));
|
||||
|
||||
partial void OnPendingHostKeyChanged(HostKeyPresentation? value) =>
|
||||
OnPropertyChanged(nameof(HasPendingHostKey));
|
||||
|
||||
|
||||
@@ -111,8 +111,16 @@
|
||||
VerticalAlignment="Center" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding Address}" Classes="hint" FontSize="11"
|
||||
FontFamily="ui-monospace,Consolas,monospace" />
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<TextBlock Text="{Binding Address}" Classes="hint" FontSize="11"
|
||||
FontFamily="ui-monospace,Consolas,monospace" />
|
||||
<!--
|
||||
Which of the two ways this host authenticates. In the list because the password box
|
||||
below is only relevant to one of them, and an empty box on a key-authenticated host is
|
||||
otherwise indistinguishable from one somebody forgot to fill in.
|
||||
-->
|
||||
<TextBlock Text="{Binding Authentication}" Classes="hint" FontSize="11" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
@@ -128,6 +136,21 @@
|
||||
<TextBox Text="{Binding Vault.EditorUsername}" PlaceholderText="username" />
|
||||
<TextBox Text="{Binding Vault.EditorNotes}" PlaceholderText="notes" AcceptsReturn="True"
|
||||
Height="60" TextWrapping="Wrap" />
|
||||
<!--
|
||||
Which key this host authenticates with, or a password. Part of the host rather than of the
|
||||
connection, so it follows the host to every machine; a host bound to a key that has since been
|
||||
deleted keeps a placeholder entry here, so that editing the port cannot quietly turn it back
|
||||
into a password host.
|
||||
-->
|
||||
<ComboBox ItemsSource="{Binding Vault.EditorKeyChoices}"
|
||||
SelectedItem="{Binding Vault.EditorSelectedKey}"
|
||||
HorizontalAlignment="Stretch">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:SshKeyChoice">
|
||||
<TextBlock Text="{Binding Label}" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<CheckBox IsChecked="{Binding Vault.EditorRelayEnabled}"
|
||||
Content="Allow connecting through the server relay" />
|
||||
<!--
|
||||
@@ -237,22 +260,21 @@
|
||||
-->
|
||||
<TextBox Text="{Binding Vault.ConnectPassword}" PlaceholderText="password (not stored yet)"
|
||||
PasswordChar="•" Width="220" VerticalAlignment="Center"
|
||||
IsEnabled="{Binding !Vault.UseKeyAuthentication}" />
|
||||
IsVisible="{Binding !Vault.SelectedHostUsesAKey}" />
|
||||
<!--
|
||||
An explicit switch, not "use a key if one is selected". The key list's selection is there to
|
||||
edit and delete keys, and letting it decide how the next connection authenticates would mean
|
||||
clicking a row to rename it changed what Connect does.
|
||||
Hidden rather than disabled for the key case, unlike most of this window. A disabled password
|
||||
box invites the reading that a password is wanted and unavailable; the honest statement for a
|
||||
key-authenticated host is that nothing needs typing, and an absent box says that better than a
|
||||
greyed-out one.
|
||||
-->
|
||||
<CheckBox IsChecked="{Binding Vault.UseKeyAuthentication}" Content="Use key"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip.Tip="Authenticate with the SSH key selected in the list, instead of a password." />
|
||||
<TextBlock Text="{Binding Vault.SelectedKey.Label, FallbackValue='no key selected'}"
|
||||
Foreground="#bcd2ea" FontSize="11" VerticalAlignment="Center"
|
||||
IsVisible="{Binding Vault.UseKeyAuthentication}" />
|
||||
<TextBlock Text="This host authenticates with its SSH key." Classes="hint" FontSize="11"
|
||||
VerticalAlignment="Center"
|
||||
IsVisible="{Binding Vault.SelectedHostUsesAKey}" />
|
||||
<Button Content="Connect" Command="{Binding Vault.ConnectCommand}"
|
||||
IsEnabled="{Binding !Vault.IsBusy}" VerticalAlignment="Center" />
|
||||
<TextBlock Classes="hint" FontSize="11" VerticalAlignment="Center"
|
||||
Text="Keys are in the vault; passwords are not yet." />
|
||||
Text="Keys are in the vault; passwords are not yet."
|
||||
IsVisible="{Binding !Vault.SelectedHostUsesAKey}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
|
||||
@@ -57,6 +57,31 @@ public sealed record HostSecret : IVaultSecret
|
||||
/// <summary>SSH directives, unique by name.</summary>
|
||||
public HostOptions Options { get; init; } = HostOptions.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The vault SSH key to authenticate with, or null to use a password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// An item id rather than the key itself, because the key is a vault item in its own right and a copy
|
||||
/// embedded here would be a second copy of a private key to keep in step — rotated in one place and
|
||||
/// stale in the other. The cost is that the reference can dangle: the key may be deleted on another
|
||||
/// machine while this host still names it. That is handled where it is noticed rather than prevented
|
||||
/// here, and it is handled by refusing to connect, never by falling back to a password. Quietly sending
|
||||
/// a password to a host the user had set up for key-only access is the one outcome worth ruling out.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Inside the encrypted payload, like everything else. It would have fitted the contract's plaintext
|
||||
/// <c>RelatedId</c> column, and putting it there would tell the server which hosts share a key — a
|
||||
/// graph of the user's infrastructure it has no need for.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This is the field that made the payload schema versioned in practice rather than in principle: see
|
||||
/// <see cref="HostSecretCodec.CurrentSchemaVersion"/> for what a host carrying one means to an older
|
||||
/// client, and why a host without one is still written at version 1.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public Guid? SshKeyId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this host may be dialled through the server relay.
|
||||
/// </summary>
|
||||
@@ -110,6 +135,14 @@ public sealed record HostSecret : IVaultSecret
|
||||
return false;
|
||||
}
|
||||
|
||||
if (SshKeyId == Guid.Empty)
|
||||
{
|
||||
// An empty id is not "no key" — that is null. It is a reference that can never resolve, and
|
||||
// storing one would produce a host that refuses to connect with no way to see why.
|
||||
reason = "An SSH key reference cannot be an empty id; use no key instead.";
|
||||
return false;
|
||||
}
|
||||
|
||||
reason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -53,8 +53,14 @@ public sealed record HostSecretDocument(HostSecret Host, int SchemaVersion)
|
||||
/// </remarks>
|
||||
public static class HostSecretCodec
|
||||
{
|
||||
/// <summary>The schema version this build writes.</summary>
|
||||
public const int CurrentSchemaVersion = 1;
|
||||
/// <summary>The first version, and the one a host with no newer field is still written at.</summary>
|
||||
public const int BaseSchemaVersion = 1;
|
||||
|
||||
/// <summary>The version that introduced <see cref="HostSecret.SshKeyId"/>.</summary>
|
||||
public const int SshKeyIdSchemaVersion = 2;
|
||||
|
||||
/// <summary>The highest schema version this build can write.</summary>
|
||||
public const int CurrentSchemaVersion = SshKeyIdSchemaVersion;
|
||||
|
||||
/// <summary>Serialises a host to the bytes that get sealed.</summary>
|
||||
/// <exception cref="ArgumentException">The host is not valid for storage.</exception>
|
||||
@@ -75,7 +81,7 @@ public static class HostSecretCodec
|
||||
|
||||
var document = new HostPayloadDocument
|
||||
{
|
||||
SchemaVersion = CurrentSchemaVersion,
|
||||
SchemaVersion = SchemaVersionFor(host),
|
||||
Label = host.Label,
|
||||
Hostname = host.Hostname,
|
||||
Port = host.Port,
|
||||
@@ -84,12 +90,35 @@ public static class HostSecretCodec
|
||||
JumpHostIds = [.. host.JumpHostIds],
|
||||
Options = options,
|
||||
RelayEnabled = host.RelayEnabled,
|
||||
SshKeyId = host.SshKeyId,
|
||||
};
|
||||
|
||||
return JsonSerializer.SerializeToUtf8Bytes(
|
||||
document, HostPayloadJsonContext.Default.HostPayloadDocument);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The lowest schema version that can represent this host without losing anything.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Not simply <see cref="CurrentSchemaVersion"/>, and in a shared vault the difference is the whole
|
||||
/// point. The version is what makes an older client treat an item as read-only, so stamping the newest
|
||||
/// one unconditionally would mean that upgrading a single machine and then touching <em>any</em> host —
|
||||
/// renaming it, changing a port — made that host uneditable on every machine that had not been upgraded
|
||||
/// yet. Emitting the lowest version that loses nothing confines that cost to the hosts which actually
|
||||
/// use the newer field.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The rule generalises, and the next field added should follow it: a host is written at the version
|
||||
/// that introduced the newest field it actually carries. It also means the bytes for a host with no key
|
||||
/// are identical to what this codec produced before <see cref="HostSecret.SshKeyId"/> existed, so
|
||||
/// adding the field did not make every host in every vault look like a change to the sync engine.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private static int SchemaVersionFor(HostSecret host) =>
|
||||
host.SshKeyId is null ? BaseSchemaVersion : SshKeyIdSchemaVersion;
|
||||
|
||||
/// <summary>
|
||||
/// Parses a decrypted payload.
|
||||
/// </summary>
|
||||
@@ -154,6 +183,7 @@ public static class HostSecretCodec
|
||||
JumpHostIds = JumpChain.Create(parsed.JumpHostIds ?? []),
|
||||
Options = options,
|
||||
RelayEnabled = parsed.RelayEnabled,
|
||||
SshKeyId = parsed.SshKeyId,
|
||||
};
|
||||
|
||||
if (!candidate.TryValidate(out _))
|
||||
@@ -199,6 +229,13 @@ internal sealed class HostPayloadDocument
|
||||
public SortedDictionary<string, string>? Options { get; set; }
|
||||
|
||||
public bool RelayEnabled { get; set; }
|
||||
|
||||
/// <remarks>
|
||||
/// Last, deliberately. Property order is the serialisation order, so appending keeps the bytes for every
|
||||
/// field that existed before this one byte-identical — and a null is omitted entirely, which is what
|
||||
/// makes a host with no key encode exactly as it did before the field existed.
|
||||
/// </remarks>
|
||||
public Guid? SshKeyId { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
|
||||
@@ -103,6 +103,17 @@ public static class HostSecretMerge
|
||||
remote.RelayEnabled,
|
||||
conflicts,
|
||||
static enabled => enabled ? "enabled" : "disabled"),
|
||||
|
||||
// The id is shown in a clash rather than redacted. It is not a secret — it names a vault item,
|
||||
// it is not the key — and hiding it would leave the user unable to tell which of two keys the
|
||||
// merge dropped.
|
||||
SshKeyId = Field(
|
||||
nameof(HostSecret.SshKeyId),
|
||||
ancestor.SshKeyId,
|
||||
local.SshKeyId,
|
||||
remote.SshKeyId,
|
||||
conflicts,
|
||||
static id => id?.ToString() ?? "no key"),
|
||||
};
|
||||
|
||||
return new HostMergeResult(merged, conflicts);
|
||||
@@ -117,8 +128,17 @@ public static class HostSecretMerge
|
||||
Field(name, ancestor, local, remote, conflicts, static value => value, StringComparer.Ordinal)!;
|
||||
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A scalar clash always overrides the local side — see <see cref="ThreeWayMerge"/> — so the
|
||||
/// discarded side is fixed here rather than derived.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The formatter is handed the discarded value even when that value is null, and the null-forgiving
|
||||
/// operator says why that is safe: a conflicted merge always has a discarded value, so a null here is a
|
||||
/// nullable field whose discarded value was "unset" rather than a missing one. Short-circuiting on null
|
||||
/// instead — which this did — meant the formatter never ran for exactly that case, so a field whose
|
||||
/// absence has a name could not report it and the conflict log showed an empty string in its place.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private static T Field<T>(
|
||||
string name,
|
||||
@@ -137,7 +157,7 @@ public static class HostSecretMerge
|
||||
name,
|
||||
MergeSide.Local,
|
||||
format(merge.Value),
|
||||
merge.Discarded is null ? null : format(merge.Discarded),
|
||||
format(merge.Discarded!),
|
||||
DiscardedWasRemoval: false));
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user