Files
DodoSSH/tests/DodoSSH.Client.Sync.Tests/SyncHarness.cs
T
jaap-jan e24012b039 Sync credentials as a vault item type, and bind one to a host
Closes the largest remaining M1 gap in the data layer: a username and password
can live in the vault, sync between machines, and be named by a host as how it
authenticates. What is not here is the interface for creating one — see the end
of this message.

The third item type, and the first one that cost almost nothing to add. Server:
a VaultCredential row, an EF configuration, a migration, and a CredentialKind.
Client: a secret, a codec, a merge, a cipher, a kind, a repository facade and a
session property. No new reconciliation logic, no change to the sync engine, no
client cache migration. That was the whole point of the item-kind seam, and this
is the evidence it holds.

The narrowest type of the three on plaintext, and not for symmetry. A host has a
deliberate concession — the relay needs an address it can resolve. A key has a
fingerprint, public by nature, which this client still declines to send. A
password has no part that is safe to expose: not its length, not a hash, not a
hint. So CredentialKind refuses every plaintext field there is, hydrates none,
and the table has no column to put one in.

HostSecret.CredentialId is the password counterpart of SshKeyId, and the two are
mutually exclusive. SSH itself would happily try a key and fall back to a
password, but a host naming both leaves "how does this authenticate?" without a
single answer — the interface, the connect path and the user would each be free
to guess differently. TryValidate refuses it. One consequence was not
anticipated: "a full host" stops being a coherent idea, which is what broke
AFullHost_RoundTrips and is now written into that test.

The schema version became a ladder rather than a maximum: credential-bound is 3,
key-bound is 2, neither is still 1. Adding credentials therefore does not drag
every key-bound host in every vault onto a version that clients understanding
keys perfectly well would refuse to edit. A test pins exactly that, because it is
the property the whole content-dependent-version rule exists to provide, and the
obvious implementation would quietly lose it.

Two tests had become false and said so:

- Push_AnUnsupportedEntityType_IsInvalidNotAFailedBatch used Credential as its
  example of a type this server does not implement. It now asks the server's own
  registry what is still missing, so it cannot go stale again, and skips with a
  reason if that set ever empties.
- ThePullFilterNamesEveryTypeThisBuildSynchronises pinned the exact list, which
  is what it is for.

Also fixes ten nullable warnings — eight in SyncEndpointTests, two in a test file
added earlier today. Neither set was introduced here; both were invisible until
an unrelated change forced their project to recompile, which means the
zero-warning claims made earlier in this work only ever covered what happened to
be rebuilt.

777 tests green. Zero warnings, dotnet format clean.

Not done, and deliberately: the credential interface. The vault column is 340
pixels wide and already holds two lists and two editors, kept from clipping its
own buttons at the window's minimum height only by the one-editor-at-a-time rule
added earlier today. A third list and a third editor would recreate that defect
rather than avoid it, so the column needs a shape decision first. Credentials
sync; they cannot yet be created in the interface.
2026-07-29 21:09:08 +02:00

334 lines
12 KiB
C#

using DodoSSH.Client.Domain;
using DodoSSH.Client.Storage;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Sync.Tests;
/// <summary>
/// One machine: its own cache, its own outbox, its own view of the vault.
/// </summary>
/// <remarks>
/// A separate SQLite database per device, because the whole subject of these tests is two caches
/// diverging and being reconciled. Sharing one would make every conflict test vacuous.
/// </remarks>
internal sealed class SyncDevice : IDisposable
{
private readonly ClientCacheFactory factory;
private readonly MasterKey master;
private readonly LocalCacheProtector protector;
private SyncDevice(
string name,
ClientCacheFactory factory,
MasterKey master,
LocalCacheProtector protector,
VaultKeyring keyring,
FakeVaultServer server,
SyncOptions options)
{
Name = name;
this.factory = factory;
this.master = master;
this.protector = protector;
Keyring = keyring;
Items = new ItemStore(factory, protector);
Outbox = new OutboxStore(factory, protector, TimeProvider.System);
SyncState = new SyncStateStore(factory);
Conflicts = new ConflictStore(factory, protector, TimeProvider.System);
Hosts = new HostRepository(Items, Outbox, keyring);
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
Credentials = new CredentialRepository(Items, Outbox, keyring);
Engine = new SyncEngine(
server, Items, Outbox, SyncState, Conflicts, keyring, TimeProvider.System, options);
}
internal string Name { get; }
internal VaultKeyring Keyring { get; }
internal ItemStore Items { get; }
internal OutboxStore Outbox { get; }
internal SyncStateStore SyncState { get; }
internal ConflictStore Conflicts { get; }
internal HostRepository Hosts { get; }
internal SshKeyRepository SshKeys { get; }
internal CredentialRepository Credentials { get; }
internal SyncEngine Engine { get; }
internal static async Task<SyncDevice> CreateAsync(
string name,
UserSecretBundle bundle,
StoredVault vault,
FakeVaultServer server,
SyncOptions options)
{
var cache = ClientCacheFactory.ForMemory($"sync-{name}-{Guid.CreateVersion7():N}");
try
{
await cache.MigrateAsync(TestContext.Current.CancellationToken);
var derived = MasterKey.Derive(
$"passphrase-{name}", new byte[CryptoSpec.SaltSize], SyncHarness.CheapProfile);
// Opened through the real grant, so the keyring, the wrap and the AAD are all exercised.
var keyring = VaultKeyring.Open(bundle, [vault]);
return new SyncDevice(
name, cache, derived, LocalCacheProtector.From(derived), keyring, server, options);
}
catch
{
cache.Dispose();
throw;
}
}
internal Task<SyncReport> SyncAsync() =>
Engine.SyncAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal Task<ItemListing<HostSecret>> ListAsync() =>
Hosts.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal async Task<IReadOnlyList<HostSecret>> HostsSortedAsync()
{
var listing = await ListAsync();
return [.. listing.Items.Select(h => h.Secret).OrderBy(h => h.Label, StringComparer.Ordinal)];
}
internal async Task<VaultItem<HostSecret>> FindAsync(Guid entityId)
{
var listing = await ListAsync();
return listing.Items.SingleOrDefault(host => host.EntityId == entityId)
?? throw new InvalidOperationException($"{Name} cannot see host {entityId}.");
}
internal Task<Guid> CreateAsync(HostSecret host) =>
Hosts.CreateAsync(SyncHarness.VaultId, host, TestContext.Current.CancellationToken);
internal Task UpdateAsync(Guid entityId, HostSecret host) =>
Hosts.UpdateAsync(SyncHarness.VaultId, entityId, host, TestContext.Current.CancellationToken);
internal Task DeleteAsync(Guid entityId) =>
Hosts.DeleteAsync(SyncHarness.VaultId, entityId, TestContext.Current.CancellationToken);
// ---- The same four operations, on SSH keys ----
internal Task<ItemListing<SshKeySecret>> ListKeysAsync() =>
SshKeys.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal async Task<VaultItem<SshKeySecret>> FindKeyAsync(Guid entityId)
{
var listing = await ListKeysAsync();
return listing.Items.SingleOrDefault(key => key.EntityId == entityId)
?? throw new InvalidOperationException($"{Name} cannot see key {entityId}.");
}
internal Task<Guid> CreateKeyAsync(SshKeySecret key) =>
SshKeys.CreateAsync(SyncHarness.VaultId, key, TestContext.Current.CancellationToken);
internal Task UpdateKeyAsync(Guid entityId, SshKeySecret key) =>
SshKeys.UpdateAsync(SyncHarness.VaultId, entityId, key, TestContext.Current.CancellationToken);
internal Task DeleteKeyAsync(Guid entityId) =>
SshKeys.DeleteAsync(SyncHarness.VaultId, entityId, TestContext.Current.CancellationToken);
// ---- And again on credentials ----
internal Task<ItemListing<CredentialSecret>> ListCredentialsAsync() =>
Credentials.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal async Task<VaultItem<CredentialSecret>> FindCredentialAsync(Guid entityId)
{
var listing = await ListCredentialsAsync();
return listing.Items.SingleOrDefault(credential => credential.EntityId == entityId)
?? throw new InvalidOperationException($"{Name} cannot see credential {entityId}.");
}
internal Task<Guid> CreateCredentialAsync(CredentialSecret credential) =>
Credentials.CreateAsync(SyncHarness.VaultId, credential, TestContext.Current.CancellationToken);
internal Task UpdateCredentialAsync(Guid entityId, CredentialSecret credential) =>
Credentials.UpdateAsync(
SyncHarness.VaultId, entityId, credential, TestContext.Current.CancellationToken);
internal Task<IReadOnlyList<StoredConflict>> ConflictsAsync() =>
Conflicts.ListAsync(SyncHarness.VaultId, false, TestContext.Current.CancellationToken);
/// <inheritdoc />
public void Dispose()
{
Keyring.Dispose();
protector.Dispose();
master.Dispose();
factory.Dispose();
}
}
/// <summary>
/// One user, one vault, two machines and a server.
/// </summary>
/// <remarks>
/// Both devices share the identity bundle, which is what a single user on a laptop and a desktop
/// actually looks like: one enrolled key pair, one vault grant, two independent local caches. That is
/// also the cheapest realistic setup in which every conflict case can be produced.
/// </remarks>
internal sealed class SyncHarness : IDisposable
{
internal static readonly Argon2Profile CheapProfile =
Argon2Profile.FromStoredParameters(memoryKibibytes: 8 * 1024, passes: 1, parallelism: 1);
private readonly UserSecretBundle bundle;
private SyncHarness(UserSecretBundle bundle, FakeVaultServer server, SyncDevice first, SyncDevice second)
{
this.bundle = bundle;
Server = server;
First = first;
Second = second;
}
internal static Guid VaultId { get; } = Guid.Parse("0192f0c8-7777-7c3d-8e4f-5a6b7c8d9e0f");
internal FakeVaultServer Server { get; }
/// <summary>The laptop.</summary>
internal SyncDevice First { get; }
/// <summary>The desktop.</summary>
internal SyncDevice Second { get; }
internal static async Task<SyncHarness> CreateAsync(SyncOptions? options = null)
{
var effective = options ?? SyncOptions.Default;
var identity = UserSecretBundle.Create(DateTimeOffset.FromUnixTimeSeconds(1_700_000_000));
try
{
var vaultKey = VaultKeys.Create();
var wrapped = VaultKeys.WrapTo(vaultKey, identity.EncryptionPublicKey, VaultId, 1);
// The plaintext key is not retained: each device unwraps the grant itself, as it would after
// an ordinary unlock.
System.Security.Cryptography.CryptographicOperations.ZeroMemory(vaultKey);
var vault = new StoredVault(
VaultId, "Personal", IsPersonal: true, TeamId: null, KeyGeneration: 1,
Permissions: 31, wrapped, RekeyRequired: false);
var server = new FakeVaultServer(VaultId);
var first = await SyncDevice.CreateAsync("laptop", identity, vault, server, effective);
try
{
var second = await SyncDevice.CreateAsync("desktop", identity, vault, server, effective);
return new SyncHarness(identity, server, first, second);
}
catch
{
first.Dispose();
throw;
}
}
catch
{
identity.Dispose();
throw;
}
}
/// <summary>Brings both devices up to date, twice, so the result is a settled state.</summary>
/// <remarks>
/// Twice because one pass per device is not enough for a change made on one to be merged on the
/// other and then pushed back. Asserting on a settled state rather than on an intermediate one is
/// what makes "the two devices converge" a meaningful claim.
/// </remarks>
internal async Task SettleAsync()
{
for (var round = 0; round < 2; round++)
{
await First.SyncAsync();
await Second.SyncAsync();
}
}
/// <inheritdoc />
public void Dispose()
{
First.Dispose();
Second.Dispose();
bundle.Dispose();
}
// ---- Builders ----
internal static HostSecret Host(
string label,
string hostname = "db.internal",
int port = 22,
string? username = "deploy",
string? notes = null,
(string Name, string Value)[]? options = null,
bool relayEnabled = false) =>
new()
{
Label = label,
Hostname = hostname,
Port = port,
Username = username,
Notes = notes,
Options = options is null
? HostOptions.Empty
: HostOptions.Create(options.Select(o => new HostOption(o.Name, o.Value))),
RelayEnabled = relayEnabled,
};
/// <summary>
/// An SSH key whose material is a plausible shape but not a real key.
/// </summary>
/// <remarks>
/// Not a valid Ed25519 key, and deliberately so: nothing in the sync path parses the material, and a
/// real private key checked into a test repository is a real private key on the internet regardless of
/// what it was used for. <c>SshKeySecret.TryValidate</c> only requires the armour, and the tests that
/// need a key SSH.NET can actually load live in <c>DodoSSH.Client.Ssh.Tests</c> where one is generated.
/// </remarks>
/// <summary>A credential for the suites, varying only what a test is about.</summary>
internal static CredentialSecret Credential(
string label,
string password = "hunter2",
string? username = null,
string? notes = null) =>
new() { Label = label, Password = password, Username = username, Notes = notes };
internal static SshKeySecret Key(
string label,
string material = "deploy-key-material",
string? passphrase = null,
string? publicKey = null,
string? notes = null) =>
new()
{
Label = label,
PrivateKeyPem = $"-----BEGIN OPENSSH PRIVATE KEY-----\n{material}\n"
+ "-----END OPENSSH PRIVATE KEY-----\n",
Passphrase = passphrase,
PublicKey = publicKey,
Notes = notes,
};
}