Public Access
Keep host key trust in the vault, and make it withdrawable
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.
This commit is contained in:
@@ -761,6 +761,81 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
|
||||
result.Detail.ShouldNotBeNull().ShouldContain("no public key");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AKnownHostKey_RoundTripsAsCiphertextWithNoPlaintextAtAll()
|
||||
{
|
||||
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
||||
var client = fixture.CreateClientFor(subject);
|
||||
|
||||
var pinId = Guid.CreateVersion7();
|
||||
|
||||
var pushed = await client.PostContractAsync(
|
||||
PushUrl(vaultId),
|
||||
new SyncPushRequest(
|
||||
[KnownHostOperation(pinId, expectedVersion: null, envelope: [4, 2])]));
|
||||
|
||||
var results = await pushed.Content.ReadContractAsync<SyncPushResponse>();
|
||||
results!.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
|
||||
|
||||
var pulled = await client.PostContractAsync(
|
||||
PullUrl(vaultId),
|
||||
new SyncPullRequest(null, null, [SyncEntityType.KnownHostKey]));
|
||||
|
||||
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
||||
var change = page!.Changes.ShouldHaveSingleItem();
|
||||
|
||||
change.EntityType.ShouldBe(SyncEntityType.KnownHostKey);
|
||||
change.EntityId.ShouldBe(pinId);
|
||||
change.Payload.ShouldNotBeNull().Envelope.ShouldBe([4, 2]);
|
||||
|
||||
change.PlaintextFields.ShouldBeNull(
|
||||
"which endpoints a user has approved is not something this server keeps");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AKnownHostKeyCarryingItsAddressInTheClear_IsRejected()
|
||||
{
|
||||
// The refusal that matters most of the four types, because this is the one item that genuinely holds
|
||||
// an address: a client that put it in the relay columns would be handing the operator a list of the
|
||||
// endpoints every user connects to, and it would look like an ordinary field while doing it.
|
||||
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
||||
var client = fixture.CreateClientFor(subject);
|
||||
|
||||
var operation = KnownHostOperation(Guid.CreateVersion7(), null, [1])
|
||||
with
|
||||
{ PlaintextFields = new SyncPlaintextFields(RelayEnabled: true, Hostname: "db.internal", Port: 22) };
|
||||
|
||||
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
||||
|
||||
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
||||
.ShouldHaveSingleItem();
|
||||
|
||||
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
||||
result.Detail.ShouldNotBeNull().ShouldContain("stays encrypted");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AKnownHostKeyWithAFingerprintColumn_IsRejected()
|
||||
{
|
||||
// A pin is nothing but a fingerprint, so this is the field a client would most plausibly think it
|
||||
// should send. The column exists for SSH keys, this client leaves even that one null, and a
|
||||
// fingerprint here would identify the server rather than the user's own key.
|
||||
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
||||
var client = fixture.CreateClientFor(subject);
|
||||
|
||||
var operation = KnownHostOperation(Guid.CreateVersion7(), null, [1])
|
||||
with
|
||||
{ PlaintextFields = new SyncPlaintextFields(PublicKeyFingerprint: "SHA256:whatever") };
|
||||
|
||||
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
||||
|
||||
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
||||
.ShouldHaveSingleItem();
|
||||
|
||||
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
||||
result.Detail.ShouldNotBeNull().ShouldContain("inside its payload");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThreeItemTypesWithOneId_AreThreeSeparateItems()
|
||||
{
|
||||
@@ -935,6 +1010,23 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
|
||||
Payload(envelope),
|
||||
PlaintextFields: null);
|
||||
|
||||
/// <remarks>
|
||||
/// As narrow as <see cref="CredentialOperation"/>, and worth stating why for a type that is nothing but an
|
||||
/// address and a fingerprint: both stay inside the envelope, so there is no field here either.
|
||||
/// </remarks>
|
||||
private static SyncPushOperation KnownHostOperation(
|
||||
Guid entityId,
|
||||
int? expectedVersion,
|
||||
byte[] envelope) =>
|
||||
new(
|
||||
Guid.CreateVersion7(),
|
||||
SyncEntityType.KnownHostKey,
|
||||
entityId,
|
||||
SyncOperation.Upsert,
|
||||
expectedVersion,
|
||||
Payload(envelope),
|
||||
PlaintextFields: null);
|
||||
|
||||
private static SyncPushRequest NewCreateBatch() =>
|
||||
new([NewOperation(Guid.CreateVersion7(), expectedVersion: null, envelope: [1, 2, 3, 4])]);
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
|
||||
private ClientPaths paths = null!;
|
||||
private ClientCacheFactory caches = null!;
|
||||
private TerminalWorkspace workspace = null!;
|
||||
private VaultKnownHostStore knownHosts = null!;
|
||||
private MainWindowViewModel shell = null!;
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -53,7 +54,10 @@ public sealed class ShellFlowTests : IAsyncLifetime
|
||||
paths = new ClientPaths(directory);
|
||||
caches = ClientCacheFactory.ForFile(paths.CacheFile);
|
||||
|
||||
var knownHosts = new InMemoryKnownHostStore();
|
||||
// The real store, not a stand-in. It is the one the application composes, its lifecycle is this
|
||||
// shell's business — opened on unlock, closed on lock — and the trust it records goes into the vault
|
||||
// this suite already has, so substituting one would only stop the wiring being tested.
|
||||
knownHosts = new VaultKnownHostStore();
|
||||
|
||||
// In-memory assets rather than the application's Avalonia-resource provider, which reads the
|
||||
// resource system at construction and needs an initialised toolkit. This is what
|
||||
@@ -271,7 +275,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
|
||||
paths,
|
||||
caches,
|
||||
workspace,
|
||||
new InMemoryKnownHostStore(),
|
||||
new VaultKnownHostStore(),
|
||||
(_, _) => throw new InvalidOperationException("The shell went to the network to unlock."),
|
||||
TimeProvider.System,
|
||||
CheapProfile);
|
||||
@@ -459,6 +463,138 @@ public sealed class ShellFlowTests : IAsyncLifetime
|
||||
requests.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TrustingAHostKey_PinsItInTheVaultAndConnects()
|
||||
{
|
||||
var vault = await ReadyToConnectAsync();
|
||||
|
||||
await using var renderer = await FakeRenderer.AttachAsync(workspace, Token);
|
||||
|
||||
ssh.Failure = new SshHostKeyUnknownException(
|
||||
new HostKeyPresentation("db.internal", 22, "ssh-ed25519", "SHA256:first-contact"));
|
||||
|
||||
await vault.ConnectCommand.ExecuteAsync(null);
|
||||
vault.HasPendingHostKey.ShouldBeTrue();
|
||||
|
||||
// The second connection is the one that succeeds, which is what a trust-and-retry actually is: the
|
||||
// handshake is refused, the user decides, and a fresh connection is made with the pin in place.
|
||||
ssh.Failure = null;
|
||||
|
||||
await vault.TrustHostKeyCommand.ExecuteAsync(null);
|
||||
|
||||
vault.HasPendingHostKey.ShouldBeFalse();
|
||||
|
||||
// Two connection attempts: the one that was refused and the one the pin allowed. Asserted on the
|
||||
// factory rather than on the status line, which the push that follows a trust legitimately repaints.
|
||||
ssh.Requests.Count.ShouldBe(2);
|
||||
|
||||
(await knownHosts.FindAsync("db.internal", 22, "ssh-ed25519", Token))
|
||||
.ShouldBe("SHA256:first-contact");
|
||||
|
||||
// Pushed as part of trusting, so the next machine to sync is not asked the same question.
|
||||
vault.PendingChanges.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinnedHostKey_SurvivesLockingAndUnlocking()
|
||||
{
|
||||
// The gap this whole item closes, from the shell's point of view: the store is opened on unlock and
|
||||
// its contents come out of the vault, so approving a fingerprint is a decision that lasts.
|
||||
var vault = await ReadyToConnectAsync();
|
||||
|
||||
await using var renderer = await FakeRenderer.AttachAsync(workspace, Token);
|
||||
|
||||
ssh.Failure = new SshHostKeyUnknownException(
|
||||
new HostKeyPresentation("db.internal", 22, "ssh-ed25519", "SHA256:approved"));
|
||||
|
||||
await vault.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
ssh.Failure = null;
|
||||
await vault.TrustHostKeyCommand.ExecuteAsync(null);
|
||||
|
||||
await shell.LockCommand.ExecuteAsync(null);
|
||||
|
||||
// Locked means locked: the pins go with the vault keys, so nothing can answer a host key question
|
||||
// while the window is showing an unlock screen.
|
||||
(await knownHosts.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
|
||||
shell.Passphrase = Passphrase;
|
||||
await shell.UnlockCommand.ExecuteAsync(null);
|
||||
|
||||
shell.State.ShouldBe(ShellState.Unlocked, shell.StatusMessage);
|
||||
|
||||
(await knownHosts.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHostKey_ClearsThePinAndTheRefusal()
|
||||
{
|
||||
// The way back from a rebuilt server, and the reason a mismatch can stay a hard refusal: the user
|
||||
// withdraws trust deliberately, from the host's own editor, rather than clicking past a warning.
|
||||
var vault = await ReadyToConnectAsync();
|
||||
|
||||
await using var renderer = await FakeRenderer.AttachAsync(workspace, Token);
|
||||
|
||||
ssh.Failure = new SshHostKeyUnknownException(
|
||||
new HostKeyPresentation("db.internal", 22, "ssh-ed25519", "SHA256:the-old-key"));
|
||||
|
||||
await vault.ConnectCommand.ExecuteAsync(null);
|
||||
|
||||
ssh.Failure = null;
|
||||
await vault.TrustHostKeyCommand.ExecuteAsync(null);
|
||||
|
||||
// The server is rebuilt and offers something else.
|
||||
ssh.Failure = new SshHostKeyMismatchException(
|
||||
new HostKeyPresentation("db.internal", 22, "ssh-ed25519", "SHA256:the-new-key"),
|
||||
"SHA256:the-old-key");
|
||||
|
||||
await vault.ConnectCommand.ExecuteAsync(null);
|
||||
vault.HasHostKeyMismatch.ShouldBeTrue();
|
||||
|
||||
vault.EditSelectedHostCommand.Execute(null);
|
||||
vault.CanForgetHostKey.ShouldBeTrue();
|
||||
|
||||
await vault.ForgetHostKeyCommand.ExecuteAsync(null);
|
||||
|
||||
// The refusal that sent the user here is about a pin that no longer exists, so it goes too.
|
||||
vault.HasHostKeyMismatch.ShouldBeFalse();
|
||||
|
||||
(await knownHosts.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
|
||||
// And the withdrawal was pushed rather than left for the timer: the other machines are the ones
|
||||
// still refusing to connect to a server that has been rebuilt. The wording of the message is
|
||||
// asserted in ForgettingAHostKeyThatWasNeverPinned_SaysSo, where no pass overwrites the status.
|
||||
vault.PendingChanges.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHostKeyThatWasNeverPinned_SaysSo()
|
||||
{
|
||||
var vault = await ReadyToConnectAsync();
|
||||
|
||||
vault.EditSelectedHostCommand.Execute(null);
|
||||
await vault.ForgetHostKeyCommand.ExecuteAsync(null);
|
||||
|
||||
vault.Status.ShouldContain("Nothing was pinned");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThereIsNothingToForgetOnAHostThatDoesNotExistYet()
|
||||
{
|
||||
// The button is hidden while a host is being created, because the pin belongs to an address that has
|
||||
// not been saved anywhere yet.
|
||||
var vault = await ReadyToConnectAsync();
|
||||
|
||||
vault.NewHostCommand.Execute(null);
|
||||
vault.CanForgetHostKey.ShouldBeFalse();
|
||||
|
||||
vault.CancelEditCommand.Execute(null);
|
||||
vault.CanForgetHostKey.ShouldBeFalse();
|
||||
|
||||
vault.EditSelectedHostCommand.Execute(null);
|
||||
vault.CanForgetHostKey.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The shell stops forwarding once the vault is gone. Dropping the detach half of that would compile
|
||||
/// and pass every other test, while leaving a discarded vault able to move focus in a locked window.
|
||||
@@ -583,7 +719,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
|
||||
paths,
|
||||
caches,
|
||||
workspace,
|
||||
new InMemoryKnownHostStore(),
|
||||
new VaultKnownHostStore(),
|
||||
(_, _) => throw new InvalidOperationException("unreachable"),
|
||||
TimeProvider.System,
|
||||
CheapProfile);
|
||||
|
||||
@@ -491,6 +491,7 @@
|
||||
"DodoSSH.Client.Api": "[1.0.0, )",
|
||||
"DodoSSH.Client.Auth": "[1.0.0, )",
|
||||
"DodoSSH.Client.Domain": "[1.0.0, )",
|
||||
"DodoSSH.Client.Ssh": "[1.0.0, )",
|
||||
"DodoSSH.Client.Storage": "[1.0.0, )",
|
||||
"DodoSSH.Client.Sync": "[1.0.0, )"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
namespace DodoSSH.Client.Domain.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The known-host record, its codec and its merge.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Shorter again than <see cref="CredentialSecretTests"/>, because three of the four fields are what the item
|
||||
/// is <em>about</em> rather than content that gets edited. What is specific to this type and worth pinning:
|
||||
/// that its name is derived rather than stored, that the derived name stays out of the payload and out of
|
||||
/// equality, that a mangled fingerprint is refused rather than stored to fail comparisons for ever, and that a
|
||||
/// fingerprint clash is reported with both values — the opposite of what the password merge does.
|
||||
/// </remarks>
|
||||
public sealed class KnownHostSecretTests
|
||||
{
|
||||
[Fact]
|
||||
public void APinIsNamedAfterWhatItPins()
|
||||
{
|
||||
// Read by the conflict log, which is the only place a person meets one of these. "db.internal:22" is
|
||||
// something they can match against a host in their list; an item id is not.
|
||||
Pin().Label.ShouldBe("db.internal:22 (ssh-ed25519)");
|
||||
Pin(port: 2222).Label.ShouldBe("db.internal:2222 (ssh-ed25519)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TwoPinsOfTheSameKey_AreEqual()
|
||||
{
|
||||
// The derived label is get-only, so it stays out of the record's equality — which is what makes
|
||||
// "these are the same pin" a question about the host, port, algorithm and fingerprint alone. The
|
||||
// reconciler compares secrets this way to recognise its own create coming back.
|
||||
Pin().ShouldBe(Pin());
|
||||
Pin(fingerprint: "SHA256:something-else").ShouldNotBe(Pin());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", 22, "ssh-ed25519", "SHA256:aaa", "needs the host")]
|
||||
[InlineData(" ", 22, "ssh-ed25519", "SHA256:aaa", "needs the host")]
|
||||
[InlineData("db.internal", 0, "ssh-ed25519", "SHA256:aaa", "Port must be between")]
|
||||
[InlineData("db.internal", 65536, "ssh-ed25519", "SHA256:aaa", "Port must be between")]
|
||||
[InlineData("db.internal", 22, "", "SHA256:aaa", "needs the key algorithm")]
|
||||
[InlineData("db.internal", 22, "ssh ed25519", "SHA256:aaa", "needs the key algorithm")]
|
||||
[InlineData("db.internal", 22, "ssh-ed25519", "", "needs a fingerprint")]
|
||||
[InlineData("db.internal", 22, "ssh-ed25519", "SHA256:aaa bbb", "needs a fingerprint")]
|
||||
public void AnInvalidPin_SaysWhatIsWrongWithIt(
|
||||
string host,
|
||||
int port,
|
||||
string algorithm,
|
||||
string fingerprint,
|
||||
string expected)
|
||||
{
|
||||
var pin = new KnownHostSecret
|
||||
{
|
||||
Host = host,
|
||||
Port = port,
|
||||
Algorithm = algorithm,
|
||||
Fingerprint = fingerprint,
|
||||
};
|
||||
|
||||
pin.TryValidate(out var reason).ShouldBeFalse();
|
||||
reason.ShouldNotBeNull().ShouldContain(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APinWithSpaceInItsFingerprint_IsRefusedRatherThanStored()
|
||||
{
|
||||
// A pasted "SHA256:… comment@host" or a stray newline would compare unequal to the same key on every
|
||||
// future connection, which the user would read as a permanently changed host key. Refusing it at the
|
||||
// codec means the bad value never becomes a stored pin.
|
||||
var mangled = Pin(fingerprint: "SHA256:aaa bbb");
|
||||
|
||||
Should.Throw<ArgumentException>(() => KnownHostSecretCodec.Encode(mangled));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APin_SurvivesARoundTrip()
|
||||
{
|
||||
var pin = Pin(host: "bastion.internal", port: 2222, algorithm: "rsa-sha2-512");
|
||||
|
||||
var encoded = KnownHostSecretCodec.Encode(pin);
|
||||
|
||||
KnownHostSecretCodec.TryDecode(encoded, out var document).ShouldBeTrue();
|
||||
|
||||
document.ShouldNotBeNull();
|
||||
document.KnownHost.ShouldBe(pin);
|
||||
document.SchemaVersion.ShouldBe(KnownHostSecretCodec.CurrentSchemaVersion);
|
||||
document.IsReadOnly.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EncodingIsDeterministic()
|
||||
{
|
||||
// An unchanged pin must not look like a change to the sync engine, or every pass would push every
|
||||
// host the user has ever approved.
|
||||
KnownHostSecretCodec.Encode(Pin()).ShouldBe(KnownHostSecretCodec.Encode(Pin()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheDerivedLabel_IsNotInThePayload()
|
||||
{
|
||||
// It is a function of the three fields that are, so writing it would put a value on the wire that a
|
||||
// reader could disagree with — and a merge could then take the label from one side and the address
|
||||
// from the other.
|
||||
var json = System.Text.Encoding.UTF8.GetString(KnownHostSecretCodec.Encode(Pin()));
|
||||
|
||||
json.ShouldNotContain("label");
|
||||
json.ShouldNotContain("(ssh-ed25519)");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not json")]
|
||||
[InlineData("{}")]
|
||||
[InlineData("""{"schemaVersion":1,"host":"db.internal","port":22,"algorithm":"ssh-ed25519"}""")]
|
||||
[InlineData("""{"schemaVersion":1,"host":"db.internal","port":22,"fingerprint":"SHA256:aaa"}""")]
|
||||
[InlineData("""{"schemaVersion":1,"port":22,"algorithm":"ssh-ed25519","fingerprint":"SHA256:aaa"}""")]
|
||||
[InlineData(
|
||||
"""{"schemaVersion":1,"host":"db.internal","algorithm":"ssh-ed25519","fingerprint":"SHA256:aaa"}""")]
|
||||
[InlineData(
|
||||
"""{"schemaVersion":0,"host":"db.internal","port":22,"algorithm":"ssh-ed25519","fingerprint":"SHA256:a"}""")]
|
||||
public void APayloadThatIsNotAPin_DoesNotDecode(string json)
|
||||
{
|
||||
KnownHostSecretCodec
|
||||
.TryDecode(System.Text.Encoding.UTF8.GetBytes(json), out var document)
|
||||
.ShouldBeFalse();
|
||||
|
||||
document.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APinFromANewerClient_IsReadableButNotWritable()
|
||||
{
|
||||
// Readable matters here more than for the other types: an unreadable pin means a host looks unvisited
|
||||
// and the user is asked again. The four fields a pin needs are all present, so a newer schema is
|
||||
// usable for comparison even though this build must not re-encode it.
|
||||
var payload = System.Text.Encoding.UTF8.GetBytes(
|
||||
"""
|
||||
{"schemaVersion":99,"host":"db.internal","port":22,"algorithm":"ssh-ed25519",
|
||||
"fingerprint":"SHA256:aaa","approvedBy":"someone using a later build"}
|
||||
""");
|
||||
|
||||
KnownHostSecretCodec.TryDecode(payload, out var document).ShouldBeTrue();
|
||||
|
||||
document.ShouldNotBeNull();
|
||||
document.IsReadOnly.ShouldBeTrue();
|
||||
document.KnownHost.Fingerprint.ShouldBe("SHA256:aaa");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyOneSideReApproving_TakesThatSide()
|
||||
{
|
||||
var ancestor = Pin();
|
||||
var local = ancestor with { Fingerprint = "SHA256:the-rebuilt-server" };
|
||||
|
||||
var merged = KnownHostSecretMerge.Merge(ancestor, local, ancestor);
|
||||
|
||||
merged.HasConflicts.ShouldBeFalse();
|
||||
merged.Merged.Fingerprint.ShouldBe("SHA256:the-rebuilt-server");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BothSidesApprovingADifferentKey_ReportsBothFingerprints()
|
||||
{
|
||||
// Deliberately the opposite of the password merge. An operator publishes a fingerprint so that it can
|
||||
// be compared, and a notice that withheld the value it dropped would leave the user nothing to check.
|
||||
var ancestor = Pin();
|
||||
var local = ancestor with { Fingerprint = "SHA256:seen-from-the-laptop" };
|
||||
var remote = ancestor with { Fingerprint = "SHA256:seen-from-the-desktop" };
|
||||
|
||||
var merged = KnownHostSecretMerge.Merge(ancestor, local, remote);
|
||||
|
||||
var conflict = merged.Conflicts.ShouldHaveSingleItem();
|
||||
conflict.Field.ShouldBe(nameof(KnownHostSecret.Fingerprint));
|
||||
|
||||
conflict.Kept.ShouldBe("SHA256:seen-from-the-desktop");
|
||||
conflict.Discarded.ShouldBe("SHA256:seen-from-the-laptop");
|
||||
|
||||
// The server's value wins, as it must for every replica to converge on the same answer.
|
||||
merged.Merged.Fingerprint.ShouldBe("SHA256:seen-from-the-desktop");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void APortClash_IsReportedAsANumberRatherThanAsNothing()
|
||||
{
|
||||
// Not reachable from this client — the store never re-addresses a pin — but a payload from elsewhere
|
||||
// is untrusted input, and a conflict entry with an empty value in it would be a notice about nothing.
|
||||
var ancestor = Pin();
|
||||
var local = ancestor with { Port = 2222 };
|
||||
var remote = ancestor with { Port = 2022 };
|
||||
|
||||
var merged = KnownHostSecretMerge.Merge(ancestor, local, remote);
|
||||
|
||||
var conflict = merged.Conflicts.ShouldHaveSingleItem();
|
||||
conflict.Field.ShouldBe(nameof(KnownHostSecret.Port));
|
||||
conflict.Kept.ShouldBe("2022");
|
||||
conflict.Discarded.ShouldBe("2222");
|
||||
}
|
||||
|
||||
private static KnownHostSecret Pin(
|
||||
string host = "db.internal",
|
||||
int port = 22,
|
||||
string algorithm = "ssh-ed25519",
|
||||
string fingerprint = "SHA256:aaa") =>
|
||||
new()
|
||||
{
|
||||
Host = host,
|
||||
Port = port,
|
||||
Algorithm = algorithm,
|
||||
Fingerprint = fingerprint,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
using DodoSSH.Client.Domain;
|
||||
using DodoSSH.Client.Ssh;
|
||||
using DodoSSH.Client.Storage;
|
||||
using DodoSSH.Contracts;
|
||||
using DodoSSH.Crypto;
|
||||
|
||||
namespace DodoSSH.Client.Session.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Host key trust that outlives the process, and the snapshot the SSH handshake reads it from.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The first test is the whole point of the feature: approve a fingerprint, lock the vault, unlock it again,
|
||||
/// and the host is still trusted. It runs with no server at all — the pin is in the outbox and the local
|
||||
/// cache, which is exactly the situation a user is in on a laptop that has not been online since.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The rest are the properties that would each be a security bug rather than an inconvenience: that a pin
|
||||
/// answers for the one algorithm it was recorded for, that a locked vault answers "not pinned" rather than
|
||||
/// something optimistic, and that withdrawing trust reaches every pin for the endpoint.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class VaultKnownHostStoreTests : IAsyncLifetime
|
||||
{
|
||||
private const string Passphrase = "correct horse battery staple";
|
||||
private const string ServerUrl = "https://dodossh.example";
|
||||
|
||||
/// <remarks>
|
||||
/// Far below the shipped profile, as in <see cref="SessionLifecycleTests"/>: nothing here attacks a wrap,
|
||||
/// and every test in this suite pays for at least one unlock.
|
||||
/// </remarks>
|
||||
private static readonly Argon2Profile CheapProfile =
|
||||
Argon2Profile.FromStoredParameters(memoryKibibytes: 8 * 1024, passes: 1, parallelism: 1);
|
||||
|
||||
private readonly FakeAccountServer server = new();
|
||||
private readonly StubKeyBinding keyBinding = new();
|
||||
|
||||
private ClientCacheFactory caches = null!;
|
||||
|
||||
private static CancellationToken Token => TestContext.Current.CancellationToken;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
caches = ClientCacheFactory.ForMemory($"known-hosts-{Guid.CreateVersion7():N}");
|
||||
await caches.MigrateAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await Provisioner().EnrollAsync(ServerUrl, Passphrase, "laptop", "Personal", Token);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
caches.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AHostTrustedOnceIsStillTrustedAfterALockAndUnlock()
|
||||
{
|
||||
// The gap this closes. With trust in memory the user is asked to check the same fingerprint on every
|
||||
// launch, which is how people learn to approve host keys without reading them.
|
||||
var store = new VaultKnownHostStore();
|
||||
|
||||
await using (var first = await UnlockAsync())
|
||||
{
|
||||
await store.OpenAsync(first, Token);
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
}
|
||||
|
||||
store.Close();
|
||||
|
||||
await using var second = await UnlockAsync();
|
||||
await store.OpenAsync(second, Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token))
|
||||
.ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnvisitedHost_HasNoPin()
|
||||
{
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinAnswersForOneAlgorithmOnly()
|
||||
{
|
||||
// A server legitimately offers several host keys, and which one is negotiated can change between
|
||||
// connections. A pin that answered for all of them would either accept a key nobody approved or
|
||||
// report a mismatch for an ordinary server.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(algorithm: "ssh-ed25519"), Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("db.internal", 2222, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AHostNameIsMatchedWithoutRegardToCase()
|
||||
{
|
||||
// DNS is case-insensitive, so DB.internal and db.internal are one machine. Treating them as two would
|
||||
// ask the user to approve the same server twice, and leave two pins where a withdrawal has to find
|
||||
// both.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(host: "DB.internal"), Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
|
||||
// And the value stored is the one that was dialled, not a lower-cased rewrite of it.
|
||||
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
|
||||
listing.Items.ShouldHaveSingleItem().Secret.Host.ShouldBe("DB.internal");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReApprovingTheSameKey_QueuesNothingFurther()
|
||||
{
|
||||
// Re-trusting an identical fingerprint used to be a dictionary write that cost nothing. It is now an
|
||||
// outbox operation, and queueing one would push a modification to every other machine for a decision
|
||||
// that had not changed.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
|
||||
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
|
||||
var entityId = listing.Items.ShouldHaveSingleItem().EntityId;
|
||||
|
||||
var before = await session.Outbox
|
||||
.FindAsync(session.ActiveVaultId, SyncEntityType.KnownHostKey, entityId, Token);
|
||||
|
||||
var operationId = before.ShouldNotBeNull().OperationId;
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
|
||||
// Asserted on the operation rather than on a count of pending changes, and the difference is the
|
||||
// whole test: queueing an identical write coalesces onto the same outbox row, so a count stays at one
|
||||
// either way. What would move is the operation id, which is re-minted whenever the payload is
|
||||
// rewritten — so this is what tells a redundant write from no write at all.
|
||||
var after = await session.Outbox
|
||||
.FindAsync(session.ActiveVaultId, SyncEntityType.KnownHostKey, entityId, Token);
|
||||
|
||||
after.ShouldNotBeNull().OperationId.ShouldBe(operationId);
|
||||
|
||||
(await session.KnownHosts.ListAsync(session.ActiveVaultId, Token)).Items.ShouldHaveSingleItem();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApprovingANewKeyForAKnownHost_ReplacesThePinRatherThanAddingOne()
|
||||
{
|
||||
// What happens after a server is rebuilt and its old pin has been forgotten. Two items for one
|
||||
// endpoint would leave the endpoint's trust depending on which of them a lookup happened to see.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
await store.TrustAsync(Presented(fingerprint: "SHA256:rebuilt"), Token);
|
||||
|
||||
var listing = await session.KnownHosts.ListAsync(session.ActiveVaultId, Token);
|
||||
|
||||
listing.Items.ShouldHaveSingleItem().Secret.Fingerprint.ShouldBe("SHA256:rebuilt");
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:rebuilt");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHost_TakesEveryAlgorithmWithIt()
|
||||
{
|
||||
// The user's decision is about the machine, not about one of the keys it offers. Leaving one behind
|
||||
// would mean a rebuilt server that still refuses to connect for a reason they believe they have
|
||||
// already dealt with.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(algorithm: "ssh-ed25519"), Token);
|
||||
await store.TrustAsync(Presented(algorithm: "rsa-sha2-512"), Token);
|
||||
await store.TrustAsync(Presented(host: "other.internal"), Token);
|
||||
|
||||
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(2);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
|
||||
|
||||
// And nothing else was touched.
|
||||
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHostThatWasNeverApproved_SaysSoRatherThanFailing()
|
||||
{
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AForgottenPinStaysForgottenAcrossALockAndUnlock()
|
||||
{
|
||||
// The refresh that follows a withdrawal replaces the snapshot rather than merging into it. Merging
|
||||
// would have made a forgotten pin reappear, which is the failure that matters here: the user would be
|
||||
// told the host key had changed after explicitly saying it had.
|
||||
var store = new VaultKnownHostStore();
|
||||
|
||||
await using (var first = await UnlockAsync())
|
||||
{
|
||||
await store.OpenAsync(first, Token);
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
await store.ForgetAsync("db.internal", 22, Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
store.Close();
|
||||
|
||||
await using var second = await UnlockAsync();
|
||||
await store.OpenAsync(second, Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALockedVaultAnswersNotPinnedRatherThanSomethingOptimistic()
|
||||
{
|
||||
// Reachable when a vault is locked while a handshake is in flight. Refusing the connection is the safe
|
||||
// direction; the alternative would be answering a host key question out of a vault that is closed.
|
||||
var store = new VaultKnownHostStore();
|
||||
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
await store.OpenAsync(session, Token);
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
|
||||
store.IsOpen.ShouldBeTrue();
|
||||
store.Close();
|
||||
store.IsOpen.ShouldBeFalse();
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALockedVaultRefusesToRecordOrWithdrawTrust()
|
||||
{
|
||||
// Loudly rather than silently. A pin accepted into nothing would leave the user believing they had
|
||||
// approved a host, and a withdrawal accepted into nothing would leave one they believe is gone.
|
||||
var store = new VaultKnownHostStore();
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(
|
||||
async () => await store.TrustAsync(Presented(), Token));
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(
|
||||
async () => await store.ForgetAsync("db.internal", 22, Token));
|
||||
|
||||
// And a refresh with nothing behind it is a no-op rather than a throw: a synchronisation pass may
|
||||
// finish after the vault was locked, and that is ordinary rather than exceptional.
|
||||
await store.RefreshAsync(Token);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefreshPicksUpAPinRecordedElsewhere()
|
||||
{
|
||||
// Stands in for a pin arriving from another machine: something reached the vault that this store's
|
||||
// snapshot predates. Written through the repository directly, which is what a pull followed by a
|
||||
// listing amounts to.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await session.KnownHosts.CreateAsync(
|
||||
session.ActiveVaultId,
|
||||
new KnownHostSecret
|
||||
{
|
||||
Host = "bastion.internal",
|
||||
Port = 22,
|
||||
Algorithm = "ssh-ed25519",
|
||||
Fingerprint = "SHA256:approved-on-the-desktop",
|
||||
},
|
||||
Token);
|
||||
|
||||
(await store.FindAsync("bastion.internal", 22, "ssh-ed25519", Token))
|
||||
.ShouldBeNull("the snapshot is only re-read when it is told to be");
|
||||
|
||||
await store.RefreshAsync(Token);
|
||||
|
||||
(await store.FindAsync("bastion.internal", 22, "ssh-ed25519", Token))
|
||||
.ShouldBe("SHA256:approved-on-the-desktop");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARefreshKeepsWhatWasApprovedHere()
|
||||
{
|
||||
// The mistake that would matter. A pass that re-read the vault must not drop a pin recorded on this
|
||||
// machine, or the user would be asked again about a host they had just approved.
|
||||
await using var session = await UnlockAsync();
|
||||
|
||||
var store = new VaultKnownHostStore();
|
||||
await store.OpenAsync(session, Token);
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
await store.RefreshAsync(Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private static HostKeyPresentation Presented(
|
||||
string host = "db.internal",
|
||||
int port = 22,
|
||||
string algorithm = "ssh-ed25519",
|
||||
string fingerprint = "SHA256:approved") =>
|
||||
new(host, port, algorithm, fingerprint);
|
||||
|
||||
private SessionOpener Opener() => new(caches, TimeProvider.System);
|
||||
|
||||
private AccountProvisioner Provisioner() =>
|
||||
new(server, keyBinding, caches, TimeProvider.System, CheapProfile);
|
||||
|
||||
private async Task<VaultSession> UnlockAsync()
|
||||
{
|
||||
var outcome = await Opener().UnlockAsync(Passphrase, Token);
|
||||
|
||||
outcome.IsUnlocked.ShouldBeTrue(outcome.Message);
|
||||
return outcome.Session!;
|
||||
}
|
||||
}
|
||||
@@ -324,10 +324,17 @@
|
||||
"DodoSSH.Client.Api": "[1.0.0, )",
|
||||
"DodoSSH.Client.Auth": "[1.0.0, )",
|
||||
"DodoSSH.Client.Domain": "[1.0.0, )",
|
||||
"DodoSSH.Client.Ssh": "[1.0.0, )",
|
||||
"DodoSSH.Client.Storage": "[1.0.0, )",
|
||||
"DodoSSH.Client.Sync": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"dodossh.client.ssh": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"SSH.NET": "[2025.1.0, )"
|
||||
}
|
||||
},
|
||||
"dodossh.client.storage": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
@@ -356,6 +363,12 @@
|
||||
"NSec.Cryptography": "[26.4.0, )"
|
||||
}
|
||||
},
|
||||
"BouncyCastle.Cryptography": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2.6.2, )",
|
||||
"resolved": "2.6.2",
|
||||
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
|
||||
},
|
||||
"EFCore.NamingConventions": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.1, )",
|
||||
@@ -451,6 +464,16 @@
|
||||
"dependencies": {
|
||||
"SQLitePCLRaw.core": "2.1.12"
|
||||
}
|
||||
},
|
||||
"SSH.NET": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[2025.1.0, )",
|
||||
"resolved": "2025.1.0",
|
||||
"contentHash": "jrnbtf0ItVaXAe6jE8X/kSLa6uC+0C+7W1vepcnRQB/rD88qy4IxG7Lf1FIbWmkoc4iVXv0pKrz+Wc6J4ngmHw==",
|
||||
"dependencies": {
|
||||
"BouncyCastle.Cryptography": "2.6.2",
|
||||
"Microsoft.Extensions.Logging.Abstractions": "8.0.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
namespace DodoSSH.Client.Ssh.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// What makes two pins the same pin, and the in-memory store that answers on those terms.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// No container and no vault. <see cref="KnownHostIdentity"/> is shared by every
|
||||
/// <see cref="IKnownHostStore"/>, so the identity rules are asserted here once, at the layer that defines
|
||||
/// them — and <see cref="InMemoryKnownHostStore"/> is what the rest of this suite runs against, so its own
|
||||
/// behaviour has to be right or every test above it is testing something the application does not do.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The vault-backed store that actually ships has the same rules asserted against a real cache in
|
||||
/// <c>DodoSSH.Client.Session.Tests</c>. The duplication is deliberate: two implementations of one interface,
|
||||
/// and a store that quietly disagreed with the other about which host a pin belongs to would make this
|
||||
/// suite's coverage of the connect path meaningless.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class KnownHostStoreTests
|
||||
{
|
||||
private static CancellationToken Token => TestContext.Current.CancellationToken;
|
||||
|
||||
[Fact]
|
||||
public async Task AnUnvisitedHost_HasNoPin()
|
||||
{
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinAnswersForOneHostPortAndAlgorithm()
|
||||
{
|
||||
// A server legitimately offers several host keys and may negotiate a different one next time, so the
|
||||
// algorithm is part of what was approved. A pin that answered for all of them would accept a key
|
||||
// nobody checked.
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("db.internal", 2222, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AHostNameIsMatchedWithoutRegardToCase()
|
||||
{
|
||||
// DNS is case-insensitive, so these are one machine and must be one pin.
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
await store.TrustAsync(Presented(host: "DB.internal"), Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
(await store.FindAsync("db.INTERNAL", 22, "SSH-ED25519", Token)).ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReApproving_ReplacesTheFingerprint()
|
||||
{
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
await store.TrustAsync(Presented(), Token);
|
||||
await store.TrustAsync(Presented(fingerprint: "SHA256:rebuilt"), Token);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:rebuilt");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHost_TakesEveryAlgorithmAndNothingElse()
|
||||
{
|
||||
// The decision being withdrawn is about the machine, not about one of the keys it offers — and a pin
|
||||
// left behind would keep refusing a connection the user believes they have already fixed.
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
await store.TrustAsync(Presented(algorithm: "ssh-ed25519"), Token);
|
||||
await store.TrustAsync(Presented(algorithm: "rsa-sha2-512"), Token);
|
||||
await store.TrustAsync(Presented(port: 2222), Token);
|
||||
await store.TrustAsync(Presented(host: "other.internal"), Token);
|
||||
|
||||
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(2);
|
||||
|
||||
(await store.FindAsync("db.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
(await store.FindAsync("db.internal", 22, "rsa-sha2-512", Token)).ShouldBeNull();
|
||||
|
||||
// A different port is a different endpoint, and a different host is obviously untouched.
|
||||
(await store.FindAsync("db.internal", 2222, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
(await store.FindAsync("other.internal", 22, "ssh-ed25519", Token)).ShouldBe("SHA256:approved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingAHostThatWasNeverApproved_SaysNothingWasRemoved()
|
||||
{
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForgettingIsCaseInsensitiveToo()
|
||||
{
|
||||
// The lookup and the withdrawal have to agree about identity, or a pin could be found and not
|
||||
// forgotten — which is the worst of the two, because the user would be told the trust was gone.
|
||||
var store = new InMemoryKnownHostStore();
|
||||
|
||||
await store.TrustAsync(Presented(host: "DB.internal"), Token);
|
||||
|
||||
(await store.ForgetAsync("db.internal", 22, Token)).ShouldBe(1);
|
||||
(await store.FindAsync("DB.internal", 22, "ssh-ed25519", Token)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnIdentityIsMadeOfAllThreeParts()
|
||||
{
|
||||
// Stated directly, because every store keys on this string and a format that dropped the port or the
|
||||
// algorithm would silently merge pins that are not the same pin.
|
||||
KnownHostIdentity.For("db.internal", 22, "ssh-ed25519").ShouldBe("db.internal:22/ssh-ed25519");
|
||||
|
||||
// Asserted through the comparer rather than with ShouldNotBe, because the comparer is what every
|
||||
// store actually keys on — a difference the default string comparison sees but this one does not
|
||||
// would still collapse two pins into one.
|
||||
KnownHostIdentity.Comparer.Equals(
|
||||
KnownHostIdentity.For("db.internal", 22, "ssh-ed25519"),
|
||||
KnownHostIdentity.For("db.internal", 2222, "ssh-ed25519")).ShouldBeFalse();
|
||||
|
||||
KnownHostIdentity.Comparer.Equals(
|
||||
KnownHostIdentity.For("DB.internal", 22, "ssh-ed25519"),
|
||||
KnownHostIdentity.For("db.internal", 22, "ssh-ed25519")).ShouldBeTrue();
|
||||
}
|
||||
|
||||
private static HostKeyPresentation Presented(
|
||||
string host = "db.internal",
|
||||
int port = 22,
|
||||
string algorithm = "ssh-ed25519",
|
||||
string fingerprint = "SHA256:approved") =>
|
||||
new(host, port, algorithm, fingerprint);
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public sealed class AadResourceTypeTests
|
||||
(SyncEntityType.Host, CryptoSpec.AadResourceType.Host),
|
||||
(SyncEntityType.SshKey, CryptoSpec.AadResourceType.SshKey),
|
||||
(SyncEntityType.Credential, CryptoSpec.AadResourceType.Credential),
|
||||
(SyncEntityType.KnownHostKey, CryptoSpec.AadResourceType.KnownHostKey),
|
||||
];
|
||||
|
||||
public static TheoryData<SyncEntityType, CryptoSpec.AadResourceType> Pinned
|
||||
@@ -161,6 +162,9 @@ public sealed class AadResourceTypeTests
|
||||
SyncEntityType.Credential => CredentialCipher.Seal(
|
||||
NewCredential(), vaultKey, entityId, generation, version),
|
||||
|
||||
SyncEntityType.KnownHostKey => KnownHostKeyCipher.Seal(
|
||||
NewKnownHost(), vaultKey, entityId, generation, version),
|
||||
|
||||
_ => throw new ArgumentOutOfRangeException(
|
||||
nameof(wire),
|
||||
wire,
|
||||
@@ -256,6 +260,46 @@ public sealed class AadResourceTypeTests
|
||||
SshKeyCipher.TryOpen(payload, vaultKey, entityId, itemVersion: 3).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKnownHostPayload_OpensAsNothingElse()
|
||||
{
|
||||
// The pairing table above is the load-bearing check; this is the cross-type refusal a reader expects
|
||||
// to see spelled out, and it is the one that would notice a second cipher being pointed at
|
||||
// AadResourceType.KnownHostKey by mistake.
|
||||
var vaultKey = RandomNumberGenerator.GetBytes(32);
|
||||
|
||||
var entityId = Guid.CreateVersion7();
|
||||
|
||||
var sealed_ = KnownHostKeyCipher.Seal(
|
||||
NewKnownHost(), vaultKey, entityId, keyGeneration: 1, itemVersion: 1);
|
||||
|
||||
HostCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
|
||||
SshKeyCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
|
||||
CredentialCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldBeNull();
|
||||
KnownHostKeyCipher.TryOpen(sealed_, vaultKey, entityId, itemVersion: 1).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKnownHostSealedAtOneVersion_DoesNotOpenAtAnother()
|
||||
{
|
||||
var vaultKey = RandomNumberGenerator.GetBytes(32);
|
||||
|
||||
var entityId = Guid.CreateVersion7();
|
||||
|
||||
var payload = KnownHostKeyCipher.Seal(
|
||||
NewKnownHost(), vaultKey, entityId, keyGeneration: 1, itemVersion: 2);
|
||||
|
||||
KnownHostKeyCipher.TryOpen(payload, vaultKey, entityId, itemVersion: 3).ShouldBeNull();
|
||||
}
|
||||
|
||||
private static KnownHostSecret NewKnownHost() => new()
|
||||
{
|
||||
Host = "db.internal",
|
||||
Port = 22,
|
||||
Algorithm = "ssh-ed25519",
|
||||
Fingerprint = "SHA256:5cWZ1Zc2ZmEXAMPLEfingerprintvalue0123456789a",
|
||||
};
|
||||
|
||||
private static CredentialSecret NewCredential() => new()
|
||||
{
|
||||
Label = "db-login",
|
||||
|
||||
@@ -31,7 +31,12 @@ internal sealed class FakeVaultServer : ISyncApi
|
||||
{
|
||||
/// <summary>The item types this fake knows, mirroring the server's own registry.</summary>
|
||||
private static readonly SyncEntityType[] Supported =
|
||||
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential];
|
||||
[
|
||||
SyncEntityType.Host,
|
||||
SyncEntityType.SshKey,
|
||||
SyncEntityType.Credential,
|
||||
SyncEntityType.KnownHostKey,
|
||||
];
|
||||
|
||||
private readonly Dictionary<(SyncEntityType Type, Guid EntityId), Row> rows = [];
|
||||
private readonly List<LogEntry> log = [];
|
||||
@@ -257,45 +262,81 @@ internal sealed class FakeVaultServer : ISyncApi
|
||||
|
||||
/// <summary>The per-type rules about which plaintext columns an item may carry.</summary>
|
||||
/// <remarks>
|
||||
/// A key's are stricter than a host's rather than merely different, and that asymmetry is the point:
|
||||
/// the relay concession belongs to hosts alone, so a key arriving with an address is a client bug and
|
||||
/// is refused with a reason instead of being quietly dropped.
|
||||
/// One method per type, as the server has one class per type, because the differences are the interesting
|
||||
/// part. Everything except a host is stricter rather than merely different: the relay concession belongs
|
||||
/// to hosts alone, so anything else arriving with an address is a client bug and is refused with a reason
|
||||
/// instead of being quietly dropped.
|
||||
/// </remarks>
|
||||
private static bool ValidateFields(
|
||||
SyncEntityType entityType,
|
||||
SyncPlaintextFields fields,
|
||||
out string error)
|
||||
out string error) => entityType switch
|
||||
{
|
||||
SyncEntityType.SshKey => ValidateKeyFields(fields, out error),
|
||||
SyncEntityType.Credential => ValidateCredentialFields(fields, out error),
|
||||
SyncEntityType.KnownHostKey => ValidateKnownHostFields(fields, out error),
|
||||
_ => ValidateHostFields(fields, out error),
|
||||
};
|
||||
|
||||
private static bool ValidateKeyFields(SyncPlaintextFields fields, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (entityType == SyncEntityType.SshKey)
|
||||
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
|
||||
{
|
||||
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
|
||||
{
|
||||
error = "An SSH key has no relay target; relay fields may only be set on a host.";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
error = "An SSH key has no relay target; relay fields may only be set on a host.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (entityType == SyncEntityType.Credential)
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool ValidateCredentialFields(SyncPlaintextFields fields, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
|
||||
{
|
||||
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
|
||||
{
|
||||
error = "A credential has no relay target; relay fields may only be set on a host.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fields.PublicKeyFingerprint is not null)
|
||||
{
|
||||
error = "A credential has no public key.";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
error = "A credential has no relay target; relay fields may only be set on a host.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fields.PublicKeyFingerprint is not null)
|
||||
{
|
||||
error = "A credential has no public key.";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The type that does hold an address, and holds it inside the ciphertext. A pin arriving with one in the
|
||||
/// clear would be the server being handed the list of endpoints a user reaches.
|
||||
/// </remarks>
|
||||
private static bool ValidateKnownHostFields(SyncPlaintextFields fields, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (fields.RelayEnabled || fields.Hostname is not null || fields.Port is not null)
|
||||
{
|
||||
error = "A known host key is not something the server dials; its address stays encrypted.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fields.PublicKeyFingerprint is not null)
|
||||
{
|
||||
error = "A known host key's fingerprint stays inside its payload.";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool ValidateHostFields(SyncPlaintextFields fields, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (!fields.RelayEnabled && (fields.Hostname is not null || fields.Port is not null))
|
||||
{
|
||||
error = "An address may only be supplied when relay is enabled.";
|
||||
|
||||
@@ -18,7 +18,12 @@ public sealed class ItemKindsTests
|
||||
public void ThePullFilterNamesEveryTypeThisBuildSynchronises()
|
||||
{
|
||||
ItemKinds.SyncedTypes.ShouldBe(
|
||||
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential]);
|
||||
[
|
||||
SyncEntityType.Host,
|
||||
SyncEntityType.SshKey,
|
||||
SyncEntityType.Credential,
|
||||
SyncEntityType.KnownHostKey,
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using DodoSSH.Contracts;
|
||||
using static DodoSSH.Client.Sync.Tests.SyncHarness;
|
||||
|
||||
namespace DodoSSH.Client.Sync.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Known host keys through the two-machine harness.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The first test here is the whole reason this item type exists: a host approved on the laptop is approved on
|
||||
/// the desktop. Everything else is what the credential and key suites check per type — the cipher, what the
|
||||
/// server is told, that the items cannot be confused with another type's — plus the two properties that are
|
||||
/// specific to trust: that withdrawing it propagates, and that a clash between two fingerprints is reported
|
||||
/// with both of them, unlike a clash between two passwords.
|
||||
/// </remarks>
|
||||
public sealed class KnownHostSyncTests : IAsyncLifetime
|
||||
{
|
||||
private SyncHarness harness = null!;
|
||||
|
||||
private static CancellationToken Token => TestContext.Current.CancellationToken;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask InitializeAsync() => harness = await CreateAsync();
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
harness.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AHostApprovedOnOneMachine_IsApprovedOnTheOther()
|
||||
{
|
||||
// The point of the item type. Without it a user is asked to check the same fingerprint on every
|
||||
// device, which is how people learn to approve host keys without reading them.
|
||||
var entityId = await harness.First.CreateKnownHostAsync(
|
||||
KnownHost("bastion.internal", port: 2222, fingerprint: "SHA256:approved-on-the-laptop"));
|
||||
|
||||
await harness.SettleAsync();
|
||||
|
||||
var seen = await harness.Second.FindKnownHostAsync(entityId);
|
||||
|
||||
seen.Secret.Host.ShouldBe("bastion.internal");
|
||||
seen.Secret.Port.ShouldBe(2222);
|
||||
seen.Secret.Algorithm.ShouldBe("ssh-ed25519");
|
||||
seen.Secret.Fingerprint.ShouldBe("SHA256:approved-on-the-laptop");
|
||||
seen.HasUnsyncedChanges.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TrustWithdrawnOnOneMachine_IsWithdrawnOnTheOther()
|
||||
{
|
||||
// The other half, and not a symmetry argument: a changed host key is refused with no way to continue,
|
||||
// so a withdrawal that did not travel would leave a rebuilt server unreachable from every machine
|
||||
// except the one that forgot its old key.
|
||||
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
|
||||
await harness.SettleAsync();
|
||||
|
||||
(await harness.Second.ListKnownHostsAsync()).Items.ShouldHaveSingleItem();
|
||||
|
||||
await harness.First.DeleteKnownHostAsync(entityId);
|
||||
await harness.SettleAsync();
|
||||
|
||||
(await harness.Second.ListKnownHostsAsync()).Items.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePull_AsksForKnownHostKeys()
|
||||
{
|
||||
// Derived from the registry rather than listed, so this cannot be forgotten — but a pin that
|
||||
// reconciles perfectly and is never requested would work on one machine and exist nowhere else,
|
||||
// which is exactly the failure the first test would then be unable to see.
|
||||
await harness.First.SyncAsync();
|
||||
|
||||
harness.Server.LastPullTypes.ShouldNotBeNull().ShouldContain(SyncEntityType.KnownHostKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinHandsTheServerNothingInPlaintext()
|
||||
{
|
||||
// The address especially. It is the one field here that the server is allowed to hold for a
|
||||
// relay-enabled host, and putting it on this item as well would hand the operator the list of
|
||||
// endpoints every user actually reaches — assembled out of values that are each harmless.
|
||||
var entityId = await harness.First.CreateKnownHostAsync(KnownHost("bastion.internal"));
|
||||
|
||||
var queued = await harness.First.Outbox
|
||||
.FindAsync(VaultId, SyncEntityType.KnownHostKey, entityId, Token);
|
||||
|
||||
queued.ShouldNotBeNull();
|
||||
queued.Fields.ShouldBeNull("a pin tells the server nothing but its ciphertext");
|
||||
|
||||
await harness.SettleAsync();
|
||||
|
||||
var row = harness.Server.Find(entityId, SyncEntityType.KnownHostKey).ShouldNotBeNull();
|
||||
|
||||
row.Fields.RelayEnabled.ShouldBeFalse();
|
||||
row.Fields.Hostname.ShouldBeNull();
|
||||
row.Fields.Port.ShouldBeNull();
|
||||
row.Fields.PublicKeyFingerprint.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinAndAHostSharingAnId_AreTwoItems()
|
||||
{
|
||||
// The cache keys on the type as well as the id, and each payload's AAD binds a different resource
|
||||
// type. Arranged on the server because the repositories mint UUIDv7s and would never collide.
|
||||
var sharedId = Guid.CreateVersion7();
|
||||
|
||||
harness.First.Keyring.TryGet(VaultId, out var vaultKey, out var generation).ShouldBeTrue();
|
||||
|
||||
harness.Server.ExternalUpsert(
|
||||
sharedId,
|
||||
HostCipher.Seal(Host("prod-db"), vaultKey.Span, sharedId, generation, itemVersion: 1),
|
||||
new SyncPlaintextFields(),
|
||||
SyncEntityType.Host);
|
||||
|
||||
harness.Server.ExternalUpsert(
|
||||
sharedId,
|
||||
KnownHostKeyCipher.Seal(
|
||||
KnownHost(), vaultKey.Span, sharedId, generation, itemVersion: 1),
|
||||
null,
|
||||
SyncEntityType.KnownHostKey);
|
||||
|
||||
await harness.Second.SyncAsync();
|
||||
|
||||
(await harness.Second.ListAsync()).Items.ShouldHaveSingleItem()
|
||||
.Secret.Label.ShouldBe("prod-db");
|
||||
|
||||
var pins = await harness.Second.ListKnownHostsAsync();
|
||||
|
||||
pins.Items.ShouldHaveSingleItem().Secret.Host.ShouldBe("db.internal");
|
||||
pins.Unreadable.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BothMachinesApprovedADifferentKey_TheDiscardedFingerprintIsReported()
|
||||
{
|
||||
// The deliberate contrast with the password merge, which reports that something differed and nothing
|
||||
// more. A fingerprint is published by the operator so that it can be compared; a notice that withheld
|
||||
// the value it dropped would leave the user with nothing to check it against.
|
||||
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
|
||||
await harness.SettleAsync();
|
||||
|
||||
await harness.First.UpdateKnownHostAsync(
|
||||
entityId, KnownHost(fingerprint: "SHA256:seen-from-the-laptop"));
|
||||
|
||||
await harness.Second.UpdateKnownHostAsync(
|
||||
entityId, KnownHost(fingerprint: "SHA256:seen-from-the-desktop"));
|
||||
|
||||
await harness.SettleAsync();
|
||||
|
||||
var first = (await harness.First.FindKnownHostAsync(entityId)).Secret;
|
||||
|
||||
// Converged, and on the value that reached the server first: every replica has to resolve a clash the
|
||||
// same way or the two would push against each other for ever.
|
||||
first.ShouldBe((await harness.Second.FindKnownHostAsync(entityId)).Secret);
|
||||
first.Fingerprint.ShouldBe("SHA256:seen-from-the-laptop");
|
||||
|
||||
var details = await ConflictDetailsAsync();
|
||||
|
||||
details.ShouldContain(detail => detail.Contains("SHA256:seen-from-the-desktop", StringComparison.Ordinal));
|
||||
details.ShouldContain(detail => detail.Contains("Fingerprint", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APinEditedElsewhereAfterBeingDeletedHere_IsCalledAKnownHostKey()
|
||||
{
|
||||
// The noun reaches a person. "This host key was edited elsewhere" would send them to look at the
|
||||
// server they are connecting to, rather than at a decision they made about it.
|
||||
var entityId = await harness.First.CreateKnownHostAsync(KnownHost());
|
||||
await harness.SettleAsync();
|
||||
|
||||
await harness.First.UpdateKnownHostAsync(
|
||||
entityId, KnownHost(fingerprint: "SHA256:still-the-one-i-approved"));
|
||||
|
||||
await harness.Second.DeleteKnownHostAsync(entityId);
|
||||
|
||||
await harness.SettleAsync();
|
||||
|
||||
(await harness.First.FindKnownHostAsync(entityId)).Secret.Fingerprint
|
||||
.ShouldBe("SHA256:still-the-one-i-approved");
|
||||
|
||||
var details = await ConflictDetailsAsync();
|
||||
|
||||
details.ShouldContain(
|
||||
detail => detail.Contains("This known host key was edited", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<string>> ConflictDetailsAsync()
|
||||
{
|
||||
var first = await harness.First.ConflictsAsync();
|
||||
var second = await harness.Second.ConflictsAsync();
|
||||
|
||||
return
|
||||
[
|
||||
.. first.Concat(second)
|
||||
.Select(conflict => System.Text.Encoding.UTF8.GetString(conflict.Detail)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ internal sealed class SyncDevice : IDisposable
|
||||
Hosts = new HostRepository(Items, Outbox, keyring);
|
||||
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
|
||||
Credentials = new CredentialRepository(Items, Outbox, keyring);
|
||||
KnownHosts = new KnownHostRepository(Items, Outbox, keyring);
|
||||
|
||||
Engine = new SyncEngine(
|
||||
server, Items, Outbox, SyncState, Conflicts, keyring, TimeProvider.System, options);
|
||||
@@ -62,6 +63,8 @@ internal sealed class SyncDevice : IDisposable
|
||||
|
||||
internal CredentialRepository Credentials { get; }
|
||||
|
||||
internal KnownHostRepository KnownHosts { get; }
|
||||
|
||||
internal SyncEngine Engine { get; }
|
||||
|
||||
internal static async Task<SyncDevice> CreateAsync(
|
||||
@@ -165,6 +168,29 @@ internal sealed class SyncDevice : IDisposable
|
||||
Credentials.UpdateAsync(
|
||||
SyncHarness.VaultId, entityId, credential, TestContext.Current.CancellationToken);
|
||||
|
||||
// ---- And again on known host keys ----
|
||||
|
||||
internal Task<ItemListing<KnownHostSecret>> ListKnownHostsAsync() =>
|
||||
KnownHosts.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
|
||||
|
||||
internal async Task<VaultItem<KnownHostSecret>> FindKnownHostAsync(Guid entityId)
|
||||
{
|
||||
var listing = await ListKnownHostsAsync();
|
||||
|
||||
return listing.Items.SingleOrDefault(pin => pin.EntityId == entityId)
|
||||
?? throw new InvalidOperationException($"{Name} cannot see known host key {entityId}.");
|
||||
}
|
||||
|
||||
internal Task<Guid> CreateKnownHostAsync(KnownHostSecret knownHost) =>
|
||||
KnownHosts.CreateAsync(SyncHarness.VaultId, knownHost, TestContext.Current.CancellationToken);
|
||||
|
||||
internal Task UpdateKnownHostAsync(Guid entityId, KnownHostSecret knownHost) =>
|
||||
KnownHosts.UpdateAsync(
|
||||
SyncHarness.VaultId, entityId, knownHost, TestContext.Current.CancellationToken);
|
||||
|
||||
internal Task DeleteKnownHostAsync(Guid entityId) =>
|
||||
KnownHosts.DeleteAsync(SyncHarness.VaultId, entityId, TestContext.Current.CancellationToken);
|
||||
|
||||
internal Task<IReadOnlyList<StoredConflict>> ConflictsAsync() =>
|
||||
Conflicts.ListAsync(SyncHarness.VaultId, false, TestContext.Current.CancellationToken);
|
||||
|
||||
@@ -315,6 +341,25 @@ internal sealed class SyncHarness : IDisposable
|
||||
string? notes = null) =>
|
||||
new() { Label = label, Password = password, Username = username, Notes = notes };
|
||||
|
||||
/// <summary>A pinned host key, varying only what a test is about.</summary>
|
||||
/// <remarks>
|
||||
/// The fingerprint is a plausible shape rather than a real digest. Nothing in the sync path hashes
|
||||
/// anything or checks the encoding — <c>SshHostKeyFingerprint</c> does that, one layer down and in its own
|
||||
/// suite — so a value that reads as one is worth more here than a genuine one.
|
||||
/// </remarks>
|
||||
internal static KnownHostSecret KnownHost(
|
||||
string host = "db.internal",
|
||||
int port = 22,
|
||||
string algorithm = "ssh-ed25519",
|
||||
string fingerprint = "SHA256:AAAAtestfingerprint0123456789abcdefghijklmno") =>
|
||||
new()
|
||||
{
|
||||
Host = host,
|
||||
Port = port,
|
||||
Algorithm = algorithm,
|
||||
Fingerprint = fingerprint,
|
||||
};
|
||||
|
||||
internal static SshKeySecret Key(
|
||||
string label,
|
||||
string material = "deploy-key-material",
|
||||
|
||||
@@ -91,11 +91,20 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
await AssertTheServerCannotSeeTheAddressAsync(connection, entityId);
|
||||
await AssertTheServerLearnsNothingAboutTheKeyAsync(connection, keyId);
|
||||
|
||||
var seen = await ReadOnASecondMachineAsync(connection, host, entityId, key, keyId);
|
||||
// The shell, and the trust decision it produces. Before the second machine reads the vault, so that
|
||||
// what the second machine pulls includes the host key this one approved — which is the claim the whole
|
||||
// item type exists to make and the only place it is proved through a real server.
|
||||
var pin = await OpenAShellAsync(laptop, host);
|
||||
|
||||
var trusted = await laptop.SyncAsync(connection.Sync, Token);
|
||||
trusted.Pushed.ShouldBe(1, "the host key the user approved at the prompt");
|
||||
trusted.NeedsAttention.ShouldBeFalse();
|
||||
|
||||
await AssertTheServerLearnsNothingAboutTheTrustedHostAsync(connection);
|
||||
|
||||
await ReadOnASecondMachineAsync(connection, host, entityId, key, keyId, pin);
|
||||
|
||||
await AssertUnlocksOfflineAsync(laptopCache);
|
||||
|
||||
await OpenAShellAsync(seen);
|
||||
}
|
||||
|
||||
// ---- Steps ----
|
||||
@@ -200,12 +209,18 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
change.Payload.DataKeyId.ShouldNotBe(Guid.Empty);
|
||||
}
|
||||
|
||||
private async Task<HostSecret> ReadOnASecondMachineAsync(
|
||||
/// <remarks>
|
||||
/// Takes the host key presentation the shell step produced, because the point of pinning trust in the
|
||||
/// vault is that this machine — which has never spoken to that <c>sshd</c> — already knows the fingerprint
|
||||
/// the other one approved.
|
||||
/// </remarks>
|
||||
private async Task ReadOnASecondMachineAsync(
|
||||
ServerConnection connection,
|
||||
HostSecret expected,
|
||||
Guid entityId,
|
||||
SshKeySecret expectedKey,
|
||||
Guid keyId)
|
||||
Guid keyId,
|
||||
HostKeyPresentation pin)
|
||||
{
|
||||
using var desktopCache = await OpenCacheAsync();
|
||||
|
||||
@@ -220,7 +235,7 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
await using var session = desktop;
|
||||
|
||||
var pulled = await desktop.SyncAsync(connection.Sync, Token);
|
||||
pulled.Pulled.ShouldBe(2, "the host and the key, in one pass");
|
||||
pulled.Pulled.ShouldBe(3, "the host, the key and the approved host key, in one pass");
|
||||
|
||||
var listing = await desktop.Hosts.ListAsync(desktop.ActiveVaultId, Token);
|
||||
var seen = listing.Items.ShouldHaveSingleItem();
|
||||
@@ -243,7 +258,44 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
// the key ever having been readable to the thing that carried it.
|
||||
seenKey.Secret.ShouldBe(expectedKey);
|
||||
|
||||
return seen.Secret;
|
||||
// And the host key trust, which is what stops this machine asking the user to check a fingerprint
|
||||
// somebody has already checked. Read through the store the SSH handshake actually asks, so what is
|
||||
// proved here is the answer a connection would get and not merely that a row arrived.
|
||||
var knownHosts = new VaultKnownHostStore();
|
||||
await knownHosts.OpenAsync(desktop, Token);
|
||||
|
||||
(await knownHosts.FindAsync(pin.Host, pin.Port, pin.Algorithm, Token))
|
||||
.ShouldBe(pin.Fingerprint, "trust recorded on one machine has to reach the other");
|
||||
|
||||
// The algorithm is part of the identity, so a pin must not answer for a key the user never saw.
|
||||
(await knownHosts.FindAsync(pin.Host, pin.Port, "ssh-rsa-that-was-never-offered", Token))
|
||||
.ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// A pin is the item type most likely to be given a plaintext column by mistake — it holds an address the
|
||||
/// server may already know for a relay-enabled host, and a fingerprint that is public by nature. Together,
|
||||
/// across a vault, they are the list of machines a user reaches. Asserted against the real endpoint's
|
||||
/// answer, as the host and the key are.
|
||||
/// </remarks>
|
||||
private static async Task AssertTheServerLearnsNothingAboutTheTrustedHostAsync(
|
||||
ServerConnection connection)
|
||||
{
|
||||
var vaultId = (await connection.Account.GetMeAsync(Token)).Vaults.Single().VaultId;
|
||||
|
||||
var page = await connection.Sync.SyncPullAsync(
|
||||
vaultId, new SyncPullRequest(null, 100, [SyncEntityType.KnownHostKey]), Token);
|
||||
|
||||
page.Changes.ShouldAllBe(change => change.EntityType == SyncEntityType.KnownHostKey);
|
||||
|
||||
var change = page.Changes.ShouldHaveSingleItem();
|
||||
|
||||
change.PlaintextFields.ShouldBeNull(
|
||||
"which endpoints a user has approved is not something the server is told");
|
||||
|
||||
change.Payload.ShouldNotBeNull();
|
||||
change.Payload.WrappedDataKey.ShouldNotBeEmpty();
|
||||
change.Payload.DataKeyId.ShouldNotBe(Guid.Empty);
|
||||
}
|
||||
|
||||
private static async Task AssertUnlocksOfflineAsync(ClientCacheFactory caches)
|
||||
@@ -256,18 +308,30 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Goes through the real trust-on-first-use path rather than around it. An unknown host key throws, the
|
||||
/// caller pins it and retries — which is what the interface does, and the only way to prove the
|
||||
/// fingerprint a user would be shown is the one the server actually presented.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Through the store that ships, so the pin is sealed under the vault key and queued for the server rather
|
||||
/// than kept in a dictionary. That also means the answer the second handshake gets has been through a
|
||||
/// real encrypt and decrypt, which is the property an in-memory store cannot exercise.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private static async Task OpenAShellAsync(HostSecret host)
|
||||
/// <returns>The host key that was approved, so a second machine can be asked whether it knows it.</returns>
|
||||
private static async Task<HostKeyPresentation> OpenAShellAsync(VaultSession laptop, HostSecret host)
|
||||
{
|
||||
var knownHosts = new InMemoryKnownHostStore();
|
||||
var knownHosts = new VaultKnownHostStore();
|
||||
await knownHosts.OpenAsync(laptop, Token);
|
||||
|
||||
var factory = new SshNetConnectionFactory(knownHosts);
|
||||
|
||||
var request = new SshConnectionRequest(
|
||||
host.Hostname, host.Port, host.Username!, new SshPasswordCredential(DevStack.SshPassword));
|
||||
|
||||
HostKeyPresentation? pin = null;
|
||||
|
||||
try
|
||||
{
|
||||
await using var first = await factory.ConnectAsync(request, Token);
|
||||
@@ -275,8 +339,10 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
}
|
||||
catch (SshHostKeyUnknownException exception)
|
||||
{
|
||||
exception.Presentation.Fingerprint.ShouldStartWith("SHA256:");
|
||||
await knownHosts.TrustAsync(exception.Presentation, Token);
|
||||
pin = exception.Presentation;
|
||||
|
||||
pin.Fingerprint.ShouldStartWith("SHA256:");
|
||||
await knownHosts.TrustAsync(pin, Token);
|
||||
}
|
||||
|
||||
await using var connection = await factory.ConnectAsync(request, Token);
|
||||
@@ -287,6 +353,8 @@ public sealed class M1VerticalSliceTests(DevStack stack) : IClassFixture<DevStac
|
||||
var output = await ReadUntilEchoedAsync(shell, "dodossh-e2e-ok");
|
||||
|
||||
output.ShouldContain("dodossh-e2e-ok");
|
||||
|
||||
return pin.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
@@ -420,6 +420,7 @@
|
||||
"DodoSSH.Client.Api": "[1.0.0, )",
|
||||
"DodoSSH.Client.Auth": "[1.0.0, )",
|
||||
"DodoSSH.Client.Domain": "[1.0.0, )",
|
||||
"DodoSSH.Client.Ssh": "[1.0.0, )",
|
||||
"DodoSSH.Client.Storage": "[1.0.0, )",
|
||||
"DodoSSH.Client.Sync": "[1.0.0, )"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user