Sync and authenticate with SSH keys on the client

Completes the client half of SSH keys: they sync alongside hosts, appear in
their own list, and can be selected to authenticate a connection instead of
typing a password.

The reconciler and the repository were Host-typed throughout, so the choice was
to generalise them or to keep a second copy per item type. Generalised, because
ItemReconciler's whole premise is that the pull and the push paths must answer
the same collision the same way — two copies would drift the first time one of
them was fixed. What is genuinely per-type now arrives through
IItemKind<TSecret>: the cipher, the merge, the plaintext columns, and the noun
to use when telling a person what happened to their item. Generic where the
server's IItemKind is not, and for the reason that reverses there — the client
needs the concrete type, because it merges field by field.

The pull filter is derived from the same registry that builds the reconcilers.
That is the specific failure being designed out: an item type that encrypts,
merges and lists perfectly and is never once requested from the server, so it
works on the machine that made it and exists nowhere else.

No client cache migration. The item table's primary key and the outbox's unique
index already carry the entity type, and AadResourceTypes already mapped SshKey
— so a host and a key may share an id and never see each other's rows, which
SshKeySyncTests now arranges deliberately.

A key hands the server nothing in plaintext. There is a public_key_fingerprint
column and it would be accepted; leaving it null is deliberate. A fingerprint is
not secret but it is a stable identifier for a key pair, so filling it would let
an operator tell which of their users hold the same key and correlate one across
vaults, for a column nothing reads. The design allows itself one plaintext
concession — the relay address, which the relay cannot work without — and this
is not that.

A key is chosen per connection rather than bound to a host, which works the way
ssh -i does. Binding one needs a field on HostSecret and therefore a payload
schema bump, which makes every host written afterwards read-only on an older
build; worth doing deliberately rather than as a side effect of adding keys.

Three things this found, all of them by being falsified rather than by review:

- Making the reconciler generic silently turned a record comparison into
  reference equality, because == on a type parameter is not value equality. The
  effect would have been a conflict recorded on every pass for an unacknowledged
  create that had in fact landed. Sabotaging the fix left all 73 tests passing —
  nothing covered that branch — so ConflictMatrixTests now has
  AnUnacknowledgedCreateThatDidLand_IsDroppedQuietly, which fails without it.

- A test asserting that a blank passphrase reaches SSH.NET as null was vacuous:
  it exercised the editor, not the credential path, and passed with the guard
  deleted. Resolved by making SshKeySecret.Passphrase normalise an empty string
  to null, so there is one spelling of one state — which also keeps two clients
  from producing different payload bytes for an identical key. That exposed a
  wider gap: SshKeySecret, its codec and its merge had no direct unit tests at
  all. They have 25 now.

- The reason first given for that normalisation was false. It claimed SSH.NET
  rejects a passphrase supplied for an unprotected key; measured against a real
  sshd it ignores it and authenticates anyway. Corrected everywhere it was
  stated and recorded in docs/platform-flags.md. The same test file also closes
  a real hole: SshPrivateKeyCredential had never been exercised against a
  server, because the existing key test builds SSH.NET's auth method directly
  and bypasses the path a vault-held key actually takes.

Only one editor may be open at a time. Both sit in the same 340-pixel column as
Auto rows and their heights together exceed it at the window's minimum size, so
two open editors put the lower one's Save and Cancel past the bottom edge — the
same failure this window already shipped once with the setup screens. Expressed
as a state rule because that is the only form of it this repository can check:
nothing here loads a .axaml. The refusal keeps what was typed, since in the key
editor that is a pasted private key the user may have nowhere else.

The end-to-end slice now carries a key as well as a host, so both item types go
through the real API, the real PostgreSQL and the real crypto in one pass — the
three hand-kept mappings between enums that do not line up are the reason that
is worth doing rather than trusting the unit suites.

735 tests green, including the container-backed SSH and end-to-end suites. Zero
warnings, dotnet format clean.
This commit is contained in:
2026-07-29 20:27:23 +02:00
parent 586cb303d5
commit e3fd3e1728
26 changed files with 2804 additions and 505 deletions
+174 -61
View File
@@ -13,7 +13,7 @@ namespace DodoSSH.Client.Sync;
/// Deterministic, from the original id and the version of the tombstone that displaced it. That matters
/// because applying a pulled change is at-least-once: the cursor is saved after the changes are applied,
/// so a process that dies in between re-applies them on the next start. A random id would resurrect the
/// same host twice and leave the user with duplicates to sort out; this way the second attempt produces
/// same item twice and leave the user with duplicates to sort out; this way the second attempt produces
/// the same id and coalesces into the same outbox row.
/// <para>
/// Not a UUIDv7, and that is fine — the server treats item ids as opaque, and the time ordering a v7 id
@@ -47,6 +47,32 @@ internal static class ResurrectionId
}
}
/// <summary>
/// Reconciles one item type, with the secret type erased so the engine can hold a table of them.
/// </summary>
/// <remarks>
/// The engine never needs the concrete type — it dispatches on the entity type a change carries and lets
/// the reconciler do the rest — so this interface is what it stores. The two members are the two places
/// the push and pull paths need type-specific crypto.
/// </remarks>
internal interface IItemReconciler
{
/// <summary>Reconciles a remote change against the operation pending for the same item.</summary>
Task ReconcileAsync(
Guid vaultId,
SyncChange remote,
PendingOperation pending,
SyncReportBuilder report,
CancellationToken cancellationToken);
/// <summary>Re-seals a queued change as a create, for a server that says it has no such row.</summary>
/// <returns>Null on success, or the reason the change could not be re-offered.</returns>
Task<string?> ReofferAsCreateAsync(
Guid vaultId,
PendingOperation pending,
CancellationToken cancellationToken);
}
/// <summary>
/// Decides what happens when a remote change collides with an unpushed local one.
/// </summary>
@@ -54,7 +80,10 @@ internal static class ResurrectionId
/// <para>
/// Shared by the pull and the push paths, because both meet the same six situations and must answer them
/// identically — a pull that merged one way and a push that merged the other would make the outcome
/// depend on which side happened to notice first.
/// depend on which side happened to notice first. Shared across item types for the same reason: a host
/// and an SSH key meet those six situations in exactly the same way, and the only differences —
/// encoding, merge, plaintext columns, what to call the thing — arrive through
/// <see cref="IItemKind{TSecret}"/>.
/// </para>
/// <para>
/// <b>The governing rule is that nothing is discarded silently.</b> Where the two sides can be
@@ -64,20 +93,29 @@ internal static class ResurrectionId
/// reconstruct.
/// </para>
/// </remarks>
internal sealed class ItemReconciler(
ItemStore items,
/// <remarks>
/// Takes no <see cref="ItemStore"/>, which is worth noticing rather than reading as an omission: nothing
/// here writes the mirror. Reconciling only ever revises the outbox and records conflicts, and the
/// server's own version of an item is written by <see cref="ItemMirror"/> before this is called.
/// </remarks>
internal sealed class ItemReconciler<TSecret>(
IItemKind<TSecret> kind,
OutboxStore outbox,
ConflictStore conflicts,
VaultKeyring keyring)
VaultKeyring keyring) : IItemReconciler
where TSecret : class, IVaultSecret
{
/// <summary>Reconciles a remote change against the operation pending for the same item.</summary>
internal Task ReconcileAsync(
public Task ReconcileAsync(
Guid vaultId,
SyncChange remote,
PendingOperation pending,
SyncReportBuilder report,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(remote);
ArgumentNullException.ThrowIfNull(pending);
if (remote.Operation == SyncOperation.Delete)
{
return pending.Operation == SyncOperation.Delete
@@ -91,6 +129,49 @@ internal sealed class ItemReconciler(
: MergeAsync(vaultId, remote, pending, report, cancellationToken);
}
/// <summary>
/// Re-seals a queued change as a create, for a server that says it has no such row.
/// </summary>
/// <remarks>
/// The payload has to be re-sealed rather than re-sent: it was sealed at the version this client
/// predicted, and a create produces version 1, which the AAD binds.
/// </remarks>
/// <returns>Null on success, or the reason the change could not be re-offered.</returns>
public async Task<string?> ReofferAsCreateAsync(
Guid vaultId,
PendingOperation pending,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(pending);
if (!keyring.TryGet(vaultId, out var vaultKey, out var generation) || pending.Payload is null)
{
return "This item has no usable vault key.";
}
var local = kind.TryOpen(
pending.Payload,
vaultKey.Span,
pending.EntityId,
SyncVersions.NextVersion(pending.ExpectedVersion));
if (local is null)
{
return "The queued change could not be decrypted, so it could not be re-offered.";
}
await outbox.ReviseAsync(
pending.Sequence,
SyncOperation.Upsert,
expectedVersion: null,
kind.Seal(local.Secret, vaultKey.Span, pending.EntityId, generation, itemVersion: 1),
kind.Fields(local.Secret),
ancestor: null,
cancellationToken).ConfigureAwait(false);
return null;
}
/// <summary>
/// Reconciles a pending create that the server says already exists.
/// </summary>
@@ -98,7 +179,7 @@ internal sealed class ItemReconciler(
/// In practice this means an earlier push of the same create did land and its acknowledgement was
/// lost — a timeout, a dropped connection — after which the local row may also have been edited. The
/// resolution adopts the server's row as the base and re-offers the local content as an update, so
/// the newer local state wins and no duplicate host appears. A genuine id collision between two
/// the newer local state wins and no duplicate item appears. A genuine id collision between two
/// clients is the other reading, and is not achievable with UUIDv7; if it happened, the server's
/// values would be in the conflict log rather than gone.
/// </remarks>
@@ -117,11 +198,14 @@ internal sealed class ItemReconciler(
return;
}
var (local, remoteHost, vaultKey, generation) = opened.Value;
var (local, remoteSecret, vaultKey, generation) = opened.Value;
if (local == remoteHost)
// Through the comparer, not ==. Both secrets are records with value equality, but TSecret is a
// type parameter, so == would bind to reference equality at compile time and never be true —
// turning "our own create coming back" into a conflict record on every single pass.
if (EqualityComparer<TSecret>.Default.Equals(local, remoteSecret))
{
// Byte-for-byte the same host: this is our own create coming back. Nothing to do but stop
// Field for field the same item: this is our own create coming back. Nothing to do but stop
// trying to send it again.
await outbox.CompleteAsync(pending.Sequence, cancellationToken).ConfigureAwait(false);
return;
@@ -133,7 +217,7 @@ internal sealed class ItemReconciler(
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
kind.EntityType,
remote.EntityId,
ConflictKind.FieldOverridden,
ConflictDetails.Encode(
@@ -167,9 +251,9 @@ internal sealed class ItemReconciler(
return;
}
var (local, remoteHost, vaultKey, generation) = opened.Value;
var (local, remoteSecret, vaultKey, generation) = opened.Value;
var ancestor = HostCipher.TryOpen(
var ancestor = kind.TryOpen(
pending.Ancestor.Payload, vaultKey.Span, remote.EntityId, pending.Ancestor.Version);
if (ancestor is null)
@@ -182,17 +266,17 @@ internal sealed class ItemReconciler(
return;
}
var merged = HostSecretMerge.Merge(ancestor.Host, local, remoteHost);
var merged = kind.Merge(ancestor.Secret, local, remoteSecret);
await ReviseAsUpdateAsync(
vaultId, remote, pending, merged.Merged, vaultKey, generation, cancellationToken)
.ConfigureAwait(false);
if (merged.HasConflicts)
if (merged.Conflicts.Count > 0)
{
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
kind.EntityType,
remote.EntityId,
ConflictKind.FieldOverridden,
ConflictDetails.Encode(
@@ -211,7 +295,7 @@ internal sealed class ItemReconciler(
/// <remarks>
/// The tombstone is accepted — arguing with it would conflict for ever, since a delete beats a late
/// upsert on the server — and the local content is re-offered under a fresh id, labelled so the user
/// can see what happened. That is the whole of "never silently drop a host": the original goes, the
/// can see what happened. That is the whole of "never silently drop an item": the original goes, the
/// work does not.
/// </remarks>
private async Task ResurrectAsync(
@@ -230,7 +314,7 @@ internal sealed class ItemReconciler(
var local = pending.Payload is null
? null
: HostCipher.TryOpen(
: kind.TryOpen(
pending.Payload,
vaultKey.Span,
remote.EntityId,
@@ -244,7 +328,7 @@ internal sealed class ItemReconciler(
}
var restoredId = ResurrectionId.For(remote.EntityId, remote.Version);
var restored = local.Host with { Label = $"{local.Host.Label} (restored)" };
var restored = kind.Relabel(local.Secret, $"{local.Secret.Label} (restored)");
// Queued before the original is cleared, and that order matters. These are two separate
// transactions, so a process that dies between them has to fail in the direction that keeps the
@@ -254,12 +338,12 @@ internal sealed class ItemReconciler(
await outbox.QueueAsync(
new QueuedChange(
vaultId,
SyncEntityType.Host,
kind.EntityType,
restoredId,
SyncOperation.Upsert,
ExpectedVersion: null,
HostCipher.Seal(restored, vaultKey.Span, restoredId, generation, itemVersion: 1),
HostFields.From(restored),
kind.Seal(restored, vaultKey.Span, restoredId, generation, itemVersion: 1),
kind.Fields(restored),
Ancestor: null),
cancellationToken).ConfigureAwait(false);
@@ -268,11 +352,11 @@ internal sealed class ItemReconciler(
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
kind.EntityType,
remote.EntityId,
ConflictKind.RemoteDeleteResurrected,
ConflictDetails.Encode(
$"'{local.Host.Label}' was deleted elsewhere while this machine had unsaved changes. "
$"'{local.Secret.Label}' was deleted elsewhere while this machine had unsaved changes. "
+ $"The deletion stands and the local version was kept as '{restored.Label}'."),
cancellationToken).ConfigureAwait(false);
@@ -291,23 +375,23 @@ internal sealed class ItemReconciler(
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
kind.EntityType,
remote.EntityId,
ConflictKind.LocalDeleteOverridden,
ConflictDetails.Encode(
"This host was edited elsewhere after it was deleted here, so the deletion was not "
+ "applied. Delete it again if that is still what you want."),
$"This {kind.Noun} was edited elsewhere after it was deleted here, so the deletion was "
+ "not applied. Delete it again if that is still what you want."),
cancellationToken).ConfigureAwait(false);
report.DeletesAbandoned++;
}
/// <summary>Re-offers a host as an update against the server's current version.</summary>
/// <summary>Re-offers an item as an update against the server's current version.</summary>
private async Task ReviseAsUpdateAsync(
Guid vaultId,
SyncChange remote,
PendingOperation pending,
HostSecret host,
TSecret secret,
ReadOnlyMemory<byte> vaultKey,
uint generation,
CancellationToken cancellationToken)
@@ -318,14 +402,14 @@ internal sealed class ItemReconciler(
pending.Sequence,
SyncOperation.Upsert,
expectedVersion: remote.Version,
HostCipher.Seal(host, vaultKey.Span, remote.EntityId, generation, nextVersion),
HostFields.From(host),
kind.Seal(secret, vaultKey.Span, remote.EntityId, generation, nextVersion),
kind.Fields(secret),
new StoredAncestor(remote.Version, remote.Payload!, remote.PlaintextFields),
cancellationToken).ConfigureAwait(false);
}
/// <summary>Opens both sides of a collision, parking the operation if either will not open.</summary>
private async Task<(HostSecret Local, HostSecret Remote, ReadOnlyMemory<byte> VaultKey, uint Generation)?>
private async Task<(TSecret Local, TSecret Remote, ReadOnlyMemory<byte> VaultKey, uint Generation)?>
OpenPairAsync(
Guid vaultId,
SyncChange remote,
@@ -342,47 +426,63 @@ internal sealed class ItemReconciler(
return null;
}
var local = HostCipher.TryOpen(
var local = kind.TryOpen(
pending.Payload,
vaultKey.Span,
remote.EntityId,
SyncVersions.NextVersion(pending.ExpectedVersion));
var remoteHost = HostCipher.TryOpen(
var remoteSecret = kind.TryOpen(
remote.Payload, vaultKey.Span, remote.EntityId, remote.Version);
if (local is null || remoteHost is null)
if (local is null || remoteSecret is null)
{
await ParkAsync(vaultId, remote.EntityId, pending, report, cancellationToken)
.ConfigureAwait(false);
return null;
}
if (local.IsReadOnly || remoteHost.IsReadOnly)
if (local.IsReadOnly || remoteSecret.IsReadOnly)
{
// A newer client wrote fields this build cannot represent. Re-encoding would drop them, so
// the item is left alone until this client is updated.
await outbox.ParkAsync(
pending.Sequence,
"Written by a newer version of DodoSSH; update before editing this host.",
cancellationToken).ConfigureAwait(false);
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
remote.EntityId,
ConflictKind.TooNewToEdit,
ConflictDetails.Encode(
"This host was written by a newer version of DodoSSH. It can be read but not "
+ "merged here, because saving it would discard fields this version does not know "
+ "about."),
cancellationToken).ConfigureAwait(false);
report.Parked++;
await ParkAsTooNewAsync(vaultId, remote.EntityId, pending, report, cancellationToken)
.ConfigureAwait(false);
return null;
}
return (local.Host, remoteHost.Host, vaultKey, generation);
return (local.Secret, remoteSecret.Secret, vaultKey, generation);
}
/// <summary>
/// Leaves an item alone because a newer client wrote it.
/// </summary>
/// <remarks>
/// Re-encoding would drop fields this build cannot represent, so the item waits until this client is
/// updated. Parked rather than merged-and-hoped: the dropped field could be the one that matters.
/// </remarks>
private async Task ParkAsTooNewAsync(
Guid vaultId,
Guid entityId,
PendingOperation pending,
SyncReportBuilder report,
CancellationToken cancellationToken)
{
await outbox.ParkAsync(
pending.Sequence,
$"Written by a newer version of DodoSSH; update before editing this {kind.Noun}.",
cancellationToken).ConfigureAwait(false);
await conflicts.RecordAsync(
vaultId,
kind.EntityType,
entityId,
ConflictKind.TooNewToEdit,
ConflictDetails.Encode(
$"This {kind.Noun} was written by a newer version of DodoSSH. It can be read but not "
+ "merged here, because saving it would discard fields this version does not know "
+ "about."),
cancellationToken).ConfigureAwait(false);
report.Parked++;
}
private async Task ParkAsync(
@@ -394,16 +494,16 @@ internal sealed class ItemReconciler(
{
await outbox.ParkAsync(
pending.Sequence,
"The local or the server copy of this host could not be decrypted.",
$"The local or the server copy of this {kind.Noun} could not be decrypted.",
cancellationToken).ConfigureAwait(false);
await conflicts.RecordAsync(
vaultId,
SyncEntityType.Host,
kind.EntityType,
entityId,
ConflictKind.Undecryptable,
ConflictDetails.Encode(
"This host could not be decrypted, so the change made here could not be merged. "
$"This {kind.Noun} could not be decrypted, so the change made here could not be merged. "
+ "The vault key may have been rotated, or the stored payload may not belong to this "
+ "item."),
cancellationToken).ConfigureAwait(false);
@@ -411,9 +511,22 @@ internal sealed class ItemReconciler(
report.Unreadable++;
report.Parked++;
}
}
/// <summary>Writes the server's version of an item into the local mirror.</summary>
internal Task MirrorAsync(Guid vaultId, SyncChange change, CancellationToken cancellationToken) =>
/// <summary>Writes the server's version of an item into the local mirror.</summary>
/// <remarks>
/// Type-agnostic on purpose, and separate from the reconcilers for that reason: mirroring copies
/// ciphertext into a row and never decrypts, so there is nothing here for an item kind to decide. Making
/// it a method on a reconciler would have meant picking one arbitrarily, or having the engine look one up
/// for a change it can mirror without knowing anything about.
/// </remarks>
internal static class ItemMirror
{
internal static Task WriteAsync(
ItemStore items,
Guid vaultId,
SyncChange change,
CancellationToken cancellationToken) =>
items.SaveAsync(
new StoredItem(
vaultId,