Public Access
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:
@@ -0,0 +1,211 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace DodoSSH.Client.Domain;
|
||||
|
||||
/// <summary>A decoded host payload, together with the schema version it was written at.</summary>
|
||||
/// <param name="Host">The host.</param>
|
||||
/// <param name="SchemaVersion">
|
||||
/// The version the writing client used. May exceed
|
||||
/// <see cref="HostSecretCodec.CurrentSchemaVersion"/>, which is the case this type exists to make
|
||||
/// visible.
|
||||
/// </param>
|
||||
public sealed record HostSecretDocument(HostSecret Host, int SchemaVersion)
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether this payload was written by a newer client than the one reading it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Such an item is safe to <em>read</em> — every field this build knows about decodes normally —
|
||||
/// but must not be re-encoded, because fields added by the newer schema are not represented here
|
||||
/// and would be dropped on write. Silently losing a field a colleague filled in is exactly the
|
||||
/// class of bug that makes people stop trusting a synced vault.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// So the rule is: display it, refuse to edit it, and tell the user to update. Preserving unknown
|
||||
/// fields through a round trip was the alternative and it is worse — it means carrying opaque
|
||||
/// JSON inside the domain model, which then has no usable structural equality and so breaks the
|
||||
/// merge.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public bool IsReadOnly => SchemaVersion > HostSecretCodec.CurrentSchemaVersion;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encodes and decodes the plaintext inside a host item's encrypted payload.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// JSON rather than the fixed binary layouts used elsewhere in the specification. The reasoning
|
||||
/// differs because the constraints differ: those layouts are hashed or signed, so canonicality is
|
||||
/// load-bearing, whereas this is only ever encrypted. What matters here instead is that the format
|
||||
/// grows a field without a migration — and the one thing that must not happen is an old client
|
||||
/// quietly dropping a field a new one wrote, which is what <see cref="HostSecretDocument.IsReadOnly"/>
|
||||
/// prevents.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Encoding is deterministic: property order is fixed by declaration, and directives are held in a
|
||||
/// sorted map. That matters because the sync engine decides whether to push by comparing values, and
|
||||
/// a codec that produced different bytes for the same host would make every pass look like a change.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class HostSecretCodec
|
||||
{
|
||||
/// <summary>The schema version this build writes.</summary>
|
||||
public const int CurrentSchemaVersion = 1;
|
||||
|
||||
/// <summary>Serialises a host to the bytes that get sealed.</summary>
|
||||
/// <exception cref="ArgumentException">The host is not valid for storage.</exception>
|
||||
public static byte[] Encode(HostSecret host)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
|
||||
if (!host.TryValidate(out var error))
|
||||
{
|
||||
throw new ArgumentException(error, nameof(host));
|
||||
}
|
||||
|
||||
var options = new SortedDictionary<string, string>(HostOption.NameComparer);
|
||||
foreach (var option in host.Options)
|
||||
{
|
||||
options[option.Name] = option.Value;
|
||||
}
|
||||
|
||||
var document = new HostPayloadDocument
|
||||
{
|
||||
SchemaVersion = CurrentSchemaVersion,
|
||||
Label = host.Label,
|
||||
Hostname = host.Hostname,
|
||||
Port = host.Port,
|
||||
Username = host.Username,
|
||||
Notes = host.Notes,
|
||||
JumpHostIds = [.. host.JumpHostIds],
|
||||
Options = options,
|
||||
RelayEnabled = host.RelayEnabled,
|
||||
};
|
||||
|
||||
return JsonSerializer.SerializeToUtf8Bytes(
|
||||
document, HostPayloadJsonContext.Default.HostPayloadDocument);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a decrypted payload.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns <see langword="false"/> rather than throwing on anything malformed. These bytes
|
||||
/// authenticated under a key only vault members hold, so a failure here is not an attack — it is
|
||||
/// a bug in some client, or a truncated write. Either way it must degrade to one unreadable item
|
||||
/// rather than an exception that aborts the whole sync pass and strands every other change.
|
||||
/// </remarks>
|
||||
public static bool TryDecode(
|
||||
ReadOnlySpan<byte> payload,
|
||||
[NotNullWhen(true)] out HostSecretDocument? document)
|
||||
{
|
||||
document = null;
|
||||
|
||||
HostPayloadDocument? parsed;
|
||||
try
|
||||
{
|
||||
parsed = JsonSerializer.Deserialize(
|
||||
payload, HostPayloadJsonContext.Default.HostPayloadDocument);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parsed is null || parsed.SchemaVersion < 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryBuild(parsed, out var host))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
document = new HostSecretDocument(host, parsed.SchemaVersion);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryBuild(
|
||||
HostPayloadDocument parsed,
|
||||
[NotNullWhen(true)] out HostSecret? host)
|
||||
{
|
||||
host = null;
|
||||
|
||||
var directives = (parsed.Options ?? [])
|
||||
.Select(entry => new HostOption(entry.Key, entry.Value));
|
||||
|
||||
if (!HostOptions.TryCreate(directives, out var options, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var candidate = new HostSecret
|
||||
{
|
||||
Label = parsed.Label ?? string.Empty,
|
||||
Hostname = parsed.Hostname ?? string.Empty,
|
||||
Port = parsed.Port,
|
||||
Username = parsed.Username,
|
||||
Notes = parsed.Notes,
|
||||
JumpHostIds = JumpChain.Create(parsed.JumpHostIds ?? []),
|
||||
Options = options,
|
||||
RelayEnabled = parsed.RelayEnabled,
|
||||
};
|
||||
|
||||
if (!candidate.TryValidate(out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
host = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The serialised shape. Mutable and nullable because it models untrusted input.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deliberately separate from <see cref="HostSecret"/>. A single type would force the domain model to
|
||||
/// carry the serialiser's requirements — a parameterless constructor, settable properties, nullable
|
||||
/// everything — and would let a decode failure produce a half-built host that looks valid to
|
||||
/// everything downstream.
|
||||
/// </remarks>
|
||||
internal sealed class HostPayloadDocument
|
||||
{
|
||||
public int SchemaVersion { get; set; }
|
||||
|
||||
public string? Label { get; set; }
|
||||
|
||||
public string? Hostname { get; set; }
|
||||
|
||||
public int Port { get; set; }
|
||||
|
||||
public string? Username { get; set; }
|
||||
|
||||
public string? Notes { get; set; }
|
||||
|
||||
public Guid[]? JumpHostIds { get; set; }
|
||||
|
||||
/// <remarks>
|
||||
/// Sorted, so serialisation order is defined by the type rather than by insertion order — a
|
||||
/// plain <see cref="Dictionary{TKey,TValue}"/> does not guarantee enumeration order, and this
|
||||
/// encoding has to be reproducible.
|
||||
/// </remarks>
|
||||
public SortedDictionary<string, string>? Options { get; set; }
|
||||
|
||||
public bool RelayEnabled { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
// An unknown member means a newer client wrote a field this build has no concept of. Skipping it
|
||||
// is right; the guard against losing it lives in HostSecretDocument.IsReadOnly.
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip)]
|
||||
[JsonSerializable(typeof(HostPayloadDocument))]
|
||||
internal sealed partial class HostPayloadJsonContext : JsonSerializerContext;
|
||||
Reference in New Issue
Block a user