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:
jaap-jan committed 2026-07-29 10:27:37 +02:00
1 parent a878c2b6bb
commit 8d2416a602
72 files changed
+11313 -30

No files matched your search

@@ -0,0 +1,122 @@
using System.Security.Cryptography;
using DodoSSH.Contracts;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Storage;
/// <summary>
/// Seals the few things the local cache holds that are not already ciphertext.
/// </summary>
/// <remarks>
/// <para>
/// The cache stores item payloads exactly as the server sent them, so they need no further
/// protection. Two things do: the plaintext columns the server needs — a relay-enabled host's
/// address, chiefly — and the values a merge overrode, which are decrypted vault content by
/// definition. Both go through here.
/// </para>
/// <para>
/// <b>What this is and is not worth.</b> The key derives from the master key, so it exists only while
/// the vault is unlocked and is never written anywhere. That makes a stolen laptop, a stray backup or
/// a synced-to-cloud application folder yield nothing — which is the threat this addresses. It does
/// <em>not</em> defend against a process running as the same user: that process can read this
/// process's memory, and no on-disk measure changes it. docs/crypto.md §10 says the same about a
/// compromised endpoint, and this layer does not pretend otherwise.
/// </para>
/// <para>
/// Every record is bound to its own row, so a record cannot be moved to a different row of the same
/// cache. For a relay address that is not academic: two swapped rows would aim one host's connection
/// at another host's address.
/// </para>
/// </remarks>
public sealed class LocalCacheProtector : IDisposable
{
private readonly byte[] key = new byte[CryptoSpec.SymmetricKeySize];
private bool disposed;
private LocalCacheProtector(MasterKey master) => master.DeriveLocalCacheKey(key);
/// <summary>
/// Derives the cache key from an unlocked master key.
/// </summary>
/// <remarks>
/// The master key is not retained. Only the subkey is, and it is domain-separated by its HKDF
/// label from the key that wraps the secret bundle — the two live in very different threat models
/// and must not be the same bytes.
/// </remarks>
public static LocalCacheProtector From(MasterKey master)
{
ArgumentNullException.ThrowIfNull(master);
return new LocalCacheProtector(master);
}
/// <summary>Seals a cache record, binding it to the row that will hold it.</summary>
public byte[] Protect(
CryptoSpec.AadResourceType resourceType,
Guid recordId,
ReadOnlySpan<byte> plaintext)
{
ObjectDisposedException.ThrowIf(disposed, this);
return DshCrypto.Seal(key, plaintext, DshAad.LocalCache(resourceType, recordId));
}
/// <summary>
/// Opens a sealed cache record.
/// </summary>
/// <returns>
/// The plaintext, or <see langword="null"/> if the record does not belong to this row or this
/// user. Null rather than an exception because a stale cache file is an ordinary situation — a
/// changed passphrase re-derives a different key — and the caller's answer is to discard the row
/// and re-pull, not to fail.
/// </returns>
public byte[]? TryUnprotect(
CryptoSpec.AadResourceType resourceType,
Guid recordId,
ReadOnlySpan<byte> envelope)
{
ObjectDisposedException.ThrowIf(disposed, this);
return DshCrypto.Open(key, envelope, DshAad.LocalCache(resourceType, recordId));
}
/// <inheritdoc />
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
CryptographicOperations.ZeroMemory(key);
}
}
/// <summary>
/// Maps a syncable entity type onto the resource type its AAD binds.
/// </summary>
/// <remarks>
/// A switch rather than a cast, even though the two enums happen to be adjacent. They are not the
/// same list: <see cref="CryptoSpec.AadResourceType"/> also covers users, devices and vaults, so the
/// numbers do not line up, and a cast would bind an item's ciphertext to the wrong resource type
/// without failing anywhere a test would notice.
/// </remarks>
internal static class AadResourceTypes
{
internal static CryptoSpec.AadResourceType For(SyncEntityType entityType) => entityType switch
{
SyncEntityType.Host => CryptoSpec.AadResourceType.Host,
SyncEntityType.Credential => CryptoSpec.AadResourceType.Credential,
SyncEntityType.SshKey => CryptoSpec.AadResourceType.SshKey,
SyncEntityType.HostGroup => CryptoSpec.AadResourceType.HostGroup,
SyncEntityType.Tag => CryptoSpec.AadResourceType.Tag,
SyncEntityType.HostTag => CryptoSpec.AadResourceType.HostTag,
SyncEntityType.HostCredential => CryptoSpec.AadResourceType.HostCredential,
SyncEntityType.Snippet => CryptoSpec.AadResourceType.Snippet,
SyncEntityType.PortForward => CryptoSpec.AadResourceType.PortForward,
SyncEntityType.KnownHostKey => CryptoSpec.AadResourceType.KnownHostKey,
_ => throw new ArgumentOutOfRangeException(
nameof(entityType), entityType, "No AAD resource type is defined for this entity type."),
};
}