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
@@ -1,5 +1,6 @@
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DodoSSH.Client.Api;
@@ -17,17 +18,17 @@ namespace DodoSSH.Client.App.ViewModels;
/// the flags the list has to show: an edit this machine has not pushed, a change the server refused, and
/// an item a newer client wrote that must not be re-encoded here.
/// </remarks>
internal sealed class HostRowViewModel(VaultHost host)
internal sealed class HostRowViewModel(VaultItem<HostSecret> host)
{
internal Guid EntityId => host.EntityId;
internal HostSecret Host => host.Host;
internal HostSecret Host => host.Secret;
internal string Label => host.Host.Label;
internal string Label => host.Secret.Label;
internal string Address => string.Create(
CultureInfo.InvariantCulture,
$"{host.Host.Username ?? ""}@{host.Host.Hostname}:{host.Host.Port}");
$"{host.Secret.Username ?? ""}@{host.Secret.Hostname}:{host.Secret.Port}");
internal bool HasUnsyncedChanges => host.HasUnsyncedChanges;
@@ -36,13 +37,65 @@ internal sealed class HostRowViewModel(VaultHost host)
internal bool IsReadOnly => host.IsReadOnly;
/// <summary>A short marker for the row, so the list says what it knows without a tooltip.</summary>
internal string Badge => host switch
internal string Badge => ItemBadge.For(host.IsBlocked, host.IsReadOnly, host.HasUnsyncedChanges);
}
/// <summary>One SSH key, as a row in the list.</summary>
/// <remarks>
/// <para>
/// Carries the decrypted <see cref="SshKeySecret"/>, as the host row carries its host, so opening the
/// editor or connecting with the key needs no second decryption.
/// </para>
/// <para>
/// <b>Nothing here exposes the private key to the view.</b> <see cref="Key"/> is what the editor and the
/// connect path read, and the members the XAML binds are the label, a description and a badge. That is not
/// a security boundary — the same object holds the material either way — but it does mean no template,
/// tooltip or accessibility surface can end up rendering a private key by being pointed at the obvious
/// property.
/// </para>
/// </remarks>
internal sealed class SshKeyRowViewModel(VaultItem<SshKeySecret> key)
{
internal Guid EntityId => key.EntityId;
internal SshKeySecret Key => key.Secret;
internal string Label => key.Secret.Label;
/// <summary>What the list shows under the name: what is known about the key, never the key.</summary>
internal string Description => key.Secret switch
{
{ IsBlocked: true } => "rejected",
{ IsReadOnly: true } => "newer version",
{ HasUnsyncedChanges: true } => "not synced",
_ => string.Empty,
{ Passphrase: not null, PublicKey: not null } => "passphrase · public half stored",
{ Passphrase: not null } => "passphrase · no public half",
{ PublicKey: not null } => "no passphrase · public half stored",
_ => "no passphrase · no public half",
};
internal bool HasUnsyncedChanges => key.HasUnsyncedChanges;
internal bool IsBlocked => key.IsBlocked;
internal bool IsReadOnly => key.IsReadOnly;
internal string Badge => ItemBadge.For(key.IsBlocked, key.IsReadOnly, key.HasUnsyncedChanges);
}
/// <summary>The one-word marker a row shows for its sync state.</summary>
/// <remarks>
/// Shared by both row types rather than written twice, because the three states mean the same thing for
/// every item type and a list where one kind said "not synced" and the other "unsynced" would read as two
/// different conditions.
/// </remarks>
internal static class ItemBadge
{
internal static string For(bool isBlocked, bool isReadOnly, bool hasUnsyncedChanges) =>
(isBlocked, isReadOnly, hasUnsyncedChanges) switch
{
(true, _, _) => "rejected",
(_, true, _) => "newer version",
(_, _, true) => "not synced",
_ => string.Empty,
};
}
/// <summary>A conflict, as a row.</summary>
@@ -88,10 +141,16 @@ internal sealed class ConflictRowViewModel(ConflictNotice notice)
/// A background pass is deliberately quieter than the button: see <see cref="AutoSyncAsync" />.
/// </para>
/// <para>
/// <b>Credentials are not in the vault yet.</b> <c>SyncEntityType.Credential</c> exists in the contract
/// but is not synced, so connecting still asks for a password each time. That is a real M1 limitation
/// rather than a design choice, and the interface says so rather than implying the vault holds more than
/// it does.
/// <b>Keys are in the vault; passwords are not.</b> An SSH key is a synced item, so it is stored once and
/// available on every machine. <c>SyncEntityType.Credential</c> exists in the contract and is still not
/// synced, so password authentication asks for the password each time. That is a real M1 limitation rather
/// 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.
/// </para>
/// </remarks>
internal sealed partial class VaultViewModel(
@@ -118,6 +177,9 @@ internal sealed partial class VaultViewModel(
/// <summary>The hosts to show, unpushed local state included.</summary>
internal ObservableCollection<HostRowViewModel> Hosts { get; } = [];
/// <summary>The SSH keys to show, unpushed local state included.</summary>
internal ObservableCollection<SshKeyRowViewModel> Keys { get; } = [];
/// <summary>Whatever the merge had to override and the user has not acknowledged.</summary>
internal ObservableCollection<ConflictRowViewModel> Conflicts { get; } = [];
@@ -127,6 +189,9 @@ internal sealed partial class VaultViewModel(
[ObservableProperty]
private HostRowViewModel? selectedHost;
[ObservableProperty]
private SshKeyRowViewModel? selectedKey;
[ObservableProperty]
private string status = string.Empty;
@@ -165,6 +230,37 @@ internal sealed partial class VaultViewModel(
/// <summary>The item being edited, or null when creating.</summary>
private Guid? editingEntityId;
// ---- The key editor ----
// A second set of editor state rather than a shared one. The two editors hold unrelated fields, and
// sharing them would mean a half-typed host reappearing inside a key editor.
[ObservableProperty]
private bool isEditingKey;
[ObservableProperty]
private string keyEditorLabel = string.Empty;
/// <remarks>
/// Bound to a text box the user pastes a private key into, so this holds key material for as long as
/// the editor is open, and <see cref="CancelKeyEdit" /> clears it. Neither that nor anything else here
/// can wipe it — see <c>SshKeySecret</c>, which explains why a .NET string is the honest choice for
/// this and what it does not buy.
/// </remarks>
[ObservableProperty]
private string keyEditorPrivateKey = string.Empty;
[ObservableProperty]
private string keyEditorPassphrase = string.Empty;
[ObservableProperty]
private string keyEditorPublicKey = string.Empty;
[ObservableProperty]
private string keyEditorNotes = string.Empty;
/// <summary>The key being edited, or null when creating.</summary>
private Guid? editingKeyId;
// ---- Connecting ----
/// <remarks>
@@ -173,6 +269,17 @@ 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;
[ObservableProperty]
private HostKeyPresentation? pendingHostKey;
@@ -202,9 +309,13 @@ internal sealed partial class VaultViewModel(
{
await ReloadAsync(cancellationToken).ConfigureAwait(true);
Status = Hosts.Count == 0
? "No hosts yet. Add one."
: $"{Hosts.Count} host(s) in {VaultName}.";
Status = (Hosts.Count, Keys.Count) switch
{
(0, 0) => "No hosts yet. Add one.",
(0, var keys) => $"No hosts yet, and {keys} key(s) in {VaultName}.",
(var hosts, 0) => $"{hosts} host(s) in {VaultName}.",
var (hosts, keys) => $"{hosts} host(s) and {keys} key(s) in {VaultName}.",
};
}
/// <summary>
@@ -217,6 +328,19 @@ internal sealed partial class VaultViewModel(
/// "the background pass is quiet" false on the one path that mattered.
/// </remarks>
private async Task ReloadAsync(CancellationToken cancellationToken)
{
var unreadable = await ReloadHostsAsync(cancellationToken).ConfigureAwait(true);
unreadable += await ReloadKeysAsync(cancellationToken).ConfigureAwait(true);
UnreadableItems = unreadable;
PendingChanges = await session.PendingChangeCountAsync(cancellationToken).ConfigureAwait(true);
await LoadConflictsAsync(cancellationToken).ConfigureAwait(true);
}
/// <returns>How many hosts would not decrypt.</returns>
private async Task<int> ReloadHostsAsync(CancellationToken cancellationToken)
{
var listing = await session.Hosts
.ListAsync(session.ActiveVaultId, cancellationToken)
@@ -226,7 +350,7 @@ internal sealed partial class VaultViewModel(
Hosts.Clear();
foreach (var host in listing.Hosts.OrderBy(host => host.Host.Label, StringComparer.CurrentCulture))
foreach (var host in listing.Items.OrderBy(host => host.Secret.Label, StringComparer.CurrentCulture))
{
Hosts.Add(new HostRowViewModel(host));
}
@@ -235,10 +359,33 @@ internal sealed partial class VaultViewModel(
// under the user.
SelectedHost = Hosts.FirstOrDefault(row => row.EntityId == selectedId) ?? Hosts.FirstOrDefault();
UnreadableItems = listing.Unreadable;
PendingChanges = await session.PendingChangeCountAsync(cancellationToken).ConfigureAwait(true);
return listing.Unreadable;
}
await LoadConflictsAsync(cancellationToken).ConfigureAwait(true);
/// <returns>How many keys would not decrypt.</returns>
/// <remarks>
/// Unlike the host list, the selection is <em>not</em> defaulted to the first row. A key selection is
/// what <see cref="UseKeyAuthentication" /> authenticates with, and quietly selecting one on load would
/// mean a connection made with a key the user never chose.
/// </remarks>
private async Task<int> ReloadKeysAsync(CancellationToken cancellationToken)
{
var listing = await session.SshKeys
.ListAsync(session.ActiveVaultId, cancellationToken)
.ConfigureAwait(true);
var selectedId = SelectedKey?.EntityId;
Keys.Clear();
foreach (var key in listing.Items.OrderBy(key => key.Secret.Label, StringComparer.CurrentCulture))
{
Keys.Add(new SshKeyRowViewModel(key));
}
SelectedKey = Keys.FirstOrDefault(row => row.EntityId == selectedId);
return listing.Unreadable;
}
/// <summary>Runs a synchronisation pass, if there is a server to talk to.</summary>
@@ -386,6 +533,11 @@ internal sealed partial class VaultViewModel(
[RelayCommand]
private void NewHost()
{
if (KeyEditorIsInTheWay())
{
return;
}
editingEntityId = null;
EditorLabel = string.Empty;
EditorHostname = string.Empty;
@@ -401,7 +553,7 @@ internal sealed partial class VaultViewModel(
[RelayCommand]
private void EditSelectedHost()
{
if (SelectedHost is not { } row)
if (SelectedHost is not { } row || KeyEditorIsInTheWay())
{
return;
}
@@ -505,6 +657,129 @@ internal sealed partial class VaultViewModel(
await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
}
/// <summary>Starts a new SSH key.</summary>
[RelayCommand]
private void NewKey()
{
if (HostEditorIsInTheWay())
{
return;
}
editingKeyId = null;
ClearKeyEditor();
IsEditingKey = true;
Status = "Adding an SSH key.";
}
/// <summary>Opens the selected key for editing.</summary>
/// <remarks>
/// The private key is loaded into the editor, which is the only way an edit can preserve it: the
/// codec has no notion of a partial update, so saving re-encodes every field.
/// </remarks>
[RelayCommand]
private void EditSelectedKey()
{
if (SelectedKey is not { } row || HostEditorIsInTheWay())
{
return;
}
if (row.IsReadOnly)
{
Status = "This key was written by a newer version of DodoSSH. Update before editing it.";
return;
}
editingKeyId = row.EntityId;
KeyEditorLabel = row.Key.Label;
KeyEditorPrivateKey = row.Key.PrivateKeyPem;
KeyEditorPassphrase = row.Key.Passphrase ?? string.Empty;
KeyEditorPublicKey = row.Key.PublicKey ?? string.Empty;
KeyEditorNotes = row.Key.Notes ?? string.Empty;
IsEditingKey = true;
Status = $"Editing {row.Label}.";
}
/// <summary>Abandons the key editor, clearing the material out of it.</summary>
[RelayCommand]
private void CancelKeyEdit()
{
IsEditingKey = false;
editingKeyId = null;
ClearKeyEditor();
Status = string.Empty;
}
/// <summary>Stores the key editor's contents, encrypted, and queues it for the server.</summary>
[RelayCommand]
private async Task SaveKeyAsync(CancellationToken cancellationToken)
{
var key = BuildKey();
if (!key.TryValidate(out var reason))
{
Status = reason;
return;
}
await RunAsync(
"Saving…",
async () =>
{
if (editingKeyId is { } entityId)
{
await session.SshKeys
.UpdateAsync(session.ActiveVaultId, entityId, key, cancellationToken)
.ConfigureAwait(true);
}
else
{
editingKeyId = await session.SshKeys
.CreateAsync(session.ActiveVaultId, key, cancellationToken)
.ConfigureAwait(true);
}
IsEditingKey = false;
ClearKeyEditor();
await ReloadAsync(cancellationToken).ConfigureAwait(true);
SelectedKey = Keys.FirstOrDefault(row => row.EntityId == editingKeyId);
editingKeyId = null;
Status = connection() is null
? $"Saved '{key.Label}'. It will sync when you are online."
: $"Saved '{key.Label}'.";
}).ConfigureAwait(true);
await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
}
/// <summary>Queues a tombstone for the selected key.</summary>
[RelayCommand]
private async Task DeleteKeyAsync(CancellationToken cancellationToken)
{
if (SelectedKey is not { } row)
{
return;
}
await RunAsync(
"Deleting…",
async () =>
{
await session.SshKeys
.DeleteAsync(session.ActiveVaultId, row.EntityId, cancellationToken)
.ConfigureAwait(true);
await ReloadAsync(cancellationToken).ConfigureAwait(true);
Status = $"Deleted '{row.Label}'.";
}).ConfigureAwait(true);
await AutoSyncAsync(cancellationToken).ConfigureAwait(true);
}
/// <summary>Opens a terminal on the selected host.</summary>
[RelayCommand]
private async Task ConnectAsync(CancellationToken cancellationToken)
@@ -521,6 +796,15 @@ internal sealed partial class VaultViewModel(
return;
}
if (UseKeyAuthentication && SelectedKey is null)
{
// 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.";
return;
}
PendingHostKey = null;
HostKeyMismatch = null;
@@ -617,7 +901,7 @@ internal sealed partial class VaultViewModel(
row.Host.Hostname,
row.Host.Port,
row.Host.Username!,
new SshPasswordCredential(ConnectPassword));
BuildCredential());
await workspace
.OpenSessionAsync(request, TerminalSize.Default, cancellationToken)
@@ -652,6 +936,30 @@ internal sealed partial class VaultViewModel(
}
}
/// <summary>
/// How the next connection authenticates.
/// </summary>
/// <remarks>
/// 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.
/// <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.
/// </para>
/// </remarks>
private SshCredential BuildCredential()
{
if (!UseKeyAuthentication || SelectedKey is not { } row)
{
return new SshPasswordCredential(ConnectPassword);
}
return new SshPrivateKeyCredential(
Encoding.UTF8.GetBytes(row.Key.PrivateKeyPem), row.Key.Passphrase);
}
private HostSecret BuildHost() =>
new()
{
@@ -663,6 +971,76 @@ internal sealed partial class VaultViewModel(
RelayEnabled = EditorRelayEnabled,
};
/// <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
/// <c>SshKeySecret.PrivateKeyPem</c> stores it verbatim. Everything else is trimmed, because a label
/// with a trailing space sorts oddly and reads as a different name.
/// </remarks>
private SshKeySecret BuildKey() =>
new()
{
Label = KeyEditorLabel.Trim(),
PrivateKeyPem = KeyEditorPrivateKey,
// Not trimmed and not emptied: leading or trailing spaces are legitimate in a passphrase, and
// the record turns an empty one into null on its own.
Passphrase = KeyEditorPassphrase,
PublicKey = string.IsNullOrWhiteSpace(KeyEditorPublicKey) ? null : KeyEditorPublicKey.Trim(),
Notes = string.IsNullOrWhiteSpace(KeyEditorNotes) ? null : KeyEditorNotes,
};
/// <summary>
/// Whether the key editor has to be dealt with before another one can open.
/// </summary>
/// <remarks>
/// <para>
/// Only one editor open at a time, and this is a layout constraint rather than a style rule. Both
/// editors sit in the same 340-pixel column as <c>Auto</c> rows, and their desired heights together
/// exceed the column at the window's minimum height — so opening both pushes the lower one's Save and
/// Cancel past the bottom edge, where they cannot be clicked. That is the same failure this window has
/// already shipped once, when the setup screens rendered sliced with their buttons unreachable, and it is
/// the failure that nothing in this repository can catch: no test loads a <c>.axaml</c>. Making it a
/// state rule instead of a sizing hope is what makes it testable at all.
/// </para>
/// <para>
/// Refused rather than resolved by closing the other editor, because closing it would silently discard
/// what was typed there — and in the key editor that is a pasted private key the user may have nowhere
/// else. One sentence and one click is the cheaper of the two.
/// </para>
/// </remarks>
private bool KeyEditorIsInTheWay()
{
if (!IsEditingKey)
{
return false;
}
Status = "Finish or cancel the SSH key you are editing first.";
return true;
}
/// <inheritdoc cref="KeyEditorIsInTheWay" />
private bool HostEditorIsInTheWay()
{
if (!IsEditing)
{
return false;
}
Status = "Finish or cancel the host you are editing first.";
return true;
}
private void ClearKeyEditor()
{
KeyEditorLabel = string.Empty;
KeyEditorPrivateKey = string.Empty;
KeyEditorPassphrase = string.Empty;
KeyEditorPublicKey = string.Empty;
KeyEditorNotes = string.Empty;
}
private async Task LoadConflictsAsync(CancellationToken cancellationToken)
{
var notices = await session.ReadConflictsAsync(cancellationToken).ConfigureAwait(true);
@@ -693,9 +1071,11 @@ internal sealed partial class VaultViewModel(
var notes = new List<string>();
// "item(s)", not "host(s)": a vault now holds keys as well, and a report that named the wrong kind
// would send someone looking through the wrong list for something that was not there.
if (report.Resurrected > 0)
{
notes.Add($"{report.Resurrected} host(s) deleted elsewhere were kept under a new name");
notes.Add($"{report.Resurrected} item(s) deleted elsewhere were kept under a new name");
}
if (report.DeletesAbandoned > 0)
+102 -5
View File
@@ -78,8 +78,21 @@
</Grid>
</Border>
<!-- Host list -->
<Grid Grid.Row="1" Grid.Column="0" RowDefinitions="*,Auto,Auto"
<!--
The vault column: hosts above, SSH keys below.
Two lists in one column rather than a TabControl. A TabControl is the tidier layout and it was not
chosen because of what the terminal does with the keyboard: MainWindow releases focus by calling
Focus() on HostList by name, and a tabbed version would put that target behind a tab selection. This
repository already has one measured finding of that shape — Focus() on a collapsed control is a
no-op and is not replayed when it is revealed, see the note on NativeWebView below — and whether an
unselected TabItem behaves the same way here is untested. Not worth finding out by shipping it, for
a layout preference.
The host list keeps the flexible row, so it is what grows with the window; the key section takes
what it needs and no more.
-->
<Grid Grid.Row="1" Grid.Column="0" RowDefinitions="*,Auto,Auto,Auto,Auto,Auto,Auto"
Background="#131722" IsVisible="{Binding IsUnlocked}">
<!-- Named because it is where keyboard focus lands when the user leaves the terminal. -->
@@ -138,6 +151,77 @@
<Button Content="Delete" Command="{Binding Vault.DeleteHostCommand}" />
</StackPanel>
<Border Grid.Row="3" Padding="8,6" Background="#10141d">
<TextBlock Text="SSH keys" Foreground="#9aa4b6" FontSize="11" FontWeight="SemiBold" />
</Border>
<!--
Bounded rather than flexible, and hidden while its editor is open. The key editor is the tallest
thing in this column — a private key needs a real text area — and at the window's minimum height
there is not room for both. Browsing the list and editing one of its rows are not things anyone
needs to do at the same moment.
-->
<ListBox Grid.Row="4" x:Name="KeyList" Margin="6" MaxHeight="170"
ItemsSource="{Binding Vault.Keys}"
SelectedItem="{Binding Vault.SelectedKey}"
Background="Transparent"
IsVisible="{Binding !Vault.IsEditingKey}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:SshKeyRowViewModel">
<StackPanel Spacing="2" Margin="2,4">
<StackPanel Orientation="Horizontal" Spacing="6">
<TextBlock Text="{Binding Label}" Foreground="#e6e9f0" FontWeight="SemiBold" />
<Border Background="#2b2410" CornerRadius="3" Padding="4,0"
IsVisible="{Binding Badge, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">
<TextBlock Text="{Binding Badge}" Foreground="#e8dcb0" FontSize="10"
VerticalAlignment="Center" />
</Border>
</StackPanel>
<!--
What is known about the key, never the key. Binding the material here would put a private
key into a list item's visual tree, where a tooltip or a screen reader could read it out.
-->
<TextBlock Text="{Binding Description}" Classes="hint" FontSize="11" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Border Grid.Row="5" Padding="10" Background="#171b24"
IsVisible="{Binding Vault.IsEditingKey}">
<StackPanel Spacing="6">
<TextBox Text="{Binding Vault.KeyEditorLabel}" PlaceholderText="name" />
<!--
Not a password box. The armour has to be visible to be pasted and checked — a masked
multi-line box makes "did the whole key arrive?" unanswerable — and the mistake this actually
prevents is pasting the .pub file, which SshKeySecret.TryValidate rejects by name.
-->
<TextBox Text="{Binding Vault.KeyEditorPrivateKey}"
PlaceholderText="-----BEGIN OPENSSH PRIVATE KEY-----"
AcceptsReturn="True" Height="96" TextWrapping="NoWrap"
FontFamily="ui-monospace,Consolas,monospace" FontSize="11" />
<TextBox Text="{Binding Vault.KeyEditorPassphrase}"
PlaceholderText="passphrase, if the key has one" PasswordChar="•" />
<TextBox Text="{Binding Vault.KeyEditorPublicKey}"
PlaceholderText="public half (optional)" FontSize="11" />
<TextBox Text="{Binding Vault.KeyEditorNotes}" PlaceholderText="notes" AcceptsReturn="True"
Height="48" TextWrapping="Wrap" />
<TextBlock Classes="hint" FontSize="11"
Text="The key and its passphrase are encrypted here and never reach the server in a form it can read. Storing both together is the point of a vault: on a disk the passphrase protects the key, and in here your vault passphrase protects both." />
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Content="Save" Command="{Binding Vault.SaveKeyCommand}" />
<Button Content="Cancel" Command="{Binding Vault.CancelKeyEditCommand}" />
</StackPanel>
</StackPanel>
</Border>
<StackPanel Grid.Row="6" Orientation="Horizontal" Spacing="6" Margin="8,4,8,8"
IsVisible="{Binding !Vault.IsEditingKey}">
<Button Content="Add key" Command="{Binding Vault.NewKeyCommand}" />
<Button Content="Edit" Command="{Binding Vault.EditSelectedKeyCommand}" />
<Button Content="Delete" Command="{Binding Vault.DeleteKeyCommand}" />
</StackPanel>
</Grid>
<!-- Terminal column -->
@@ -148,14 +232,27 @@
<!--
Typed per connection. SyncEntityType.Credential exists in the contract but is not synced
yet, so the vault genuinely does not hold this — saying so beats a password box that looks
like it should have been remembered.
like it should have been remembered. Disabled rather than hidden when a key is being used, so
it stays visible that a password is what the other choice means.
-->
<TextBox Text="{Binding Vault.ConnectPassword}" PlaceholderText="password (not stored yet)"
PasswordChar="•" Width="220" VerticalAlignment="Center" />
PasswordChar="•" Width="220" VerticalAlignment="Center"
IsEnabled="{Binding !Vault.UseKeyAuthentication}" />
<!--
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.
-->
<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}" />
<Button Content="Connect" Command="{Binding Vault.ConnectCommand}"
IsEnabled="{Binding !Vault.IsBusy}" VerticalAlignment="Center" />
<TextBlock Classes="hint" FontSize="11" VerticalAlignment="Center"
Text="Credentials are not in the vault yet." />
Text="Keys are in the vault; passwords are not yet." />
</StackPanel>
</Border>
+7 -7
View File
@@ -24,7 +24,7 @@ namespace DodoSSH.Client.Domain;
/// relies on to tell "unchanged" from "changed to the same thing" from "changed differently".
/// </para>
/// </remarks>
public sealed record HostSecret
public sealed record HostSecret : IVaultSecret
{
/// <summary>The default SSH port, used when a host does not say otherwise.</summary>
public const int DefaultPort = 22;
@@ -84,33 +84,33 @@ public sealed record HostSecret
/// would make the editor unusable. The sync layer validates before sealing, and the codec
/// validates on decode, which are the two points where an invalid host would become durable.
/// </remarks>
public bool TryValidate([NotNullWhen(false)] out string? error)
public bool TryValidate([NotNullWhen(false)] out string? reason)
{
if (string.IsNullOrWhiteSpace(Label))
{
error = "A host needs a name.";
reason = "A host needs a name.";
return false;
}
if (string.IsNullOrWhiteSpace(Hostname))
{
error = "A host needs a hostname or address.";
reason = "A host needs a hostname or address.";
return false;
}
if (Port is < 1 or > 65535)
{
error = $"Port must be between 1 and 65535, not {Port}.";
reason = $"Port must be between 1 and 65535, not {Port}.";
return false;
}
if (JumpHostIds.AsSpan().Contains(Guid.Empty))
{
error = "A jump chain cannot contain an empty host id.";
reason = "A jump chain cannot contain an empty host id.";
return false;
}
error = null;
reason = null;
return true;
}
}
+31 -8
View File
@@ -29,8 +29,10 @@ namespace DodoSSH.Client.Domain;
/// <c>MemoryStream</c> rather than a file, so there is no temporary key file to leak or forget.
/// </para>
/// </remarks>
public sealed record SshKeySecret
public sealed record SshKeySecret : IVaultSecret
{
private readonly string? passphrase;
/// <summary>What the user calls this key.</summary>
public required string Label { get; init; }
@@ -48,12 +50,33 @@ public sealed record SshKeySecret
/// The passphrase protecting the private key, when it has one.
/// </summary>
/// <remarks>
/// <para>
/// Kept with the key rather than typed per connection, which is the entire point of a vault: the
/// passphrase defends the key file on a disk, and inside a vault the key is not on a disk. Storing both
/// together means the vault passphrase is what protects them, which is the guarantee this product is
/// built to make. A user who wants the second factor can leave this null and be prompted.
/// </para>
/// <para>
/// <b>An empty string is normalised to null, so there is exactly one way to say "no passphrase".</b>
/// Two spellings of one state cost more than they look: two clients that agree about a key and disagree
/// only about which spelling they used would produce different payload bytes for an identical key and a
/// spurious field conflict out of the merge, and <c>Passphrase is not null</c> would stop being a
/// reliable answer to "is this key protected?" — which is what the interface reads to describe a key.
/// Normalising here rather than at each call site means every way one can arrive lands on the same
/// value: an editor whose box was left blank, a codec decoding another client's <c>""</c>, a merge
/// picking one side.
/// </para>
/// <para>
/// It is <em>not</em> a defence against SSH.NET, which was the original reason given here and turned out
/// to be false: a passphrase handed to <c>PrivateKeyFile</c> for a key that has none is ignored, not
/// rejected, and the connection succeeds. See docs/platform-flags.md.
/// </para>
/// </remarks>
public string? Passphrase { get; init; }
public string? Passphrase
{
get => passphrase;
init => passphrase = string.IsNullOrEmpty(value) ? null : value;
}
/// <summary>
/// The public half, in <c>authorized_keys</c> form, when it is known.
@@ -78,17 +101,17 @@ public sealed record SshKeySecret
/// produces a vault item that looks fine and fails at connection time with an authentication error that
/// says nothing about which file you chose.
/// </remarks>
public bool TryValidate([NotNullWhen(false)] out string? error)
public bool TryValidate([NotNullWhen(false)] out string? reason)
{
if (string.IsNullOrWhiteSpace(Label))
{
error = "A key needs a name.";
reason = "A key needs a name.";
return false;
}
if (string.IsNullOrWhiteSpace(PrivateKeyPem))
{
error = "A key needs its private key material.";
reason = "A key needs its private key material.";
return false;
}
@@ -97,17 +120,17 @@ public sealed record SshKeySecret
if (material.StartsWith("ssh-", StringComparison.Ordinal)
|| material.StartsWith("ecdsa-", StringComparison.Ordinal))
{
error = "That is a public key. Paste the private key — the file without the .pub extension.";
reason = "That is a public key. Paste the private key — the file without the .pub extension.";
return false;
}
if (!material.StartsWith("-----BEGIN", StringComparison.Ordinal))
{
error = "That does not look like a private key; it should begin with \"-----BEGIN\".";
reason = "That does not look like a private key; it should begin with \"-----BEGIN\".";
return false;
}
error = null;
reason = null;
return true;
}
}
+37
View File
@@ -0,0 +1,37 @@
using System.Diagnostics.CodeAnalysis;
namespace DodoSSH.Client.Domain;
/// <summary>
/// What every kind of decrypted vault item has in common.
/// </summary>
/// <remarks>
/// <para>
/// Two members, and both are here because the sync layer needs them for every item type it handles: a
/// name to put in a message to a person, and the check that must pass before the item is sealed.
/// Everything else about an item — how it is encoded, how two versions of it merge, which plaintext
/// columns the server is allowed to see — is per-type behaviour that lives in the sync layer's item
/// kinds rather than on the record. The split is not arbitrary: a label and a validity rule are
/// intrinsic to the thing, whereas how it is encrypted is a decision about how it is stored.
/// </para>
/// <para>
/// An interface rather than a base record, because the implementations share no field — a base record
/// would exist solely to declare two abstract members, and would put a type in the equality contract of
/// records that have nothing else in common. The server's <c>IVaultItem</c> is an interface for a
/// sharper reason (EF Core maps a visible base class as a TPH hierarchy) but reaches the same place.
/// </para>
/// </remarks>
public interface IVaultSecret
{
/// <summary>What the user calls this item. The only name it has anywhere.</summary>
string Label { get; }
/// <summary>Whether this is storable, and why not if it is not.</summary>
/// <remarks>
/// The out parameter is <c>reason</c> rather than the <c>error</c> every implementation used before
/// this interface existed, because CA1716 refuses a reserved word from another CLR language on an
/// interface member. Renamed at the implementations too: a parameter name that differs from the one it
/// implements is legal and reads as an oversight.
/// </remarks>
bool TryValidate([NotNullWhen(false)] out string? reason);
}
@@ -75,6 +75,7 @@ public sealed class VaultSession : IAsyncDisposable
Conflicts = new ConflictStore(caches, protector, clock);
Vault = new VaultStore(caches, clock);
Hosts = new HostRepository(Items, Outbox, keyring);
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
}
/// <summary>Who this session belongs to, and the material that unlocked it.</summary>
@@ -89,6 +90,13 @@ public sealed class VaultSession : IAsyncDisposable
/// <summary>Hosts, decrypted, with unpushed local changes laid over them.</summary>
public HostRepository Hosts { get; }
/// <summary>SSH keys, decrypted, with unpushed local changes laid over them.</summary>
/// <remarks>
/// Shares the item store and outbox with <see cref="Hosts"/>, so one synchronisation pass carries
/// both and a key edit made offline queues behind a host edit in the order the user made them.
/// </remarks>
public SshKeyRepository SshKeys { get; }
/// <summary>Vaults whose grant could not be opened, so their items cannot be read.</summary>
public IReadOnlyList<Guid> UnreadableVaults => keyring.Unopened;
+21 -280
View File
@@ -1,299 +1,40 @@
using DodoSSH.Client.Domain;
using DodoSSH.Client.Storage;
using DodoSSH.Contracts;
namespace DodoSSH.Client.Sync;
/// <summary>A host as the interface should show it.</summary>
/// <param name="EntityId">The item id.</param>
/// <param name="Host">The decrypted host.</param>
/// <param name="Version">
/// The server version this is based on. Zero for an item that has never been accepted.
/// </param>
/// <param name="HasUnsyncedChanges">
/// Whether this reflects a local edit the server has not accepted yet. Worth showing: it is the
/// difference between "saved" and "saved here".
/// </param>
/// <param name="IsBlocked">
/// Whether the pending change was refused and is waiting on a person, so it will not retry on its own.
/// </param>
/// <param name="IsReadOnly">
/// Whether this host was written by a newer client and so must not be edited here, because re-encoding
/// it would drop fields this build cannot represent.
/// </param>
public sealed record VaultHost(
Guid EntityId,
HostSecret Host,
int Version,
bool HasUnsyncedChanges,
bool IsBlocked,
bool IsReadOnly);
/// <summary>The hosts in a vault, and what could not be read.</summary>
/// <param name="Hosts">The readable hosts, newest change last.</param>
/// <param name="Unreadable">
/// How many items would not decrypt. Surfaced rather than swallowed: a non-zero count here after a
/// rekey is the signal that new grants are needed.
/// </param>
public sealed record HostListing(IReadOnlyList<VaultHost> Hosts, int Unreadable);
/// <summary>
/// Reading and writing hosts, as the interface sees them.
/// The hosts in a vault, decrypted, with unpushed local changes laid over them.
/// </summary>
/// <remarks>
/// <para>
/// The view is the mirror of the server's state with the outbox laid over it, which is what makes the
/// application feel local: an edit appears immediately and a delete disappears immediately, whether or
/// not the network is there. Nothing here talks to the server; the sync engine reconciles later.
/// </para>
/// <para>
/// Writes never touch the mirror. That separation is load-bearing — the mirror is the common ancestor a
/// three-way merge needs, and a repository that updated it on save would destroy the very state that
/// lets a conflict be merged instead of arbitrated.
/// </para>
/// A named facade over <see cref="VaultItemRepository{TSecret}"/>, which holds the logic and is shared
/// with <see cref="SshKeyRepository"/>. Two reasons it is a facade rather than the generic class itself:
/// callers read better for having asked for hosts by name, and the item kind that parameterises the
/// generic is internal to this assembly — exposing it would make the encoding and merge of every item
/// type part of the public surface for the sake of a constructor argument.
/// </remarks>
public sealed class HostRepository(ItemStore items, OutboxStore outbox, VaultKeyring keyring)
{
/// <summary>Reads every host the user should see in a vault.</summary>
public async Task<HostListing> ListAsync(Guid vaultId, CancellationToken cancellationToken)
{
if (!keyring.TryGet(vaultId, out var vaultKey, out _))
{
throw new VaultUnreadableException(vaultId);
}
private readonly VaultItemRepository<HostSecret> hosts =
new(HostKind.Instance, items, outbox, keyring);
var mirrored = await items
.ListAsync(vaultId, SyncEntityType.Host, includeDeleted: true, cancellationToken)
.ConfigureAwait(false);
/// <inheritdoc cref="VaultItemRepository{TSecret}.ListAsync" />
public Task<ItemListing<HostSecret>> ListAsync(Guid vaultId, CancellationToken cancellationToken) =>
hosts.ListAsync(vaultId, cancellationToken);
var pending = await outbox.ListAllAsync(vaultId, cancellationToken).ConfigureAwait(false);
/// <inheritdoc cref="VaultItemRepository{TSecret}.CreateAsync" />
public Task<Guid> CreateAsync(Guid vaultId, HostSecret host, CancellationToken cancellationToken) =>
hosts.CreateAsync(vaultId, host, cancellationToken);
var pendingByEntity = pending
.Where(operation => operation.EntityType == SyncEntityType.Host)
.ToDictionary(operation => operation.EntityId);
var hosts = new List<VaultHost>();
var unreadable = 0;
foreach (var item in mirrored)
{
if (pendingByEntity.Remove(item.EntityId, out var local))
{
AddPending(hosts, ref unreadable, vaultKey, local);
continue;
}
if (item.IsDeleted || item.Payload is null)
{
continue;
}
var opened = HostCipher.TryOpen(item.Payload, vaultKey.Span, item.EntityId, item.Version);
if (opened is null)
{
unreadable++;
continue;
}
hosts.Add(new VaultHost(
item.EntityId, opened.Host, item.Version, false, false, opened.IsReadOnly));
}
// Whatever is left has no mirror row yet: items created here and not yet accepted.
foreach (var local in pendingByEntity.Values)
{
AddPending(hosts, ref unreadable, vaultKey, local);
}
return new HostListing(hosts, unreadable);
}
/// <summary>
/// Adds a host, returning the id it was given.
/// </summary>
/// <remarks>
/// The id is generated here, not by the server, which is what lets a host be created with no network
/// at all — the point of the whole outbox. UUIDv7 so that ids sort by creation time, which keeps
/// index locality reasonable on the server side.
/// </remarks>
public async Task<Guid> CreateAsync(
Guid vaultId,
HostSecret host,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
Validate(host);
var (vaultKey, generation) = Key(vaultId);
var entityId = Guid.CreateVersion7();
await outbox.QueueAsync(
new QueuedChange(
vaultId,
SyncEntityType.Host,
entityId,
SyncOperation.Upsert,
ExpectedVersion: null,
HostCipher.Seal(host, vaultKey.Span, entityId, generation, itemVersion: 1),
HostFields.From(host),
Ancestor: null),
cancellationToken).ConfigureAwait(false);
return entityId;
}
/// <summary>
/// Replaces a host's contents.
/// </summary>
/// <remarks>
/// The base is taken from the pending operation when there is one, and from the mirror otherwise.
/// Reading it the other way round would seal the payload at a version that does not match the
/// <c>expectedVersion</c> the coalesced row keeps — and because the AAD binds the item version, the
/// result would encrypt cleanly and never decrypt again.
/// </remarks>
public async Task UpdateAsync(
/// <inheritdoc cref="VaultItemRepository{TSecret}.UpdateAsync" />
public Task UpdateAsync(
Guid vaultId,
Guid entityId,
HostSecret host,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(host);
Validate(host);
CancellationToken cancellationToken) =>
hosts.UpdateAsync(vaultId, entityId, host, cancellationToken);
var (vaultKey, generation) = Key(vaultId);
var pending = await outbox
.FindAsync(vaultId, SyncEntityType.Host, entityId, cancellationToken)
.ConfigureAwait(false);
var expectedVersion = pending is not null
? pending.ExpectedVersion
: await MirrorVersionAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
var ancestor = pending?.Ancestor
?? await MirrorAncestorAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
await outbox.QueueAsync(
new QueuedChange(
vaultId,
SyncEntityType.Host,
entityId,
SyncOperation.Upsert,
expectedVersion,
HostCipher.Seal(
host, vaultKey.Span, entityId, generation, SyncVersions.NextVersion(expectedVersion)),
HostFields.From(host),
ancestor),
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a host.
/// </summary>
/// <remarks>
/// Queued as a tombstone, never a local removal. An offline client that simply forgot the row would
/// be unable to tell the server anything, and the item would come back on the next pull.
/// </remarks>
public async Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken)
{
var pending = await outbox
.FindAsync(vaultId, SyncEntityType.Host, entityId, cancellationToken)
.ConfigureAwait(false);
var expectedVersion = pending is not null
? pending.ExpectedVersion
: await MirrorVersionAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
var ancestor = pending?.Ancestor
?? await MirrorAncestorAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
await outbox.QueueAsync(
new QueuedChange(
vaultId,
SyncEntityType.Host,
entityId,
SyncOperation.Delete,
expectedVersion,
Payload: null,
Fields: null,
ancestor),
cancellationToken).ConfigureAwait(false);
}
private static void Validate(HostSecret host)
{
if (!host.TryValidate(out var error))
{
throw new ArgumentException(error, nameof(host));
}
}
private static void AddPending(
List<VaultHost> hosts,
ref int unreadable,
ReadOnlyMemory<byte> vaultKey,
PendingOperation local)
{
if (local.Operation == SyncOperation.Delete)
{
// Gone as far as this machine is concerned, even before the server agrees.
return;
}
if (local.Payload is null)
{
unreadable++;
return;
}
var version = SyncVersions.NextVersion(local.ExpectedVersion);
var opened = HostCipher.TryOpen(local.Payload, vaultKey.Span, local.EntityId, version);
if (opened is null)
{
unreadable++;
return;
}
hosts.Add(new VaultHost(
local.EntityId,
opened.Host,
local.ExpectedVersion ?? 0,
HasUnsyncedChanges: true,
local.IsParked,
opened.IsReadOnly));
}
private (ReadOnlyMemory<byte> VaultKey, uint Generation) Key(Guid vaultId) =>
keyring.TryGet(vaultId, out var vaultKey, out var generation)
? (vaultKey, generation)
: throw new VaultUnreadableException(vaultId);
private async Task<int?> MirrorVersionAsync(
Guid vaultId,
Guid entityId,
CancellationToken cancellationToken)
{
var item = await items
.FindAsync(vaultId, SyncEntityType.Host, entityId, cancellationToken)
.ConfigureAwait(false);
// A null means the server has never seen this item, which is exactly what "create" is.
return item?.Version;
}
private async Task<StoredAncestor?> MirrorAncestorAsync(
Guid vaultId,
Guid entityId,
CancellationToken cancellationToken)
{
var item = await items
.FindAsync(vaultId, SyncEntityType.Host, entityId, cancellationToken)
.ConfigureAwait(false);
return item?.Payload is null
? null
: new StoredAncestor(item.Version, item.Payload, item.Fields);
}
/// <inheritdoc cref="VaultItemRepository{TSecret}.DeleteAsync" />
public Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken) =>
hosts.DeleteAsync(vaultId, entityId, cancellationToken);
}
+250
View File
@@ -0,0 +1,250 @@
using DodoSSH.Client.Domain;
using DodoSSH.Client.Storage;
using DodoSSH.Contracts;
namespace DodoSSH.Client.Sync;
/// <summary>A decrypted item, and whether this build may write it back.</summary>
/// <param name="Secret">The item.</param>
/// <param name="IsReadOnly">
/// Whether a newer client wrote it, in which case re-encoding it here would drop fields this build has
/// no concept of.
/// </param>
internal sealed record OpenedItem<TSecret>(TSecret Secret, bool IsReadOnly)
where TSecret : class, IVaultSecret;
/// <summary>A merged item, and everything that had to be overridden to produce it.</summary>
/// <param name="Merged">The item to store and push.</param>
/// <param name="Conflicts">Empty when the two sides were reconcilable field by field.</param>
internal sealed record MergedItem<TSecret>(
TSecret Merged,
IReadOnlyList<HostFieldConflict> Conflicts)
where TSecret : class, IVaultSecret;
/// <summary>
/// Everything about one item type that the shared sync path cannot know.
/// </summary>
/// <remarks>
/// <para>
/// The reconciler holds the six answers a collision can have — merge, adopt, resurrect, abandon, park,
/// refuse — and every one of them is identical for a host and for an SSH key. Only the encoding, the
/// merge and the plaintext columns differ, and those arrive through here. A second copy of the
/// reconciler per item type is the alternative, and it is not a real one: the file's whole premise is
/// that the pull and push paths must answer the same situation the same way, and two copies would drift
/// the moment one of them was fixed.
/// </para>
/// <para>
/// Generic, unlike the server's <c>IItemKind</c>, and for a reason that reverses there: the client
/// <em>does</em> need the concrete type. It merges two versions of an item field by field and hands the
/// result to a codec, so erasing the type would only move the downcasts inside the reconciler, where
/// they would be a cast per branch instead of none.
/// </para>
/// </remarks>
internal interface IItemKind<TSecret>
where TSecret : class, IVaultSecret
{
/// <summary>The type as the wire contract names it.</summary>
SyncEntityType EntityType { get; }
/// <summary>
/// What to call one of these when telling a person what happened to it.
/// </summary>
/// <remarks>
/// Lower case and singular, because every use is mid-sentence. This exists because the conflict log
/// is read by people: "this host could not be decrypted" is actively misleading when the item was a
/// private key, and a user who is told the wrong noun looks in the wrong place.
/// </remarks>
string Noun { get; }
/// <inheritdoc cref="HostCipher.TryOpen" />
OpenedItem<TSecret>? TryOpen(
EncryptedPayload payload,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
int itemVersion);
/// <inheritdoc cref="HostCipher.Seal" />
EncryptedPayload Seal(
TSecret secret,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
uint keyGeneration,
int itemVersion);
/// <summary>
/// The plaintext columns the server gets, or null when this type gives it nothing.
/// </summary>
/// <remarks>
/// Nullable rather than an all-defaults record, because the difference is visible on the wire and to
/// a reader: <c>SyncPlaintextFields</c> with nothing set still serialises <c>relayEnabled: false</c>,
/// which invites the belief that the type has a relay setting which happens to be off.
/// </remarks>
SyncPlaintextFields? Fields(TSecret secret);
/// <summary>Merges two divergent versions against the version they both started from.</summary>
MergedItem<TSecret> Merge(TSecret ancestor, TSecret local, TSecret remote);
/// <summary>The same item under a new name, for a resurrection.</summary>
TSecret Relabel(TSecret secret, string label);
}
/// <summary>
/// The item types this client synchronises.
/// </summary>
/// <remarks>
/// <para>
/// <b>One list, and the pull filter is derived from it.</b> The engine asks the server for exactly the
/// types in <see cref="Registry"/> and refuses to apply a change of any other type, so adding a kind
/// cannot leave the filter behind — which is the specific way this would otherwise break: an item type
/// that reads and writes perfectly in every unit test and is never once requested from the server.
/// </para>
/// <para>
/// A reconciler per type rather than one shared instance, because each closes the generic over its own
/// secret type. They are cheap — four fields and no state — and building them once per engine keeps the
/// per-change path a dictionary lookup.
/// </para>
/// </remarks>
internal static class ItemKinds
{
private static readonly (SyncEntityType Type, ReconcilerFactory Create)[] Registry =
[
(SyncEntityType.Host, static (outbox, conflicts, keyring) =>
new ItemReconciler<HostSecret>(HostKind.Instance, outbox, conflicts, keyring)),
(SyncEntityType.SshKey, static (outbox, conflicts, keyring) =>
new ItemReconciler<SshKeySecret>(SshKeyKind.Instance, outbox, conflicts, keyring)),
];
/// <summary>The types to ask the server for, in a fixed order.</summary>
internal static IReadOnlyList<SyncEntityType> SyncedTypes { get; } =
[.. Registry.Select(entry => entry.Type)];
private delegate IItemReconciler ReconcilerFactory(
OutboxStore outbox,
ConflictStore conflicts,
VaultKeyring keyring);
/// <summary>Builds one reconciler per synchronised type.</summary>
internal static Dictionary<SyncEntityType, IItemReconciler> Reconcilers(
OutboxStore outbox,
ConflictStore conflicts,
VaultKeyring keyring) =>
Registry.ToDictionary(
entry => entry.Type,
entry => entry.Create(outbox, conflicts, keyring));
}
/// <summary>Hosts.</summary>
internal sealed class HostKind : IItemKind<HostSecret>
{
internal static HostKind Instance { get; } = new();
/// <inheritdoc />
public SyncEntityType EntityType => SyncEntityType.Host;
/// <inheritdoc />
public string Noun => "host";
/// <inheritdoc />
public OpenedItem<HostSecret>? TryOpen(
EncryptedPayload payload,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
int itemVersion)
{
var document = HostCipher.TryOpen(payload, vaultKey, entityId, itemVersion);
return document is null ? null : new OpenedItem<HostSecret>(document.Host, document.IsReadOnly);
}
/// <inheritdoc />
public EncryptedPayload Seal(
HostSecret secret,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
uint keyGeneration,
int itemVersion) =>
HostCipher.Seal(secret, vaultKey, entityId, keyGeneration, itemVersion);
/// <inheritdoc />
public SyncPlaintextFields? Fields(HostSecret secret) => HostFields.From(secret);
/// <inheritdoc />
public MergedItem<HostSecret> Merge(HostSecret ancestor, HostSecret local, HostSecret remote)
{
var merged = HostSecretMerge.Merge(ancestor, local, remote);
return new MergedItem<HostSecret>(merged.Merged, merged.Conflicts);
}
/// <inheritdoc />
public HostSecret Relabel(HostSecret secret, string label)
{
ArgumentNullException.ThrowIfNull(secret);
return secret with { Label = label };
}
}
/// <summary>SSH keys.</summary>
internal sealed class SshKeyKind : IItemKind<SshKeySecret>
{
internal static SshKeyKind Instance { get; } = new();
/// <inheritdoc />
public SyncEntityType EntityType => SyncEntityType.SshKey;
/// <inheritdoc />
public string Noun => "SSH key";
/// <inheritdoc />
public OpenedItem<SshKeySecret>? TryOpen(
EncryptedPayload payload,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
int itemVersion)
{
var document = SshKeyCipher.TryOpen(payload, vaultKey, entityId, itemVersion);
return document is null ? null : new OpenedItem<SshKeySecret>(document.Key, document.IsReadOnly);
}
/// <inheritdoc />
public EncryptedPayload Seal(
SshKeySecret secret,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
uint keyGeneration,
int itemVersion) =>
SshKeyCipher.Seal(secret, vaultKey, entityId, keyGeneration, itemVersion);
/// <summary>
/// Nothing at all.
/// </summary>
/// <remarks>
/// The server has a <c>public_key_fingerprint</c> column and would accept one here, and this client
/// deliberately declines to fill it. A fingerprint is not a secret, but it is a stable identifier for
/// a key pair, and handing it over would let the operator tell which of their users hold the same key
/// and correlate one key across vaults — for a column nothing in the product reads. The design allows
/// itself exactly one plaintext concession, the relay address, and it is a concession because the
/// relay cannot work without it. This is not that. See ADR 0004.
/// </remarks>
/// <inheritdoc />
public SyncPlaintextFields? Fields(SshKeySecret secret) => null;
/// <inheritdoc />
public MergedItem<SshKeySecret> Merge(SshKeySecret ancestor, SshKeySecret local, SshKeySecret remote)
{
var merged = SshKeySecretMerge.Merge(ancestor, local, remote);
return new MergedItem<SshKeySecret>(merged.Merged, merged.Conflicts);
}
/// <inheritdoc />
public SshKeySecret Relabel(SshKeySecret secret, string label)
{
ArgumentNullException.ThrowIfNull(secret);
return secret with { Label = label };
}
}
+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,
@@ -0,0 +1,49 @@
using DodoSSH.Client.Domain;
using DodoSSH.Client.Storage;
namespace DodoSSH.Client.Sync;
/// <summary>
/// The SSH keys in a vault, decrypted, with unpushed local changes laid over them.
/// </summary>
/// <remarks>
/// <para>
/// Identical in shape to <see cref="HostRepository"/> and identical in implementation, because both are
/// facades over the same generic repository. The only thing that differs is the item kind, and with it
/// the cipher, the merge, and the fact that a key sends the server no plaintext columns at all.
/// </para>
/// <para>
/// <b>A key listed here has its private key in memory.</b> Listing is not a cheap metadata read: it
/// decrypts every key in the vault, so the caller holds the material for as long as it holds the listing.
/// That is the same bargain <see cref="HostRepository"/> makes for passwords in notes and the reason
/// <c>SshKeySecret</c> documents what managed strings do and do not give you — but it is worth stating
/// where the decryption actually happens, which is here.
/// </para>
/// </remarks>
public sealed class SshKeyRepository(ItemStore items, OutboxStore outbox, VaultKeyring keyring)
{
private readonly VaultItemRepository<SshKeySecret> keys =
new(SshKeyKind.Instance, items, outbox, keyring);
/// <inheritdoc cref="VaultItemRepository{TSecret}.ListAsync" />
public Task<ItemListing<SshKeySecret>> ListAsync(
Guid vaultId,
CancellationToken cancellationToken) =>
keys.ListAsync(vaultId, cancellationToken);
/// <inheritdoc cref="VaultItemRepository{TSecret}.CreateAsync" />
public Task<Guid> CreateAsync(Guid vaultId, SshKeySecret key, CancellationToken cancellationToken) =>
keys.CreateAsync(vaultId, key, cancellationToken);
/// <inheritdoc cref="VaultItemRepository{TSecret}.UpdateAsync" />
public Task UpdateAsync(
Guid vaultId,
Guid entityId,
SshKeySecret key,
CancellationToken cancellationToken) =>
keys.UpdateAsync(vaultId, entityId, key, cancellationToken);
/// <inheritdoc cref="VaultItemRepository{TSecret}.DeleteAsync" />
public Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken) =>
keys.DeleteAsync(vaultId, entityId, cancellationToken);
}
+43 -43
View File
@@ -33,7 +33,13 @@ public sealed class SyncEngine
private readonly VaultKeyring keyring;
private readonly TimeProvider clock;
private readonly SyncOptions options;
private readonly ItemReconciler reconciler;
/// <remarks>
/// One per synchronised item type, built once. The keys are also the pull filter — see
/// <see cref="ItemKinds"/> — so a type this engine cannot reconcile is never requested, and a type it
/// can reconcile cannot be left out of the request.
/// </remarks>
private readonly Dictionary<SyncEntityType, IItemReconciler> reconcilers;
/// <summary>Creates the engine.</summary>
public SyncEngine(
@@ -63,7 +69,7 @@ public sealed class SyncEngine
this.clock = clock;
this.options = options ?? SyncOptions.Default;
reconciler = new ItemReconciler(items, outbox, conflicts, keyring);
reconcilers = ItemKinds.Reconcilers(outbox, conflicts, keyring);
}
/// <summary>Runs a full pass over one vault.</summary>
@@ -127,7 +133,7 @@ public sealed class SyncEngine
{
var response = await api.SyncPullAsync(
vaultId,
new SyncPullRequest(state.Cursor, options.PullPageSize, [SyncEntityType.Host]),
new SyncPullRequest(state.Cursor, options.PullPageSize, ItemKinds.SyncedTypes),
cancellationToken).ConfigureAwait(false);
foreach (var change in response.Changes)
@@ -187,14 +193,16 @@ public sealed class SyncEngine
SyncReportBuilder report,
CancellationToken cancellationToken)
{
if (change.EntityType != SyncEntityType.Host)
if (!reconcilers.TryGetValue(change.EntityType, out var reconciler))
{
// Reserved in the contract but not yet syncable. Ignoring it keeps a newer server's extra
// entity types from breaking an older client's pull.
// Reserved in the contract but not yet syncable here. The pull filter already asks for only
// the types this build handles, so reaching this means a newer server sent something extra —
// and ignoring it keeps that from breaking an older client's pull. Not mirrored either: a row
// this build can never read is cache with no reader.
return;
}
await reconciler.MirrorAsync(vaultId, change, cancellationToken).ConfigureAwait(false);
await ItemMirror.WriteAsync(items, vaultId, change, cancellationToken).ConfigureAwait(false);
var pending = await outbox
.FindAsync(vaultId, change.EntityType, change.EntityId, cancellationToken)
@@ -394,14 +402,29 @@ public sealed class SyncEngine
return false;
}
if (!reconcilers.TryGetValue(operation.EntityType, out var reconciler))
{
// Only reachable if something queued a type this build does not synchronise, which the
// repositories cannot do. Parked rather than dropped, so the change is visible to a user
// instead of retried for ever against a path that cannot handle it.
await RejectAsync(
vaultId,
operation,
$"This version of DodoSSH cannot reconcile items of type {operation.EntityType}.",
report,
cancellationToken).ConfigureAwait(false);
return false;
}
if (result.ServerEntity is null)
{
// The version check failed but the server has no such row. Re-offer it as a create.
return await RetryAsCreateAsync(vaultId, operation, report, cancellationToken)
return await RetryAsCreateAsync(vaultId, reconciler, operation, report, cancellationToken)
.ConfigureAwait(false);
}
await reconciler.MirrorAsync(vaultId, result.ServerEntity, cancellationToken)
await ItemMirror.WriteAsync(items, vaultId, result.ServerEntity, cancellationToken)
.ConfigureAwait(false);
await reconciler
@@ -413,6 +436,7 @@ public sealed class SyncEngine
private async Task<bool> RetryAsCreateAsync(
Guid vaultId,
IItemReconciler reconciler,
PendingOperation operation,
SyncReportBuilder report,
CancellationToken cancellationToken)
@@ -424,44 +448,20 @@ public sealed class SyncEngine
return false;
}
if (!keyring.TryGet(vaultId, out var vaultKey, out var generation)
|| operation.Payload is null)
// Re-sealing needs the item's own cipher, so the reconciler does it. A reason back means the
// change can never be sent, not that it should be retried.
var failure = await reconciler
.ReofferAsCreateAsync(vaultId, operation, cancellationToken)
.ConfigureAwait(false);
if (failure is null)
{
await RejectAsync(
vaultId, operation, "This item has no usable vault key.", report, cancellationToken)
.ConfigureAwait(false);
return false;
return true;
}
var local = HostCipher.TryOpen(
operation.Payload,
vaultKey.Span,
operation.EntityId,
SyncVersions.NextVersion(operation.ExpectedVersion));
await RejectAsync(vaultId, operation, failure, report, cancellationToken).ConfigureAwait(false);
if (local is null)
{
await RejectAsync(
vaultId,
operation,
"The queued change could not be decrypted, so it could not be re-offered.",
report,
cancellationToken).ConfigureAwait(false);
return false;
}
// Re-sealed at version 1, because that is what the server assigns to a create and the AAD binds
// the version.
await outbox.ReviseAsync(
operation.Sequence,
SyncOperation.Upsert,
expectedVersion: null,
HostCipher.Seal(local.Host, vaultKey.Span, operation.EntityId, generation, itemVersion: 1),
HostFields.From(local.Host),
ancestor: null,
cancellationToken).ConfigureAwait(false);
return true;
return false;
}
/// <summary>Parks an operation the server will never accept, and says why.</summary>
@@ -0,0 +1,317 @@
using DodoSSH.Client.Domain;
using DodoSSH.Client.Storage;
using DodoSSH.Contracts;
namespace DodoSSH.Client.Sync;
/// <summary>One vault item as the interface should show it.</summary>
/// <param name="EntityId">The item id.</param>
/// <param name="Secret">The decrypted item.</param>
/// <param name="Version">
/// The server version this is based on. Zero for an item that has never been accepted.
/// </param>
/// <param name="HasUnsyncedChanges">
/// Whether this reflects a local edit the server has not accepted yet. Worth showing: it is the
/// difference between "saved" and "saved here".
/// </param>
/// <param name="IsBlocked">
/// Whether the pending change was refused and is waiting on a person, so it will not retry on its own.
/// </param>
/// <param name="IsReadOnly">
/// Whether this item was written by a newer client and so must not be edited here, because re-encoding
/// it would drop fields this build cannot represent.
/// </param>
public sealed record VaultItem<TSecret>(
Guid EntityId,
TSecret Secret,
int Version,
bool HasUnsyncedChanges,
bool IsBlocked,
bool IsReadOnly)
where TSecret : class, IVaultSecret;
/// <summary>The items of one kind in a vault, and what could not be read.</summary>
/// <param name="Items">The readable items.</param>
/// <param name="Unreadable">
/// How many items would not decrypt. Surfaced rather than swallowed: a non-zero count here after a
/// rekey is the signal that new grants are needed.
/// </param>
public sealed record ItemListing<TSecret>(IReadOnlyList<VaultItem<TSecret>> Items, int Unreadable)
where TSecret : class, IVaultSecret;
/// <summary>
/// Reading and writing one kind of vault item, as the interface sees them.
/// </summary>
/// <remarks>
/// <para>
/// The view is the mirror of the server's state with the outbox laid over it, which is what makes the
/// application feel local: an edit appears immediately and a delete disappears immediately, whether or
/// not the network is there. Nothing here talks to the server; the sync engine reconciles later.
/// </para>
/// <para>
/// Writes never touch the mirror. That separation is load-bearing — the mirror is the common ancestor a
/// three-way merge needs, and a repository that updated it on save would destroy the very state that
/// lets a conflict be merged instead of arbitrated.
/// </para>
/// <para>
/// Every read and write is scoped to <see cref="IItemKind{TSecret}.EntityType"/>, which is also what
/// keeps two kinds apart in storage: the item table is keyed on the type as well as the id, so a host and
/// a key could share an id and never see each other's rows.
/// </para>
/// </remarks>
internal sealed class VaultItemRepository<TSecret>(
IItemKind<TSecret> kind,
ItemStore items,
OutboxStore outbox,
VaultKeyring keyring)
where TSecret : class, IVaultSecret
{
/// <summary>Reads every item of this kind the user should see in a vault.</summary>
internal async Task<ItemListing<TSecret>> ListAsync(
Guid vaultId,
CancellationToken cancellationToken)
{
if (!keyring.TryGet(vaultId, out var vaultKey, out _))
{
throw new VaultUnreadableException(vaultId);
}
var mirrored = await items
.ListAsync(vaultId, kind.EntityType, includeDeleted: true, cancellationToken)
.ConfigureAwait(false);
var pending = await outbox.ListAllAsync(vaultId, cancellationToken).ConfigureAwait(false);
var pendingByEntity = pending
.Where(operation => operation.EntityType == kind.EntityType)
.ToDictionary(operation => operation.EntityId);
var listed = new List<VaultItem<TSecret>>();
var unreadable = 0;
foreach (var item in mirrored)
{
if (pendingByEntity.Remove(item.EntityId, out var local))
{
AddPending(listed, ref unreadable, vaultKey, local);
continue;
}
if (item.IsDeleted || item.Payload is null)
{
continue;
}
var opened = kind.TryOpen(item.Payload, vaultKey.Span, item.EntityId, item.Version);
if (opened is null)
{
unreadable++;
continue;
}
listed.Add(new VaultItem<TSecret>(
item.EntityId, opened.Secret, item.Version, false, false, opened.IsReadOnly));
}
// Whatever is left has no mirror row yet: items created here and not yet accepted.
foreach (var local in pendingByEntity.Values)
{
AddPending(listed, ref unreadable, vaultKey, local);
}
return new ItemListing<TSecret>(listed, unreadable);
}
/// <summary>
/// Adds an item, returning the id it was given.
/// </summary>
/// <remarks>
/// The id is generated here, not by the server, which is what lets an item be created with no network
/// at all — the point of the whole outbox. UUIDv7 so that ids sort by creation time, which keeps
/// index locality reasonable on the server side.
/// </remarks>
internal async Task<Guid> CreateAsync(
Guid vaultId,
TSecret secret,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(secret);
Validate(secret);
var (vaultKey, generation) = Key(vaultId);
var entityId = Guid.CreateVersion7();
await outbox.QueueAsync(
new QueuedChange(
vaultId,
kind.EntityType,
entityId,
SyncOperation.Upsert,
ExpectedVersion: null,
kind.Seal(secret, vaultKey.Span, entityId, generation, itemVersion: 1),
kind.Fields(secret),
Ancestor: null),
cancellationToken).ConfigureAwait(false);
return entityId;
}
/// <summary>
/// Replaces an item's contents.
/// </summary>
/// <remarks>
/// The base is taken from the pending operation when there is one, and from the mirror otherwise.
/// Reading it the other way round would seal the payload at a version that does not match the
/// <c>expectedVersion</c> the coalesced row keeps — and because the AAD binds the item version, the
/// result would encrypt cleanly and never decrypt again.
/// </remarks>
internal async Task UpdateAsync(
Guid vaultId,
Guid entityId,
TSecret secret,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(secret);
Validate(secret);
var (vaultKey, generation) = Key(vaultId);
var pending = await outbox
.FindAsync(vaultId, kind.EntityType, entityId, cancellationToken)
.ConfigureAwait(false);
var expectedVersion = pending is not null
? pending.ExpectedVersion
: await MirrorVersionAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
var ancestor = pending?.Ancestor
?? await MirrorAncestorAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
await outbox.QueueAsync(
new QueuedChange(
vaultId,
kind.EntityType,
entityId,
SyncOperation.Upsert,
expectedVersion,
kind.Seal(
secret,
vaultKey.Span,
entityId,
generation,
SyncVersions.NextVersion(expectedVersion)),
kind.Fields(secret),
ancestor),
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an item.
/// </summary>
/// <remarks>
/// Queued as a tombstone, never a local removal. An offline client that simply forgot the row would
/// be unable to tell the server anything, and the item would come back on the next pull.
/// </remarks>
internal async Task DeleteAsync(Guid vaultId, Guid entityId, CancellationToken cancellationToken)
{
var pending = await outbox
.FindAsync(vaultId, kind.EntityType, entityId, cancellationToken)
.ConfigureAwait(false);
var expectedVersion = pending is not null
? pending.ExpectedVersion
: await MirrorVersionAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
var ancestor = pending?.Ancestor
?? await MirrorAncestorAsync(vaultId, entityId, cancellationToken).ConfigureAwait(false);
await outbox.QueueAsync(
new QueuedChange(
vaultId,
kind.EntityType,
entityId,
SyncOperation.Delete,
expectedVersion,
Payload: null,
Fields: null,
ancestor),
cancellationToken).ConfigureAwait(false);
}
private static void Validate(TSecret secret)
{
if (!secret.TryValidate(out var error))
{
throw new ArgumentException(error, nameof(secret));
}
}
private void AddPending(
List<VaultItem<TSecret>> listed,
ref int unreadable,
ReadOnlyMemory<byte> vaultKey,
PendingOperation local)
{
if (local.Operation == SyncOperation.Delete)
{
// Gone as far as this machine is concerned, even before the server agrees.
return;
}
if (local.Payload is null)
{
unreadable++;
return;
}
var version = SyncVersions.NextVersion(local.ExpectedVersion);
var opened = kind.TryOpen(local.Payload, vaultKey.Span, local.EntityId, version);
if (opened is null)
{
unreadable++;
return;
}
listed.Add(new VaultItem<TSecret>(
local.EntityId,
opened.Secret,
local.ExpectedVersion ?? 0,
HasUnsyncedChanges: true,
local.IsParked,
opened.IsReadOnly));
}
private (ReadOnlyMemory<byte> VaultKey, uint Generation) Key(Guid vaultId) =>
keyring.TryGet(vaultId, out var vaultKey, out var generation)
? (vaultKey, generation)
: throw new VaultUnreadableException(vaultId);
private async Task<int?> MirrorVersionAsync(
Guid vaultId,
Guid entityId,
CancellationToken cancellationToken)
{
var item = await items
.FindAsync(vaultId, kind.EntityType, entityId, cancellationToken)
.ConfigureAwait(false);
// A null means the server has never seen this item, which is exactly what "create" is.
return item?.Version;
}
private async Task<StoredAncestor?> MirrorAncestorAsync(
Guid vaultId,
Guid entityId,
CancellationToken cancellationToken)
{
var item = await items
.FindAsync(vaultId, kind.EntityType, entityId, cancellationToken)
.ConfigureAwait(false);
return item?.Payload is null
? null
: new StoredAncestor(item.Version, item.Payload, item.Fields);
}
}