Sync credentials as a vault item type, and bind one to a host

Closes the largest remaining M1 gap in the data layer: a username and password
can live in the vault, sync between machines, and be named by a host as how it
authenticates. What is not here is the interface for creating one — see the end
of this message.

The third item type, and the first one that cost almost nothing to add. Server:
a VaultCredential row, an EF configuration, a migration, and a CredentialKind.
Client: a secret, a codec, a merge, a cipher, a kind, a repository facade and a
session property. No new reconciliation logic, no change to the sync engine, no
client cache migration. That was the whole point of the item-kind seam, and this
is the evidence it holds.

The narrowest type of the three on plaintext, and not for symmetry. A host has a
deliberate concession — the relay needs an address it can resolve. A key has a
fingerprint, public by nature, which this client still declines to send. A
password has no part that is safe to expose: not its length, not a hash, not a
hint. So CredentialKind refuses every plaintext field there is, hydrates none,
and the table has no column to put one in.

HostSecret.CredentialId is the password counterpart of SshKeyId, and the two are
mutually exclusive. SSH itself would happily try a key and fall back to a
password, but a host naming both leaves "how does this authenticate?" without a
single answer — the interface, the connect path and the user would each be free
to guess differently. TryValidate refuses it. One consequence was not
anticipated: "a full host" stops being a coherent idea, which is what broke
AFullHost_RoundTrips and is now written into that test.

The schema version became a ladder rather than a maximum: credential-bound is 3,
key-bound is 2, neither is still 1. Adding credentials therefore does not drag
every key-bound host in every vault onto a version that clients understanding
keys perfectly well would refuse to edit. A test pins exactly that, because it is
the property the whole content-dependent-version rule exists to provide, and the
obvious implementation would quietly lose it.

Two tests had become false and said so:

- Push_AnUnsupportedEntityType_IsInvalidNotAFailedBatch used Credential as its
  example of a type this server does not implement. It now asks the server's own
  registry what is still missing, so it cannot go stale again, and skips with a
  reason if that set ever empties.
- ThePullFilterNamesEveryTypeThisBuildSynchronises pinned the exact list, which
  is what it is for.

Also fixes ten nullable warnings — eight in SyncEndpointTests, two in a test file
added earlier today. Neither set was introduced here; both were invisible until
an unrelated change forced their project to recompile, which means the
zero-warning claims made earlier in this work only ever covered what happened to
be rebuilt.

777 tests green. Zero warnings, dotnet format clean.

Not done, and deliberately: the credential interface. The vault column is 340
pixels wide and already holds two lists and two editors, kept from clipping its
own buttons at the window's minimum height only by the one-editor-at-a-time rule
added earlier today. A third list and a third editor would recreate that defect
rather than avoid it, so the column needs a shape decision first. Credentials
sync; they cannot yet be created in the interface.
This commit is contained in:
2026-07-29 21:09:08 +02:00
parent 70b3290a77
commit e24012b039
27 changed files with 2812 additions and 23 deletions
+150 -1
View File
@@ -584,6 +584,19 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
{
// A newer client asking for something this server does not do yet gets a precise
// per-operation answer rather than a whole-batch rejection.
//
// The type is taken from the server's own registry rather than named, and that is not fussiness. This
// test used to name Credential, and implementing credentials turned it into a test asserting the
// opposite of the truth — it failed loudly, but a differently-shaped test would have gone quiet
// instead. Asking the registry what is still missing keeps it aimed at the branch it was written for.
var unsupported = Enum.GetValues<SyncEntityType>()
.Where(type => type != SyncEntityType.Unspecified)
.FirstOrDefault(type => Features.Sync.ItemKinds.For(type) is null);
Assert.SkipWhen(
unsupported == SyncEntityType.Unspecified,
"Every entity type in the contract is implemented, so this branch is no longer reachable.");
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
@@ -591,7 +604,7 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Credential,
unsupported,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
@@ -665,6 +678,125 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
/// separately and then put them back in the log's order, because a client's cursor cannot resume from a
/// sequence that was regrouped.
/// </remarks>
[Fact]
public async Task ACredential_RoundTripsAsCiphertextWithNoPlaintextAtAll()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var credentialId = Guid.CreateVersion7();
var pushed = await client.PostContractAsync(
PushUrl(vaultId),
new SyncPushRequest(
[CredentialOperation(credentialId, expectedVersion: null, envelope: [7, 7, 7])]));
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.Credential]));
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
var change = page!.Changes.ShouldHaveSingleItem();
change.EntityType.ShouldBe(SyncEntityType.Credential);
change.EntityId.ShouldBe(credentialId);
change.Payload.ShouldNotBeNull().Envelope.ShouldBe([7, 7, 7]);
change.PlaintextFields.ShouldBeNull(
"a credential has no plaintext columns, so a pull has nothing to hydrate");
}
[Fact]
public async Task ACredentialCarryingPlaintextFields_IsRejected()
{
// Refused rather than dropped. A client that thinks it is storing something and is not will be
// surprised later, and for this type "something" would be a detail about a password.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var operation = new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Credential,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
Payload([1, 2, 3]),
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("no relay target");
}
[Fact]
public async Task ACredentialWithAFingerprint_IsRejected()
{
// The one plaintext field a key may carry, refused here. A password has no public half, so a client
// sending one is confused about what it is storing.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var operation = new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Credential,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
Payload([1, 2, 3]),
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("no public key");
}
[Fact]
public async Task ThreeItemTypesWithOneId_AreThreeSeparateItems()
{
// The tables are separate, so one id may name a host, a key and a credential at once. Not something a
// client would do — ids are UUIDv7 — but if the write path ever confused two types, this is the test
// that says so rather than a mystery about a missing item.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var sharedId = Guid.CreateVersion7();
var pushed = await client.PostContractAsync(
PushUrl(vaultId),
new SyncPushRequest(
[
NewOperation(sharedId, expectedVersion: null, envelope: [1, 1]),
KeyOperation(sharedId, expectedVersion: null, envelope: [2, 2]),
CredentialOperation(sharedId, expectedVersion: null, envelope: [3, 3]),
]));
(await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
.ShouldAllBe(result => result.Status == SyncOperationStatus.Applied);
var pulled = await client.PostContractAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null));
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
page!.Changes.Count.ShouldBe(3);
page.Changes.ShouldAllBe(change => change.EntityId == sharedId);
page.Changes.Select(change => change.EntityType).Order().ShouldBe(
[SyncEntityType.Host, SyncEntityType.Credential, SyncEntityType.SshKey]);
}
[Fact]
public async Task APullMixingHostsAndKeys_ReturnsBothInLogOrder()
{
@@ -776,6 +908,23 @@ public sealed class SyncEndpointTests(ApiFixture fixture)
/// <c>PlaintextFields: null</c> rather than an empty instance, which is what a real client sends for a
/// type with no plaintext columns — and what the server must accept without inventing defaults.
/// </remarks>
/// <remarks>
/// Like <see cref="KeyOperation"/> with even less: a credential has no plaintext column at all, not even
/// the fingerprint a key may carry, so this is the narrowest an operation gets.
/// </remarks>
private static SyncPushOperation CredentialOperation(
Guid entityId,
int? expectedVersion,
byte[] envelope) =>
new(
Guid.CreateVersion7(),
SyncEntityType.Credential,
entityId,
SyncOperation.Upsert,
expectedVersion,
Payload(envelope),
PlaintextFields: null);
private static SyncPushOperation KeyOperation(Guid entityId, int? expectedVersion, byte[] envelope) =>
new(
Guid.CreateVersion7(),
@@ -0,0 +1,180 @@
namespace DodoSSH.Client.Domain.Tests;
/// <summary>
/// The credential record, its codec and its merge.
/// </summary>
/// <remarks>
/// Deliberately shorter than <see cref="SshKeySecretTests"/>. The two types have the same shape and the same
/// merge strategy, so what is covered here is what is specific to a credential: that an empty password is
/// refused while a password of spaces is not, that "no username" has one spelling, and that the password
/// never appears in a conflict log.
/// </remarks>
public sealed class CredentialSecretTests
{
[Fact]
public void AnEmptyUsername_IsTheSameAsNone()
{
// One spelling of "use the host's username", for the same reasons SshKeySecret.Passphrase normalises:
// identical credentials encode identically, and "does this override the host?" has one answer.
Credential(username: string.Empty).Username.ShouldBeNull();
Credential(username: null).Username.ShouldBeNull();
Credential(username: "postgres").Username.ShouldBe("postgres");
Credential(username: string.Empty).ShouldBe(Credential(username: null));
}
[Fact]
public void APasswordOfSpaces_IsAPassword()
{
// IsNullOrWhiteSpace would refuse this, and refusing it would lock someone out of a host over a
// validation opinion. Only genuinely empty is refused.
Credential(password: " ").TryValidate(out var reason).ShouldBeTrue(reason);
Credential(password: string.Empty).TryValidate(out _).ShouldBeFalse();
}
[Theory]
[InlineData("", "hunter2", "needs a name")]
[InlineData(" ", "hunter2", "needs a name")]
[InlineData("db", "", "needs a password")]
public void AnInvalidCredential_SaysWhatIsWrongWithIt(string label, string password, string expected)
{
var credential = new CredentialSecret { Label = label, Password = password };
credential.TryValidate(out var reason).ShouldBeFalse();
reason.ShouldNotBeNull().ShouldContain(expected);
}
[Fact]
public void ACredential_SurvivesARoundTrip()
{
var credential = Credential(username: "postgres") with { Notes = "rotate in June" };
var encoded = CredentialSecretCodec.Encode(credential);
CredentialSecretCodec.TryDecode(encoded, out var document).ShouldBeTrue();
document.ShouldNotBeNull();
document.Credential.ShouldBe(credential);
document.SchemaVersion.ShouldBe(CredentialSecretCodec.CurrentSchemaVersion);
document.IsReadOnly.ShouldBeFalse();
}
[Fact]
public void EncodingIsDeterministic()
{
CredentialSecretCodec.Encode(Credential())
.ShouldBe(CredentialSecretCodec.Encode(Credential()));
}
[Fact]
public void AnEmptyUsernameIsNotWrittenAtAll()
{
CredentialSecretCodec.Encode(Credential(username: string.Empty))
.ShouldBe(CredentialSecretCodec.Encode(Credential(username: null)));
}
[Theory]
[InlineData("not json")]
[InlineData("{}")]
[InlineData("""{"schemaVersion":1,"label":"db"}""")]
[InlineData("""{"schemaVersion":1,"password":"hunter2"}""")]
[InlineData("""{"schemaVersion":0,"label":"db","password":"hunter2"}""")]
public void APayloadThatIsNotACredential_DoesNotDecode(string json)
{
CredentialSecretCodec
.TryDecode(System.Text.Encoding.UTF8.GetBytes(json), out var document)
.ShouldBeFalse();
document.ShouldBeNull();
}
[Fact]
public void ACredentialFromANewerClient_IsReadableButNotWritable()
{
var payload = System.Text.Encoding.UTF8.GetBytes(
"""
{"schemaVersion":99,"label":"db","password":"hunter2","totpSeed":"something new"}
""");
CredentialSecretCodec.TryDecode(payload, out var document).ShouldBeTrue();
document.ShouldNotBeNull().IsReadOnly.ShouldBeTrue();
}
[Fact]
public void EachSideEditingADifferentField_KeepsBoth()
{
var ancestor = Credential();
var local = ancestor with { Label = "db-primary" };
var remote = ancestor with { Notes = "from the desktop" };
var merged = CredentialSecretMerge.Merge(ancestor, local, remote);
merged.HasConflicts.ShouldBeFalse();
merged.Merged.Label.ShouldBe("db-primary");
merged.Merged.Notes.ShouldBe("from the desktop");
merged.Merged.Password.ShouldBe(ancestor.Password);
}
[Fact]
public void BothSidesChangingThePassword_NeverPutsEitherInTheConflictLog()
{
// The reason CredentialSecretMerge redacts, and the case for it is if anything plainer than for a
// key: a discarded password is very often still the live password on some other system.
var ancestor = Credential();
var local = ancestor with { Password = "LAPTOP-SECRET" };
var remote = ancestor with { Password = "DESKTOP-SECRET" };
var merged = CredentialSecretMerge.Merge(ancestor, local, remote);
var conflict = merged.Conflicts.ShouldHaveSingleItem();
conflict.Field.ShouldBe(nameof(CredentialSecret.Password));
var kept = conflict.Kept.ShouldNotBeNull();
var discarded = conflict.Discarded.ShouldNotBeNull();
foreach (var reported in new[] { kept, discarded })
{
reported.ShouldNotContain("LAPTOP-SECRET");
reported.ShouldNotContain("DESKTOP-SECRET");
}
// Redacting the report must not redact the value.
merged.Merged.Password.ShouldBeOneOf("LAPTOP-SECRET", "DESKTOP-SECRET");
}
[Fact]
public void AUsernameClash_IsShownInFull()
{
// Not a secret, and knowing which account the merge dropped is the whole use of the notice.
var ancestor = Credential();
var local = ancestor with { Username = "postgres" };
var remote = ancestor with { Username = "deploy" };
var merged = CredentialSecretMerge.Merge(ancestor, local, remote);
var conflict = merged.Conflicts.ShouldHaveSingleItem();
conflict.Field.ShouldBe(nameof(CredentialSecret.Username));
new[] { conflict.Kept, conflict.Discarded }.ShouldBe(["deploy", "postgres"], ignoreOrder: true);
}
[Fact]
public void AUsernameClashingWithItsRemoval_SaysWhichSideHadNone()
{
var ancestor = Credential(username: "root");
var local = ancestor with { Username = null };
var remote = ancestor with { Username = "deploy" };
var merged = CredentialSecretMerge.Merge(ancestor, local, remote);
var conflict = merged.Conflicts.ShouldHaveSingleItem();
conflict.Kept.ShouldBe("deploy");
conflict.Discarded.ShouldBe("(none)");
}
private static CredentialSecret Credential(
string password = "hunter2",
string? username = null) =>
new() { Label = "db", Password = password, Username = username };
}
@@ -19,7 +19,8 @@ internal static class HostFactory
Guid[]? jumps = null,
(string Name, string Value)[]? options = null,
bool relayEnabled = false,
Guid? sshKeyId = null) =>
Guid? sshKeyId = null,
Guid? credentialId = null) =>
new()
{
Label = label,
@@ -33,5 +34,6 @@ internal static class HostFactory
: HostOptions.Create(options.Select(o => new HostOption(o.Name, o.Value))),
RelayEnabled = relayEnabled,
SshKeyId = sshKeyId,
CredentialId = credentialId,
};
}
@@ -14,11 +14,17 @@ namespace DodoSSH.Client.Domain.Tests;
/// </remarks>
public sealed class HostSecretCodecTests
{
/// <remarks>
/// "Full" cannot mean every field any more: the two bindings are mutually exclusive, so a host may carry
/// a key or a credential and never both. This one carries the credential because that is the newer of
/// the two and therefore the highest schema version a valid host can reach; the key-bound case has its
/// own version test below.
/// </remarks>
[Fact]
public void AFullHost_RoundTrips()
{
// Every field, which is what makes the version assertion below meaningful: a host carrying the
// newest field is the only kind written at the newest version.
var credentialId = Guid.Parse("0192f0c8-5555-7c3d-8e4f-5a6b7c8d9e05");
var host = Host(
label: "prod-db",
hostname: "db.internal",
@@ -28,12 +34,13 @@ public sealed class HostSecretCodecTests
jumps: [Bastion, Relay],
options: [("ServerAliveInterval", "30"), ("Compression", "yes")],
relayEnabled: true,
sshKeyId: DeployKey);
credentialId: credentialId);
HostSecretCodec.TryDecode(HostSecretCodec.Encode(host), out var document).ShouldBeTrue();
document.ShouldNotBeNull();
document.Host.ShouldBe(host);
document.Host.CredentialId.ShouldBe(credentialId);
document.SchemaVersion.ShouldBe(HostSecretCodec.CurrentSchemaVersion);
document.IsReadOnly.ShouldBeFalse();
}
@@ -65,6 +72,37 @@ public sealed class HostSecretCodecTests
document.Host.SshKeyId.ShouldBe(DeployKey);
}
[Fact]
public void AHostThatBindsACredential_IsWrittenAtTheVersionThatIntroducedIt()
{
// Each binding earns its own version, so a host using only the older one is not dragged forward onto
// a version older clients refuse to edit.
var credentialId = Guid.CreateVersion7();
HostSecretCodec
.TryDecode(HostSecretCodec.Encode(Host(credentialId: credentialId)), out var document)
.ShouldBeTrue();
document.ShouldNotBeNull();
document.SchemaVersion.ShouldBe(HostSecretCodec.CredentialIdSchemaVersion);
document.Host.CredentialId.ShouldBe(credentialId);
}
[Fact]
public void AKeyBoundHost_IsNotDraggedOntoTheCredentialVersion()
{
// The point of the ladder. Adding credentials must not make every key-bound host in every vault
// read-only on a client that understands keys perfectly well.
HostSecretCodec
.TryDecode(HostSecretCodec.Encode(Host(sshKeyId: DeployKey)), out var document)
.ShouldBeTrue();
var version = document.ShouldNotBeNull().SchemaVersion;
version.ShouldBe(HostSecretCodec.SshKeyIdSchemaVersion);
version.ShouldBeLessThan(HostSecretCodec.CredentialIdSchemaVersion);
}
[Fact]
public void AddingTheKeyField_DidNotChangeTheBytesOfAHostWithoutOne()
{
@@ -198,10 +198,14 @@ public sealed class SshKeySecretTests
// Named, so the user knows what clashed. Not quoted, because the conflict log is stored to be read
// and is deliberately kept after acknowledgement.
conflict.Kept.ShouldNotContain("LAPTOP-SECRET");
conflict.Kept.ShouldNotContain("DESKTOP-SECRET");
conflict.Discarded.ShouldNotBeNull().ShouldNotContain("LAPTOP-SECRET");
conflict.Discarded.ShouldNotContain("DESKTOP-SECRET");
var kept = conflict.Kept.ShouldNotBeNull();
var discarded = conflict.Discarded.ShouldNotBeNull();
foreach (var reported in new[] { kept, discarded })
{
reported.ShouldNotContain("LAPTOP-SECRET");
reported.ShouldNotContain("DESKTOP-SECRET");
}
// And the surviving key is a real one — redacting the report must not redact the value.
merged.Merged.PrivateKeyPem.ShouldBeOneOf(local.PrivateKeyPem, remote.PrivateKeyPem);
@@ -218,8 +222,11 @@ public sealed class SshKeySecretTests
var conflict = merged.Conflicts.ShouldHaveSingleItem();
conflict.Field.ShouldBe(nameof(SshKeySecret.Passphrase));
conflict.Kept.ShouldNotContain("passphrase-");
conflict.Kept.ShouldNotContain("laptop-passphrase");
var kept = conflict.Kept.ShouldNotBeNull();
kept.ShouldNotContain("passphrase-");
kept.ShouldNotContain("laptop-passphrase");
conflict.Discarded.ShouldNotBeNull().ShouldNotContain("desktop-passphrase");
}
@@ -156,6 +156,23 @@ public sealed class ValueSemanticsTests
Host(hostname: " ").TryValidate(out _).ShouldBeFalse();
Host(port: 65536).TryValidate(out _).ShouldBeFalse();
Host(jumps: [Guid.Empty]).TryValidate(out _).ShouldBeFalse();
Host(sshKeyId: Guid.Empty).TryValidate(out _).ShouldBeFalse();
Host(credentialId: Guid.Empty).TryValidate(out _).ShouldBeFalse();
Host().TryValidate(out _).ShouldBeTrue();
}
[Fact]
public void AHostAuthenticatesOneWay_NotTwo()
{
// SSH would happily try a key and fall back to a password, and a host that named both would leave
// "how does this authenticate?" without a single answer — so the interface, the connect path and the
// user would each be free to guess differently. Refused at the type instead.
var both = Host(sshKeyId: DeployKey, credentialId: Guid.CreateVersion7());
both.TryValidate(out var reason).ShouldBeFalse();
reason.ShouldNotBeNull().ShouldContain("not both");
Host(sshKeyId: DeployKey).TryValidate(out _).ShouldBeTrue();
Host(credentialId: Guid.CreateVersion7()).TryValidate(out _).ShouldBeTrue();
}
}
@@ -0,0 +1,211 @@
using DodoSSH.Client.Storage;
using DodoSSH.Contracts;
using static DodoSSH.Client.Sync.Tests.SyncHarness;
namespace DodoSSH.Client.Sync.Tests;
/// <summary>
/// Credentials through the two-machine harness.
/// </summary>
/// <remarks>
/// Shorter still than <see cref="SshKeySyncTests"/>, and that is the payoff of the shared reconciler: the six
/// collision outcomes are one implementation and are already exercised. What is left to check per type is its
/// cipher, what it tells the server, that its items cannot be confused with another type's, and that the one
/// thing which must never be logged is not logged.
/// </remarks>
public sealed class CredentialSyncTests : 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 ACredentialCreatedOnOneMachine_ReachesTheOther()
{
var entityId = await harness.First.CreateCredentialAsync(
Credential("prod-db", password: "hunter2", username: "postgres", notes: "rotate in June"));
await harness.SettleAsync();
var seen = await harness.Second.FindCredentialAsync(entityId);
seen.Secret.Label.ShouldBe("prod-db");
seen.Secret.Password.ShouldBe("hunter2");
seen.Secret.Username.ShouldBe("postgres");
seen.Secret.Notes.ShouldBe("rotate in June");
seen.HasUnsyncedChanges.ShouldBeFalse();
}
[Fact]
public async Task ThePull_AsksForAllThreeTypes()
{
await harness.First.SyncAsync();
var asked = harness.Server.LastPullTypes.ShouldNotBeNull();
asked.ShouldContain(SyncEntityType.Host);
asked.ShouldContain(SyncEntityType.SshKey);
asked.ShouldContain(SyncEntityType.Credential);
}
[Fact]
public async Task ACredentialHandsTheServerNothingInPlaintext()
{
var entityId = await harness.First.CreateCredentialAsync(Credential("prod-db"));
var queued = await harness.First.Outbox
.FindAsync(VaultId, SyncEntityType.Credential, entityId, Token);
queued.ShouldNotBeNull();
queued.Fields.ShouldBeNull("nothing about a password is safe to hold in the clear");
await harness.SettleAsync();
var row = harness.Server.Find(entityId, SyncEntityType.Credential).ShouldNotBeNull();
row.Fields.RelayEnabled.ShouldBeFalse();
row.Fields.Hostname.ShouldBeNull();
row.Fields.PublicKeyFingerprint.ShouldBeNull();
}
[Fact]
public async Task ThreeTypesSharingOneId_AreThreeItems()
{
// The cache keys on the type as well as the id, and each payload's AAD binds a different resource
// type — two defences, independently. 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,
SshKeyCipher.Seal(Key("deploy"), vaultKey.Span, sharedId, generation, itemVersion: 1),
null,
SyncEntityType.SshKey);
harness.Server.ExternalUpsert(
sharedId,
CredentialCipher.Seal(
Credential("db-login"), vaultKey.Span, sharedId, generation, itemVersion: 1),
null,
SyncEntityType.Credential);
await harness.Second.SyncAsync();
(await harness.Second.ListAsync()).Items.ShouldHaveSingleItem()
.Secret.Label.ShouldBe("prod-db");
(await harness.Second.ListKeysAsync()).Items.ShouldHaveSingleItem()
.Secret.Label.ShouldBe("deploy");
var credentials = await harness.Second.ListCredentialsAsync();
credentials.Items.ShouldHaveSingleItem().Secret.Label.ShouldBe("db-login");
credentials.Unreadable.ShouldBe(0);
}
[Fact]
public async Task TwoMachinesEditingDifferentFields_BothSurvive()
{
var entityId = await harness.First.CreateCredentialAsync(Credential("prod-db"));
await harness.SettleAsync();
await harness.First.UpdateCredentialAsync(entityId, Credential("prod-db-primary"));
await harness.Second.UpdateCredentialAsync(
entityId, Credential("prod-db", notes: "from the desktop"));
await harness.SettleAsync();
var first = (await harness.First.FindCredentialAsync(entityId)).Secret;
first.ShouldBe((await harness.Second.FindCredentialAsync(entityId)).Secret);
first.Label.ShouldBe("prod-db-primary");
first.Notes.ShouldBe("from the desktop");
(await ConflictKindsAsync()).ShouldBeEmpty();
}
[Fact]
public async Task BothChangedThePassword_NeitherReachesTheConflictLog()
{
var entityId = await harness.First.CreateCredentialAsync(Credential("prod-db"));
await harness.SettleAsync();
await harness.First.UpdateCredentialAsync(entityId, Credential("prod-db", "LAPTOP-SECRET"));
await harness.Second.UpdateCredentialAsync(entityId, Credential("prod-db", "DESKTOP-SECRET"));
await harness.SettleAsync();
(await ConflictKindsAsync()).ShouldContain(kind => kind == ConflictKind.FieldOverridden);
var details = await ConflictDetailsAsync();
details.ShouldContain(
detail => detail.Contains("Password", StringComparison.Ordinal),
"the user still has to be told which field clashed");
foreach (var detail in details)
{
detail.ShouldNotContain("LAPTOP-SECRET");
detail.ShouldNotContain("DESKTOP-SECRET");
}
}
[Fact]
public async Task ACredentialEditedElsewhereAfterBeingDeletedHere_IsCalledACredential()
{
var entityId = await harness.First.CreateCredentialAsync(Credential("prod-db"));
await harness.SettleAsync();
await harness.First.UpdateCredentialAsync(entityId, Credential("prod-db", notes: "still in use"));
await harness.Second.Credentials.DeleteAsync(VaultId, entityId, Token);
await harness.SettleAsync();
(await harness.First.FindCredentialAsync(entityId)).Secret.Notes.ShouldBe("still in use");
var details = await ConflictDetailsAsync();
details.ShouldContain(
detail => detail.Contains("This credential was edited", StringComparison.Ordinal));
details.ShouldNotContain(
detail => detail.Contains("This host was edited", StringComparison.Ordinal));
}
private async Task<IReadOnlyList<ConflictKind>> ConflictKindsAsync()
{
var first = await harness.First.ConflictsAsync();
var second = await harness.Second.ConflictsAsync();
return [.. first.Concat(second).Select(conflict => conflict.Kind)];
}
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)),
];
}
}
@@ -30,7 +30,8 @@ namespace DodoSSH.Client.Sync.Tests;
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];
private static readonly SyncEntityType[] Supported =
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential];
private readonly Dictionary<(SyncEntityType Type, Guid EntityId), Row> rows = [];
private readonly List<LogEntry> log = [];
@@ -278,6 +279,23 @@ internal sealed class FakeVaultServer : ISyncApi
return true;
}
if (entityType == SyncEntityType.Credential)
{
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;
}
if (!fields.RelayEnabled && (fields.Hostname is not null || fields.Port is not null))
{
error = "An address may only be supplied when relay is enabled.";
@@ -17,7 +17,8 @@ public sealed class ItemKindsTests
[Fact]
public void ThePullFilterNamesEveryTypeThisBuildSynchronises()
{
ItemKinds.SyncedTypes.ShouldBe([SyncEntityType.Host, SyncEntityType.SshKey]);
ItemKinds.SyncedTypes.ShouldBe(
[SyncEntityType.Host, SyncEntityType.SshKey, SyncEntityType.Credential]);
}
[Fact]
@@ -38,6 +38,7 @@ internal sealed class SyncDevice : IDisposable
Conflicts = new ConflictStore(factory, protector, TimeProvider.System);
Hosts = new HostRepository(Items, Outbox, keyring);
SshKeys = new SshKeyRepository(Items, Outbox, keyring);
Credentials = new CredentialRepository(Items, Outbox, keyring);
Engine = new SyncEngine(
server, Items, Outbox, SyncState, Conflicts, keyring, TimeProvider.System, options);
@@ -59,6 +60,8 @@ internal sealed class SyncDevice : IDisposable
internal SshKeyRepository SshKeys { get; }
internal CredentialRepository Credentials { get; }
internal SyncEngine Engine { get; }
internal static async Task<SyncDevice> CreateAsync(
@@ -142,6 +145,26 @@ internal sealed class SyncDevice : IDisposable
internal Task DeleteKeyAsync(Guid entityId) =>
SshKeys.DeleteAsync(SyncHarness.VaultId, entityId, TestContext.Current.CancellationToken);
// ---- And again on credentials ----
internal Task<ItemListing<CredentialSecret>> ListCredentialsAsync() =>
Credentials.ListAsync(SyncHarness.VaultId, TestContext.Current.CancellationToken);
internal async Task<VaultItem<CredentialSecret>> FindCredentialAsync(Guid entityId)
{
var listing = await ListCredentialsAsync();
return listing.Items.SingleOrDefault(credential => credential.EntityId == entityId)
?? throw new InvalidOperationException($"{Name} cannot see credential {entityId}.");
}
internal Task<Guid> CreateCredentialAsync(CredentialSecret credential) =>
Credentials.CreateAsync(SyncHarness.VaultId, credential, TestContext.Current.CancellationToken);
internal Task UpdateCredentialAsync(Guid entityId, CredentialSecret credential) =>
Credentials.UpdateAsync(
SyncHarness.VaultId, entityId, credential, TestContext.Current.CancellationToken);
internal Task<IReadOnlyList<StoredConflict>> ConflictsAsync() =>
Conflicts.ListAsync(SyncHarness.VaultId, false, TestContext.Current.CancellationToken);
@@ -284,6 +307,14 @@ internal sealed class SyncHarness : IDisposable
/// what it was used for. <c>SshKeySecret.TryValidate</c> only requires the armour, and the tests that
/// need a key SSH.NET can actually load live in <c>DodoSSH.Client.Ssh.Tests</c> where one is generated.
/// </remarks>
/// <summary>A credential for the suites, varying only what a test is about.</summary>
internal static CredentialSecret Credential(
string label,
string password = "hunter2",
string? username = null,
string? notes = null) =>
new() { Label = label, Password = password, Username = username, Notes = notes };
internal static SshKeySecret Key(
string label,
string material = "deploy-key-material",