Files
DodoSSH/tests/DodoSSH.Client.Domain.Tests/ValueSemanticsTests.cs
T
jaap-janandClaude Opus 5 8c04ba60b0 Build the three things the phone's + needs, before the + exists
Steps 1 to 3 of docs/adding-hosts-on-the-phone.md: the domain half. Nothing
on either head has changed, which is deliberate — the plan orders these first
because everything the editors will bind to has to exist and be merge-safe
before a screen can offer it.

HostGroupSecret gains a parent and four defaults, and the codec gains the
version rule it never had. It stamped CurrentSchemaVersion unconditionally,
which was harmless with one field and one version and stops being harmless
here: upgrading one machine and renaming any group would have made that group
uneditable on every machine still on the old build. It now emits the lowest
version that loses nothing, so a flat group with no defaults still encodes at
version 1, byte for byte, pinned against a literal.

Tags become a real item over the reserved slot. Secret, codec, merge, cipher,
repository, both registries, the EF entity and a generated AddTagItem
migration. TagCipher names AadResourceType.Tag as a constant rather than
casting the wire type, because Tag is 5 on the wire and 8 in the crypto enum
and 5 there is Credential — a cast would seal every tag under the resource
type for a password, encrypt and decrypt perfectly on the machine that wrote
it, and only fail when another implementation refused the item, by which time
the AAD is frozen into stored ciphertext. HostTag stays reserved and unused:
the one thing the join buys over a set on the host is bought instead by
merging TagIds per id.

HostSecret grows TagIds and Port goes nullable, which is the change with the
widest blast radius and the only one that loses an item rather than locking
one. A host with no port of its own omits the property, an older build reads
int Port as 0, and TryValidate refuses it — unreadable rather than read-only.
That cost is confined to hosts which actually inherit, because the version is
a maximum over the fields present; the alternative, writing 22 into every
host, is the lie inheritance exists to stop telling.

One decision the plan did not specify. "Three states where there were two" is
four — key, credential, typed password, or the group's answer — and two
nullable ids carry three. Naming neither id now means inherit, so
AsksForPassword says "a typed password even under a group that lends a key"
out loud. Only true is ever written and a decoded false folds back to null, so
a host that never touched it encodes as it always did. Nothing already stored
changed meaning: no group could lend a binding before this build, so every
existing host resolves exactly as it did.

HostInheritance is the resolver, and its visited set is load-bearing rather
than defensive. Two clients can each re-parent A under B and B under A while
offline; the merge sees one item against one item and the server sees
ciphertext, so nothing upstream can refuse the pair. With inheritance the
chain is walked at connect time, so an unguarded cycle is not an undrawable
sidebar — it is a shell that never opens. Stopping at the first repeat
degrades it to a group that reads as a root, and clearing the parent is the
repair.

A tag set turns out to be the one field on a host that can never ask the user
anything. TagSet.ToIdMap keys by the value, so no key can hold two values, so
the both-sides-moved-differently branch of the keyed merge is unreachable —
asserted over the whole eight-row matrix. The conflict loop is kept anyway,
because that proof is one edit from ceasing to hold and what it would cause is
a discarded tag nothing records.

Three guard tests failed by design and were fixed rather than relaxed: the
ordered pull filter, the AAD pinning table, and the server's refusal of a
plaintext parent — that last one survives with its reason rewritten, because
the refusal now means "the parent is not the server's to hold" rather than
"there is no such thing as a parent". The prose that said groups are flat is
rewritten in all four places it appeared, not deleted.

The five view-model sites that read Port directly now go through the resolver,
which is a down payment on step 4 rather than the whole of it. HostFields.From
still emits the stored port, and that is the one remaining place where an
unresolved read would be a wrong wire rather than a wrong label.

Verified by the whole suite: 1382 tests over nineteen projects, none failing.
Both heads build. Nothing seen on a display, because nothing on a display has
changed yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 10:21:02 +02:00

240 lines
10 KiB
C#

using static DodoSSH.Client.Domain.Tests.HostFactory;
namespace DodoSSH.Client.Domain.Tests;
/// <summary>
/// Equality of the collection types, and of the host that holds them.
/// </summary>
/// <remarks>
/// This suite guards a failure that would be invisible rather than loud. If any of these compared by
/// reference, the merge would report every host as changed on every sync pass, two identical edits
/// would register as a conflict, and the engine would push spurious updates forever. Nothing would
/// throw and no test elsewhere would obviously fail — which is exactly why these are asserted here.
/// </remarks>
public sealed class ValueSemanticsTests
{
[Fact]
public void TwoHostsWithEqualContents_AreEqual()
{
var one = Host(jumps: [Bastion, Relay], options: [("Compression", "yes")]);
var other = Host(jumps: [Bastion, Relay], options: [("Compression", "yes")]);
one.ShouldBe(other);
one.GetHashCode().ShouldBe(other.GetHashCode());
}
[Fact]
public void AHostDifferingOnlyInACollection_IsNotEqual()
{
Host(jumps: [Bastion]).ShouldNotBe(Host(jumps: [Relay]));
Host(options: [("Compression", "yes")]).ShouldNotBe(Host(options: [("Compression", "no")]));
}
// Note on the assertion style below: these call Equals and the operators directly rather than
// going through ShouldBe. Both of these types implement IReadOnlyList, and Shouldly compares
// enumerables element by element — so ShouldBe would pass whatever Equals did, which is the one
// thing this suite exists to check.
[Fact]
public void AJumpChain_ComparesByContentsAndOrder()
{
JumpChain.Create([Bastion, Relay]).Equals(JumpChain.Create([Bastion, Relay])).ShouldBeTrue();
(JumpChain.Create([Bastion, Relay]) == JumpChain.Create([Bastion, Relay])).ShouldBeTrue();
JumpChain.Create([Bastion, Relay]).Equals(JumpChain.Create([Relay, Bastion])).ShouldBeFalse();
JumpChain.Create([Bastion]).Equals(JumpChain.Create([Bastion, Relay])).ShouldBeFalse();
JumpChain.Create([]).Equals(JumpChain.Empty).ShouldBeTrue();
JumpChain.Create([Bastion]).Equals(null).ShouldBeFalse();
}
[Fact]
public void AJumpChain_HashesByContents()
{
JumpChain.Create([Bastion, Relay]).GetHashCode()
.ShouldBe(JumpChain.Create([Bastion, Relay]).GetHashCode());
}
[Fact]
public void AJumpChain_ComparesEqualAcrossTheSpanAndSequenceFactories()
{
Guid[] hops = [Bastion, Relay];
JumpChain.Create(hops.AsSpan()).Equals(JumpChain.Create(hops.AsEnumerable())).ShouldBeTrue();
}
[Fact]
public void Directives_CompareIgnoringNameCaseAndInputOrder()
{
// Both halves matter. Case, because a merge picks whichever spelling it saw first and two
// clients must still agree. Order, because the collection canonicalises and a user typing
// the same two directives in the other order has not changed anything.
var one = HostOptions.Create([new HostOption("Compression", "yes"), new HostOption("Port", "22")]);
var other = HostOptions.Create([new HostOption("port", "22"), new HostOption("compression", "yes")]);
one.Equals(other).ShouldBeTrue();
(one == other).ShouldBeTrue();
one.GetHashCode().ShouldBe(other.GetHashCode());
}
[Fact]
public void Directives_CompareValuesCaseSensitively()
{
// Keywords are case-insensitive in SSH; values are not. "yes" and "YES" happen to mean the
// same to sshd, but this layer must not decide that for every directive that exists.
HostOptions.Create([new HostOption("Compression", "yes")])
.Equals(HostOptions.Create([new HostOption("Compression", "YES")]))
.ShouldBeFalse();
}
[Fact]
public void Directives_CompareUnequalWhenOneSideHasMore()
{
var one = HostOptions.Create([new HostOption("Compression", "yes")]);
var other = HostOptions.Create(
[new HostOption("Compression", "yes"), new HostOption("Port", "22")]);
one.Equals(other).ShouldBeFalse();
HostOptions.Empty.Equals(one).ShouldBeFalse();
one.Equals(null).ShouldBeFalse();
}
[Fact]
public void Directives_AreHeldInNameOrder()
{
var options = HostOptions.Create(
[
new HostOption("ServerAliveInterval", "30"),
new HostOption("Compression", "yes"),
]);
options[0].Name.ShouldBe("Compression");
options[1].Name.ShouldBe("ServerAliveInterval");
}
[Fact]
public void ARepeatedDirectiveName_IsRefused()
{
// A repeated keyword has no merge key, so M1 cannot represent it. Refusing is the honest
// answer; silently keeping one of the two would lose data without saying so.
var duplicate = new[]
{
new HostOption("Compression", "yes"),
new HostOption("compression", "no"),
};
HostOptions.TryCreate(duplicate, out _, out var error).ShouldBeFalse();
error.ShouldNotBeNull();
error.Contains("more than once", StringComparison.Ordinal).ShouldBeTrue();
Should.Throw<ArgumentException>(() => HostOptions.Create(duplicate));
}
[Fact]
public void ABlankDirectiveName_IsRefused()
{
HostOptions.TryCreate([new HostOption(" ", "x")], out _, out _).ShouldBeFalse();
}
[Fact]
public void AHostBuiltWithWith_KeepsCollectionEquality()
{
// `with` copies the collection references, so this would pass even under reference equality.
// It is here because the merge builds its result with an object initialiser rather than
// `with`, and both paths have to agree.
var host = Host(options: [("Compression", "yes")]);
var copy = host with { Notes = "changed" };
copy.Options.Equals(host.Options).ShouldBeTrue();
(copy with { Notes = host.Notes }).ShouldBe(host);
}
[Fact]
public void ATagSet_ComparesByContentsAndNotByOrder()
{
// The half that differs from a jump chain, and the reason it is a separate type. A route reordered
// is a different route; a tag list reordered is the same host, so two users who tapped the same two
// chips in opposite orders must produce one value and nothing to push.
TagSet.Create([Pci, EuWest]).Equals(TagSet.Create([EuWest, Pci])).ShouldBeTrue();
(TagSet.Create([Pci, EuWest]) == TagSet.Create([EuWest, Pci])).ShouldBeTrue();
TagSet.Create([Pci, EuWest]).GetHashCode()
.ShouldBe(TagSet.Create([EuWest, Pci]).GetHashCode());
TagSet.Create([Pci]).Equals(TagSet.Create([EuWest])).ShouldBeFalse();
TagSet.Create([Pci]).Equals(TagSet.Create([Pci, EuWest])).ShouldBeFalse();
TagSet.Create([]).Equals(TagSet.Empty).ShouldBeTrue();
TagSet.Create([Pci]).Equals(null).ShouldBeFalse();
}
[Fact]
public void ATagSet_CollapsesARepeatedTag()
{
// A repeat arrives from a payload some other client wrote. Left alone it would compare unequal to
// the same set written once, and the engine would push the host as changed on every pass for ever.
TagSet.Create([Pci, Pci]).Equals(TagSet.Create([Pci])).ShouldBeTrue();
TagSet.Create([Pci, Pci]).Count.ShouldBe(1);
}
[Fact]
public void ATagSet_MapsToItsOwnIdsSoAKeyedMergeIsASetMerge()
{
// The value repeats the key on purpose: no key can then hold two different values, so the only
// disagreement a keyed merge can report is one side adding what the other removed.
var map = TagSet.Create([Pci, EuWest]).ToIdMap();
map.Keys.Order().ShouldBe(new[] { Pci, EuWest }.Order());
map[Pci].ShouldBe(Pci);
map[EuWest].ShouldBe(EuWest);
}
[Fact]
public void TryValidate_RejectsWhatCannotBeStored()
{
Host(label: "").TryValidate(out _).ShouldBeFalse();
Host(hostname: " ").TryValidate(out _).ShouldBeFalse();
Host(port: 0).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(tags: [Guid.Empty]).TryValidate(out _).ShouldBeFalse();
// Null is "take the group's port", not an absent one, and it has to be storable — it is the whole
// of what inheritance stores.
Host(port: null).TryValidate(out _).ShouldBeTrue();
Host().TryValidate(out _).ShouldBeTrue();
}
[Fact]
public void AHostGivesOneAnswerAboutAuthentication_NotTwo()
{
// The same failure the key-or-credential rule catches, in the direction inheritance opened: a host
// that names a key and also says "ask me for a password" has answered one question twice, and the
// interface, the connect path and the user would each be free to pick a different answer.
var both = Host(sshKeyId: DeployKey, asksForPassword: true);
both.TryValidate(out var reason).ShouldBeFalse();
reason.ShouldNotBeNull().ShouldContain("not both");
Host(asksForPassword: true).TryValidate(out _).ShouldBeTrue();
Host(sshKeyId: DeployKey).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();
}
}