Public Access
A fingerprint approved once is now approved on every machine and survives a
restart, because host key trust is a vault item type rather than a dictionary
that dies with the process. InMemoryKnownHostStore was what shipped, so the user
was asked to verify a fingerprint on every single connection — which is the gap
most likely to train somebody to click through the one warning that actually
matters. A warning that appears when nothing is wrong teaches that nothing is
ever wrong.
The fourth item type, and like the third it cost no sync logic: a row, an EF
configuration, a migration, a server kind; a secret, a codec, a merge, a cipher,
a repository facade and a session property. One row in the client registry. The
reconciler, the mirror, the repository, the outbox and the pull filter were not
touched. SyncEntityType.KnownHostKey and AadResourceType.KnownHostKey were
already reserved, so neither the contract nor docs/crypto.md changed.
One item per (host, port, algorithm), because a server legitimately offers
several host keys and which one gets negotiated is not ours to predict. Pinning
per endpoint would make an algorithm change indistinguishable from an attack.
The label is derived rather than stored, which is the one place this type
departs from the other three. A user never names a pin — there is nothing to
name it after but the three fields it already has — and a stored label is a
second copy of data that can disagree with the first after a merge. Relabel
returns the secret unchanged, and says why.
The store answers the handshake without touching the disk. SshNetConnectionFactory
calls FindAsync from inside SSH.NET's synchronous HostKeyReceived event, over
.GetAwaiter().GetResult(), which cannot be avoided; doing SQLite I/O plus an AEAD
open per lookup there would put the handshake behind the cache. So decryption
happens in OpenAsync and RefreshAsync — on unlock and after each sync pass,
exactly where the host and key lists already reload — and FindAsync is a
dictionary read under a lock with no await inside it.
That snapshot is where the one real bug in this change lived. Install originally
merged the live pins over the freshly loaded snapshot, to protect a TrustAsync
that had landed while the read was in flight. It would also have resurrected
every pin the user had just forgotten, and stopped a withdrawal made on another
machine from ever taking effect — the store would have healed the deletion back
into existence on every refresh. Replacing wholesale and discarding the read
instead is correct because writes are the rare case: every write bumps a
generation counter, and a refresh whose stamp is stale throws itself away rather
than winning. Nothing found this but reading the method again; it is the kind of
mistake that passes every test written before it, because the test that catches
it is the one the bug tells you to write.
Forgetting is new, and persistence is what made it mandatory rather than
convenient. A mismatch is a hard refusal with no way to continue — deliberately,
and that stays — so pinning a key permanently is also a way to make a
legitimately rebuilt server permanently unreachable. Before this change the pin
died at exit and the problem solved itself; now it does not.
ForgetAsync drops every algorithm for an endpoint, and it is reachable from the
host editor rather than from the warning. Putting it on the mismatch banner would
have made it two clicks from "this may be an attack" to "connect anyway", which
is the affordance the hard refusal exists to deny. The banner already promised
the key could be removed in the host's settings; that promise is now true and
points at the button.
Trust recorded on another machine becomes visible at the next sync pass, not
immediately, and that is a decision rather than an oversight. The failure it
produces is a first-contact prompt for a host a colleague approved a minute ago:
answerable, and self-correcting on the next pass. The opposite trade — polling
the vault on the handshake thread to close a one-minute window — buys nothing
and costs the property above. The dangerous direction is not reachable at all: a
pin recorded here enters the snapshot as part of recording it, so a refresh can
never discard a local trust decision.
The server learns nothing, and this is the item type where the temptation was
real. A plaintext host column would let a known-hosts screen sort and page
without decrypting anything, and it would hand the operator the map of every
user's estate — assembled, as these things are, out of facts that are each
individually harmless. A host row concedes an address only when relay is
switched on and the database refuses to store one otherwise (ADR 0004); there is
no equivalent excuse here. The table has no column to put one in, and the EF
configuration says so where somebody adding it would be standing.
Two things about the migration in this commit are worth knowing, because both
came out of getting it wrong.
It was hand-written first, including its .Designer.cs, and that version is not
what is here. Verifying it turned up something that had been quietly assumed:
Migration_AppliedCleanly_WithNoPendingModelChanges does not check the model
snapshot. It asserts that migrations applied and that none are pending, which a
wrong snapshot satisfies perfectly — the snapshot only matters as the diff base
for the *next* migrations add, so an incorrect one passes the whole suite and
corrupts the following migration instead. The real check is to generate a
throwaway migration and confirm its Up and Down come out empty. They did, and
the generated designer was byte-identical to the transcribed one across all 1255
lines, so the hand-written work was in fact correct.
Then dotnet ef migrations remove --no-build deleted the wrong migration. With
--no-build the tool reads the previously compiled assembly rather than the files
on disk, and the probe had just changed which migration was last, so it removed
AddKnownHostKeyItem and reverted the snapshot. That turned out to leave exactly
the right diff base, so the migration here is EF's own output rather than a
transcription — a better outcome than the one that was interrupted, arrived at
by accident. Never pass --no-build to migrations remove.
Mutation tested, all three sabotages detected: dropping the algorithm from
KnownHostIdentity.For, merging instead of replacing in Install, and pointing
KnownHostKeyCipher at PortForward — which is what a cast from the wire enum's 10
would silently produce. Each is caught both by an assertion about the mechanism
and by a behavioural test that never mentions it; the resource-type sabotage is
caught by the table from d10a38d and nothing else, which is what that table is
for.
The end-to-end slice now approves the real sshd's host key through the vault,
pushes it, and reads it back on the second simulated machine — including a check
that the server learned no address, and that the second machine answers null for
an algorithm never offered.
845 tests green. Zero warnings, dotnet format clean.
Three things are deliberately not fixed. A tombstone queued over a create that
was never pushed is refused by the server as Invalid and parked; that is
pre-existing for all four item types, and the fix belongs in
VaultItemRepository.DeleteAsync rather than here. Deleting a host, or changing
its address, orphans its pins — both are correct as trust decisions, since a pin
describes an endpoint and not a bookmark, but nothing surfaces the leftovers.
And there is no interface listing pins at all: trust is created at the connect
prompt and withdrawn in the host editor. A known-hosts list is where the orphans
would become visible, and it wants the vault column rework first, for the same
reason the credential editor does.
211 lines
8.1 KiB
C#
211 lines
8.1 KiB
C#
using DodoSSH.Client.Api;
|
|
using DodoSSH.Client.Storage;
|
|
using DodoSSH.Client.Sync;
|
|
using DodoSSH.Contracts;
|
|
using DodoSSH.Crypto;
|
|
|
|
namespace DodoSSH.Client.Session;
|
|
|
|
/// <summary>A conflict, decoded and ready to show.</summary>
|
|
/// <param name="Id">The conflict record, so it can be acknowledged.</param>
|
|
/// <param name="EntityId">The item it happened to.</param>
|
|
/// <param name="Kind">What happened.</param>
|
|
/// <param name="Summary">One line for a person.</param>
|
|
/// <param name="Fields">
|
|
/// Everything the merge overrode, with the discarded values. Empty for the kinds that have no field
|
|
/// detail — a rejected push, or an item that would not decrypt.
|
|
/// </param>
|
|
/// <param name="DetectedAt">When it was noticed.</param>
|
|
public sealed record ConflictNotice(
|
|
Guid Id,
|
|
Guid EntityId,
|
|
ConflictKind Kind,
|
|
string Summary,
|
|
IReadOnlyList<ConflictDetailEntry> Fields,
|
|
DateTimeOffset DetectedAt);
|
|
|
|
/// <summary>
|
|
/// An unlocked vault: the keys are in memory, the cache is open, and the hosts are readable.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Everything a session owns dies with it — the identity bundle, the vault keys and the cache key. That
|
|
/// is the whole reason this is a disposable object rather than a set of long-lived services: locking is
|
|
/// disposing, and there is exactly one place that has to be right.
|
|
/// </para>
|
|
/// <para>
|
|
/// The sync engine is <em>not</em> held here. It carries no state, so it is constructed per pass around
|
|
/// whichever transport the caller currently has — which models the actual situation, where a session is
|
|
/// perfectly usable with no network at all and syncing is the occasional thing that needs one.
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class VaultSession : IAsyncDisposable
|
|
{
|
|
private readonly UserSecretBundle bundle;
|
|
private readonly LocalCacheProtector protector;
|
|
private readonly VaultKeyring keyring;
|
|
private readonly TimeProvider clock;
|
|
private readonly SyncOptions options;
|
|
private bool disposed;
|
|
|
|
internal VaultSession(
|
|
StoredUnlockMaterial profile,
|
|
IReadOnlyList<StoredVault> vaults,
|
|
Guid activeVaultId,
|
|
UserSecretBundle bundle,
|
|
LocalCacheProtector protector,
|
|
VaultKeyring keyring,
|
|
ClientCacheFactory caches,
|
|
TimeProvider clock,
|
|
SyncOptions options)
|
|
{
|
|
Profile = profile;
|
|
Vaults = vaults;
|
|
ActiveVaultId = activeVaultId;
|
|
|
|
this.bundle = bundle;
|
|
this.protector = protector;
|
|
this.keyring = keyring;
|
|
this.clock = clock;
|
|
this.options = options;
|
|
|
|
Items = new ItemStore(caches, protector);
|
|
Outbox = new OutboxStore(caches, protector, clock);
|
|
SyncState = new SyncStateStore(caches);
|
|
Conflicts = new ConflictStore(caches, protector, clock);
|
|
Vault = new VaultStore(caches, clock);
|
|
Hosts = new HostRepository(Items, Outbox, keyring);
|
|
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
|
|
Credentials = new CredentialRepository(Items, Outbox, keyring);
|
|
KnownHosts = new KnownHostRepository(Items, Outbox, keyring);
|
|
}
|
|
|
|
/// <summary>Who this session belongs to, and the material that unlocked it.</summary>
|
|
public StoredUnlockMaterial Profile { get; }
|
|
|
|
/// <summary>Every vault this user can reach, readable or not.</summary>
|
|
public IReadOnlyList<StoredVault> Vaults { get; }
|
|
|
|
/// <summary>The vault the interface is showing. The personal one, for now.</summary>
|
|
public Guid ActiveVaultId { get; }
|
|
|
|
/// <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>Usernames and passwords, decrypted, with unpushed local changes laid over them.</summary>
|
|
public CredentialRepository Credentials { get; }
|
|
|
|
/// <summary>The host keys this vault trusts, decrypted, with unpushed local changes laid over them.</summary>
|
|
/// <remarks>
|
|
/// Read through <see cref="VaultKnownHostStore"/> rather than directly by anything that connects. The
|
|
/// handshake asks about host key trust from inside a synchronous SSH.NET event, and listing decrypts every
|
|
/// pin in the vault — see that type for why the two must not meet.
|
|
/// </remarks>
|
|
public KnownHostRepository KnownHosts { get; }
|
|
|
|
/// <summary>Vaults whose grant could not be opened, so their items cannot be read.</summary>
|
|
public IReadOnlyList<Guid> UnreadableVaults => keyring.Unopened;
|
|
|
|
internal ItemStore Items { get; }
|
|
|
|
internal OutboxStore Outbox { get; }
|
|
|
|
internal SyncStateStore SyncState { get; }
|
|
|
|
internal ConflictStore Conflicts { get; }
|
|
|
|
internal VaultStore Vault { get; }
|
|
|
|
/// <summary>Runs one synchronisation pass over the active vault.</summary>
|
|
/// <param name="api">The transport. Supplied per call because a session outlives any one connection.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
public Task<SyncReport> SyncAsync(ISyncApi api, CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(disposed, this);
|
|
ArgumentNullException.ThrowIfNull(api);
|
|
|
|
var engine = new SyncEngine(
|
|
api, Items, Outbox, SyncState, Conflicts, keyring, clock, options);
|
|
|
|
return engine.SyncAsync(ActiveVaultId, cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads the conflicts a person still needs to see.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// A conflict whose detail will not decode is still reported, with the reason in place of the
|
|
/// summary. The record itself — which item, when, what kind — remains useful even when the
|
|
/// discarded value has become unreadable, and dropping the row would be the one outcome the whole
|
|
/// conflict log exists to avoid.
|
|
/// </remarks>
|
|
public async Task<IReadOnlyList<ConflictNotice>> ReadConflictsAsync(
|
|
CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(disposed, this);
|
|
|
|
var stored = await Conflicts
|
|
.ListAsync(ActiveVaultId, includeAcknowledged: false, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
return [.. stored.Select(Describe)];
|
|
}
|
|
|
|
/// <summary>Marks a conflict as seen, keeping the discarded value retrievable.</summary>
|
|
public Task<bool> AcknowledgeConflictAsync(Guid conflictId, CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(disposed, this);
|
|
|
|
return Conflicts.AcknowledgeAsync(conflictId, cancellationToken);
|
|
}
|
|
|
|
/// <summary>How many local changes are waiting to be pushed.</summary>
|
|
public async Task<int> PendingChangeCountAsync(CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(disposed, this);
|
|
|
|
var pending = await Outbox.ListAllAsync(ActiveVaultId, cancellationToken).ConfigureAwait(false);
|
|
return pending.Count;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
if (disposed)
|
|
{
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
disposed = true;
|
|
|
|
// Order is not important — none of these depend on another — but completeness is. Missing one
|
|
// leaves key material in memory for the life of the process, which is the opposite of what
|
|
// locking is supposed to mean.
|
|
keyring.Dispose();
|
|
protector.Dispose();
|
|
bundle.Dispose();
|
|
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
private static ConflictNotice Describe(StoredConflict conflict)
|
|
{
|
|
var detail = ConflictDetails.TryRead(conflict.Detail);
|
|
|
|
return new ConflictNotice(
|
|
conflict.Id,
|
|
conflict.EntityId,
|
|
conflict.Kind,
|
|
detail?.Summary ?? "The details of this conflict could not be read.",
|
|
detail?.Fields ?? [],
|
|
conflict.DetectedAt);
|
|
}
|
|
}
|