Add the encrypted local cache and the sync client

Three new client projects, and the wire-contract fix they needed.

DodoSSH.Client.Domain holds the decrypted item model and the three-way
merge, with no I/O at all — so the suite that decides whether a
credential can be lost runs in milliseconds with nothing to mock.
Scalars defer to the server on a genuine clash so every replica resolves
the same triple identically and two clients cannot ping-pong; directives
merge per name so two people each adding one both keep theirs; the jump
chain merges as a whole value because its order is the route. Whatever
loses is returned rather than dropped.

DodoSSH.Client.Storage is EF Core on SQLite, no SQLCipher: the rows are
already ciphertext, so an encrypted file would protect protected bytes
at the cost of a native dependency. It keeps the server's state and the
outbox in separate tables, which is what preserves the common ancestor a
merge needs. One pending operation per item, enforced by a unique index.

DodoSSH.Client.Sync is the pull/apply/push loop. Pulling never decrypts
— a change with no local work pending is plumbed as ciphertext — so a
first sync of thousands of items does not run twice as many AEAD
operations for nothing.

Contracts: EncryptedPayload gains WrappedDataKey and DataKeyId. The
specification has required a per-item data key since crypto.md §3, the
columns have existed since the first migration and DshAad.ItemPayload
binds the id, but this record had nowhere to put either — so a
spec-compliant item could not be transmitted at all. Found by writing
the client that has to produce one. Also closes a hole in
AadResourceType, which had no value for the HostTag and HostCredential
that SyncEntityType has always listed.

Four bugs the tests found, not review:

- SQLite refuses to order or compare its own DateTimeOffset mapping, and
  throws at execution rather than model build. Collecting tombstones and
  listing conflicts are both that shape, so this was a crash waiting for
  the first user with a deleted host. Timestamps are integers now, by
  convention so a later field cannot be the one left unconverted.
- SQLitePCLRaw 2.1.11, which EF resolves, is covered by
  GHSA-2m69-gcr7-jv3q. Pinned forward as a family.
- Resurrecting content from a remote deletion cleared the original
  before queueing the copy. Two transactions, so a crash between them
  lost the work; reversed, and the rescued id is derived from the
  tombstone so a replay coalesces instead of duplicating.
- Several equality assertions went through Shouldly's ShouldBe, which
  compares IEnumerable element-wise and so tested nothing about the
  Equals these types exist to provide. Corrected; the falsification that
  caught it went from 2 failures to 6.

The push response's cursor is deliberately ignored. It sits after this
client's own writes, so adopting it skips anything another client
committed at a lower sequence in the window between a pull and a push —
permanently. Re-reading one's own writes is idempotent and costs a page.
The Contracts doc that invited the shortcut now says so.

593 tests, up from 448. The delete-versus-edit rules, the ancestor
retention, the fresh operation id on coalesce and the cursor safeguard
were each verified by breaking them and watching the right test fail.
This commit is contained in:
2026-07-29 10:27:37 +02:00
parent a878c2b6bb
commit 8d2416a602
72 changed files with 11313 additions and 30 deletions
+176
View File
@@ -0,0 +1,176 @@
using System.Security.Cryptography;
using DodoSSH.Client.Domain;
using DodoSSH.Contracts;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Sync;
/// <summary>
/// Turns a host into an item payload and back.
/// </summary>
/// <remarks>
/// <para>
/// Every operation binds to the item's identity, its key generation <em>and</em> its version, because
/// that is what <c>DshAad.ItemPayload</c> requires. The version part has a consequence worth stating
/// plainly: a payload must be sealed at the version the server will assign, not the version it is
/// replacing. See <see cref="SyncVersions"/>.
/// </para>
/// <para>
/// The data key is fresh per call and is zeroed before returning, as is the encoded plaintext. Neither
/// is ever handed to a caller: a data key that escaped this class would be a data key some other layer
/// could forget to clear.
/// </para>
/// </remarks>
public static class HostCipher
{
private const CryptoSpec.AadResourceType Resource = CryptoSpec.AadResourceType.Host;
/// <summary>
/// Encrypts a host.
/// </summary>
/// <param name="host">The host. Must be valid for storage.</param>
/// <param name="vaultKey">The vault key, which the data key is wrapped under.</param>
/// <param name="entityId">The item id, which the AAD binds.</param>
/// <param name="keyGeneration">The vault's current key generation.</param>
/// <param name="itemVersion">
/// The version this payload will hold once the server accepts it — one more than the version being
/// replaced. Sealing at the version being replaced would produce a payload that authenticates
/// against a row that no longer exists, and the item would read as corrupt from then on.
/// </param>
public static EncryptedPayload Seal(
HostSecret host,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
uint keyGeneration,
int itemVersion)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentOutOfRangeException.ThrowIfLessThan(itemVersion, 1);
var plaintext = HostSecretCodec.Encode(host);
var dataKey = ItemKeys.CreateDataKey();
try
{
var dataKeyId = Guid.CreateVersion7();
var wrappedDataKey = ItemKeys.WrapDataKey(
dataKey, vaultKey, Resource, entityId, keyGeneration, (uint)itemVersion);
var envelope = ItemKeys.SealPayload(
dataKey, plaintext, Resource, entityId, dataKeyId, keyGeneration, (uint)itemVersion);
return new EncryptedPayload(
envelope, wrappedDataKey, dataKeyId, keyGeneration, CryptoSpec.CurrentAadVersion);
}
finally
{
CryptographicOperations.ZeroMemory(dataKey);
CryptographicOperations.ZeroMemory(plaintext);
}
}
/// <summary>
/// Decrypts a host.
/// </summary>
/// <returns>
/// The host and the schema version it was written at, or <see langword="null"/> if the payload does
/// not belong to this item, version or generation, or does not parse.
/// <para>
/// A null is a meaningful outcome, not an error to be thrown past. It is what a server relocating
/// ciphertext between rows looks like from here, and it is also what an ordinary rekey looks like
/// before new grants arrive. The caller distinguishes them by comparing generations; either way one
/// unreadable item must not abort a sync pass and strand every change behind it.
/// </para>
/// </returns>
public static HostSecretDocument? TryOpen(
EncryptedPayload payload,
ReadOnlySpan<byte> vaultKey,
Guid entityId,
int itemVersion)
{
ArgumentNullException.ThrowIfNull(payload);
if (itemVersion < 1 || payload.WrappedDataKey.Length == 0)
{
return null;
}
var dataKey = ItemKeys.TryUnwrapDataKey(
vaultKey,
payload.WrappedDataKey,
Resource,
entityId,
payload.KeyGeneration,
(uint)itemVersion);
if (dataKey is null)
{
return null;
}
try
{
var plaintext = ItemKeys.TryOpenPayload(
dataKey,
payload.Envelope,
Resource,
entityId,
payload.DataKeyId,
payload.KeyGeneration,
(uint)itemVersion);
if (plaintext is null)
{
return null;
}
try
{
return HostSecretCodec.TryDecode(plaintext, out var document) ? document : null;
}
finally
{
CryptographicOperations.ZeroMemory(plaintext);
}
}
finally
{
CryptographicOperations.ZeroMemory(dataKey);
}
}
}
/// <summary>
/// The one place that decides which item version a payload is sealed at.
/// </summary>
/// <remarks>
/// The payload's AAD binds the item version, so the sealing side has to predict what the server will
/// assign. That prediction is safe because it is checked: the server applies an upsert only when
/// <c>expectedVersion</c> matches, and then increments by exactly one. A mismatch is a conflict, not a
/// silently mis-sealed row. Both the sealing and the opening sides go through here, so they cannot
/// drift — the failure if they did would be an item that encrypts fine and never decrypts again.
/// </remarks>
internal static class SyncVersions
{
/// <summary>The version an accepted upsert will produce.</summary>
/// <param name="expectedVersion">The version being replaced, or null for a create.</param>
internal static int NextVersion(int? expectedVersion) => (expectedVersion ?? 0) + 1;
}
/// <summary>
/// Derives the plaintext columns the server needs from a host.
/// </summary>
/// <remarks>
/// The single point at which a hostname can leave the encrypted payload, which is the whole reason it
/// is a function rather than something each call site assembles. The address is emitted only when the
/// user has turned the relay on for that host; with relay off, the server learns nothing but that an
/// item exists. See ADR 0004 for why the relay cannot work any other way.
/// </remarks>
internal static class HostFields
{
internal static SyncPlaintextFields From(HostSecret host) =>
host.RelayEnabled
? new SyncPlaintextFields(RelayEnabled: true, Hostname: host.Hostname, Port: host.Port)
: new SyncPlaintextFields();
}