Skip to content

fix!: thread-safety and mutability fixes for IPNetwork2 and collections (5.0.0) - #459

Merged
lduchosal merged 9 commits into
masterfrom
test/thread-safety-audit-repro
Oct 24, 2026
Merged

lduchosal merged 9 commits into
masterfrom
test/thread-safety-audit-repro

Conversation

@lduchosal

Copy link
Copy Markdown
Owner

Summary

Fixes the thread-safety and mutability defects found during the audit. Each defect is first reproduced by a red test, then fixed.

IPNetwork2

  • The address, family and CIDR now live in one immutable Snapshot behind a single volatile reference. The Value setter replaces the whole network in one store, so a concurrent reader can no longer observe a network that was never assigned (new CIDR paired with the old address, for example).
  • The broadcast and hash caches now live on the snapshot, so rewriting Value invalidates them. Before, the hash was frozen in a Lazy and went stale.
  • Every reader (ToString, Contains, CompareTo, Network, Broadcast, FirstUsable, LastUsable, Usable, WildcardMask, ...) reads the snapshot once per call.
  • The IANA_* blocks and the ULA prefixes now return a copy that shares the immutable snapshot, so a caller can no longer rewrite them for the whole process.

Collections

  • IPNetworkCollection gets an enumerator of its own instead of a cursor shared by every enumeration.
  • IPNetworkCollection and IPAddressCollection reject negative indexes.

Version

The version goes to 5.0.0: PackageVersion, Version and AssemblyVersion/AssemblyFileVersion (which were still at 3.2.0.0). appveyor.yml goes to 5.0.{build}.

Breaking changes

  • GetHashCode now follows Value, as the Equals/GetHashCode contract requires. A network mutated after being added to a dictionary or a set can no longer be found there. GetHashCodeUnitTest is updated to match.
  • UniqueLocalAddress.UlaLocallyAssigned, UlaCentrallyAssigned and UlaRange are now properties instead of static readonly fields. Code compiled against the old version must be recompiled.
  • The IANA_* and ULA properties return a new instance on every call, so ReferenceEquals between two calls no longer holds.

Tests

  • net10.0: 1382/1382 pass locally (dotnet src/TestProject/bin/Debug/net10.0/TestProject.dll).
  • net48 was not run locally; it is covered by the Windows CI job.

After merge

Create the release with the tag 5.0.0. release.yml takes the published version from the tag.

🤖 Generated with Claude Code

lduchosal and others added 7 commits August 18, 2026 22:16
TDD red phase for four defects found while auditing the surroundings of
#429. These tests fail on purpose: no production code is changed here,
so this branch must not be merged or pushed to CI as it stands.

IPNetworkCollection implements IEnumerable and IEnumerator at once and
returns this from GetEnumerator, so every consumer shares one cursor:

  second foreach over the same collection  -> 0 elements instead of 4
  nested foreach over the same collection  -> 3 pairs instead of 16
  two concurrent foreach                   -> ArgumentOutOfRangeException

The first two need no concurrency at all. The concurrent case is worse
than losing elements: one thread can advance the cursor past Count while
another calls Current, which indexes out of range and throws.
IPAddressCollection already hands out a dedicated enumerator instance,
so the pattern to follow is in the codebase.

The Value setter rewrites ipaddress, family and cidr as three separate
unsynchronized writes, so a reader can pair the new CIDR with the old
address and observe 10.0.0.0/24, a network that was never assigned.

GetHashCode is memoized in a readonly Lazy built in the constructor and
never invalidated by the Value setter, so a mutated instance keeps the
hash of its former value. Equal instances then carry different hash
codes and HashSet.Contains misses them, which breaks the
Equals/GetHashCode contract. The existing deserialization tests do not
catch this because the setter runs before the Lazy is ever materialized.

The IANA blocks are process wide singletons whose Value setter is
public, so any caller can rewrite them and change what the library
reports as reserved. The test restores the singleton in a finally, and
the rest of the suite stays green: 1371 total, 7 failed, 1364 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Second sweep of the concurrency audit. Still red on purpose, still no
production code changed.

Both indexers guard only the upper bound:

    if (i >= this.Count) throw new ArgumentOutOfRangeException(nameof(i));

Nothing rejects a negative index, so it resolves to an element located
before the network and is returned silently:

    subnets[-1]                  -> 192.168.0.192/26   (parent 192.168.1.0/24)
    ListIPAddress()[-1]          -> 192.168.0.255

This is reachable without ever computing an index, because the cursor of
both collections starts at -1. Reading Current before the first
MoveNext() returns the out of range element, and a Reset() issued by
another thread mid-enumeration does the same: reproduced after a single
read, yielding 192.168.0.255/32 from a 192.168.1.0/24 enumeration.

Handing back an address outside the range instead of throwing is the
dangerous failure mode for a library used to decide whether an address
belongs to a network.

Also adds a deterministic guard on IPNetworkCollection.GetEnumerator()
returning an instance distinct from the collection. It covers the shared
cursor and its side effect: since the collection is its own enumerator,
it is also the IDisposable that foreach disposes at the end of every
loop. Harmless today because Dispose is a no-op, but it disappears once
the enumerator is separated, the way IPAddressCollection already does.

Suite: 1376 total, 12 failed, 1364 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
IPNetworkCollection implemented IEnumerable and IEnumerator at once and
returned this from GetEnumerator, so every consumer shared the single
cursor held in a field of the collection.

Without any concurrency involved, a second foreach over the same
collection yielded 0 elements instead of 4, and a nested foreach visited
3 pairs instead of 16, because the inner loop consumed the cursor of the
outer one. Concurrently, two enumerations of a 256 element collection
returned 258 elements between them instead of 512, and depending on the
interleaving one thread could advance the cursor past Count while
another called Current, which indexes out of range and throws.

GetEnumerator now returns a private Enumerator struct carrying its own
cursor, exactly as IPAddressCollection already does. The public
IEnumerator members of the collection are kept so the change is not
breaking; they are legacy surface that no longer takes part in foreach.

This also removes a side effect of the collection being its own
enumerator: foreach disposes the enumerator when it ends, which meant
disposing the collection itself on every loop. Harmless while Dispose is
a no-op, gone now.

Tests: the four red tests turn green, including the structural guard
that GetEnumerator must not return the collection. Ran the group 10
times in a row to confirm the concurrent one does not flake. Suite goes
from 12 to 8 failures, the remaining 8 being the defects not addressed
here: the unchecked negative index in both indexers, the non-atomic
Value setter, the stale hash code and the rewritable IANA singletons.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Both indexers guarded only the upper bound:

    if (i >= this.Count) throw new ArgumentOutOfRangeException(nameof(i));

Nothing rejected a negative index, so it resolved to an element located
before the network and was returned silently:

    subnets[-1]         -> 192.168.0.192/26   (parent 192.168.1.0/24)
    ListIPAddress()[-1] -> 192.168.0.255

This was reachable without ever computing an index, because the cursor
of both collections starts at -1. Reading Current before the first
MoveNext returned the out of range element, and a Reset issued by
another thread mid-enumeration did the same, reproduced after a single
read. For a library used to decide whether an address belongs to a
range, handing back an element outside that range instead of throwing is
the dangerous failure mode.

The guard now covers both bounds, and the exception documentation says
so.

BEHAVIOUR CHANGE, worth a note in the release notes: reading Current
before the first MoveNext, or after Reset, now throws
ArgumentOutOfRangeException instead of returning an element outside the
network. The BCL treats Current in that state as undefined and its
collections throw, so this aligns with the platform, but code relying on
the old return value will now see an exception.

Six existing tests asserted the old behaviour and were updated, since
each of them read Current with the cursor at -1:

  TestEnumeratorCurrent, TestEnumeratorCurrentOor,
  Test_ipv6_EnumeratorCurrent, Test_ipv6_EnumeratorCurrentOor
    Assert.IsNotNull(ips.Current) before the first MoveNext, now
    asserting the throw.

  TestIterateIPAddress
    read Current through the collection after a foreach; since foreach
    now uses a separate enumerator the collection cursor is still at -1.

  TestReset1
    compared two out of bounds reads of Current, which never exercised
    Reset. It now moves, reads, resets, moves and reads again, so it
    actually tests that Reset returns to the first element.

Suite: 1376 total, 4 failed, 1372 passed. The 4 remaining failures are
the defects not addressed here: the non-atomic Value setter, the stale
hash code and the rewritable IANA singletons.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…tons

Hold the address, family and CIDR in one immutable Snapshot behind a
single volatile reference, so the Value setter replaces the whole
network in one store and every reader sees a network that was actually
assigned. The broadcast and hash caches live on the snapshot and are
dropped with it, so they can no longer go stale.

The IANA_* blocks and the ULA prefixes now hand out a copy sharing the
immutable snapshot, so callers can no longer rewrite them for the whole
process.

Bump the version to 5.0.0 (AssemblyVersion 5.0.0.0).

BREAKING CHANGE: GetHashCode now follows Value, as the Equals/GetHashCode
contract requires; a network mutated after being added to a dictionary
or a set can no longer be found there.
UniqueLocalAddress.UlaLocallyAssigned, UlaCentrallyAssigned and UlaRange
are now properties instead of static readonly fields, which breaks
binary compatibility.
The IANA_* properties and the ULA properties return a new instance on
every call, so reference equality between two calls no longer holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@coveralls

coveralls commented Oct 24, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 1047

Coverage increased (+0.1%) to 94.172%

Details

  • Coverage increased (+0.1%) from the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 2471
Covered Lines: 2327
Line Coverage: 94.17%
Coverage Strength: 625520.08 hits per line

💛 - Coveralls

…, IDE0017)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover every IANA_* property now that IsIANAReserved no longer goes
through them, and the Reset of the new collection enumerator. Drop the
now unused InternalNetmask, and the zero-hash branch that no test could
reach: a network hashing to zero is simply recomputed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@lduchosal
lduchosal merged commit a2cce77 into master Oct 24, 2026
15 of 16 checks passed
@lduchosal
lduchosal deleted the test/thread-safety-audit-repro branch October 24, 2026 16:01

This branch had an error being deployed

1 failed deployment
github-pages — 697be281 Deployed Oct 24, 2026 by lduchosal via Generate and publish the docs #264
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants