Files
bitchat/bitchatTests/Noise/NoiseCoverageTests.swift
T
0152196ac2 Deflake CI, and make the flake class unrepeatable (#1491)
* Deflake two iOS-sim CI tests with unbounded timing assumptions

Both failed on main-adjacent CI runs during this session's PRs. Neither
was a product bug; both asserted things about real time that a loaded
runner is under no obligation to honour.

**NetworkReachabilityGateTests: a wall-clock upper bound.**
test_monitor_duplicateUpdatesDoNotPostponeOfflineCommit slept 500ms for
real, then asserted total elapsed time was under 1.4s to prove a duplicate
mid-window had not restarted the 1.0s debounce. One CI run took 3.75s. No
wall-clock bound can separate "deadline preserved" from "runner is slow",
because Task.sleep and the asyncAfter flush are both real time and neither
is bounded above.

The deadline property was already covered deterministically one level
down: test_debounce_duplicateObservationsPreservePendingDeadline drives
ReachabilityDebounce with injected timestamps and checks pendingRemaining
directly. So the monitor test now asserts only what needs a real monitor —
that a duplicate still yields exactly one committed false through the
debounce — with an injected clock for the arithmetic and a generous
liveness budget. Renamed to say what it actually checks. No coverage lost,
and it runs in 0.14s instead of ~3.8s because the real sleep is gone.

**NoiseEncryptionServiceTests: injected timeouts that also arm during
setup.** #1483 diagnosed and fixed exactly this in the quarantine-restore
test, but two sibling tests kept the shape. Their injected
ordinaryResponderHandshakeTimeout (0.04 and 0.06) also arms during the
establishSessions setup handshake, where bob is the responder — so a
preempted runner fires it mid-setup, tears down the half-open responder,
and message 3 gets answered as a fresh initiation. The CI failure named
setup's own `#expect(finalMessage == nil)` seeing a 96-byte message 2,
which is precisely the signature #1483 recorded.

Raised both to 1.0s, matching #1483's remedy: the scenarios still need the
responder timeout to fire, and it still does, just with room for setup to
complete first. Thin 1-second waitUntil budgets in the file now use the
shared TestConstants.longTimeout; every one of them backs a positive
assertion, so waitUntil still returns the moment the condition holds and
nothing gets slower in the passing case.

No assertion weakened in either file. Verified 3x sequentially and 3x with
all 18 cores saturated.

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

* Raise two more starvation-prone test deadlines

Both surfaced on the CI runs for this PR and #1487, both in tests neither
PR touches, both the same shape as the two already fixed here: a deadline
sized for the work rather than for a runner executing many suites at once.

VoiceNotePlaybackControllerTests waited 5s for a @MainActor Task that
playback schedules for the session acquire and its failure path. When that
Task is not scheduled in time the helper reports *two* failures — the wait,
and the `!isPlaying` the un-run failure path has not reset yet — which
reads like a playback bug rather than a starved scheduler. That is exactly
what CI showed.

GeoRelayDirectoryTests waited 10s for work the directory runs in
Task.detached(priority: .utility); utility priority competes with every
other suite. The retry-scheduling case timed out at exactly 10.06s with the
retry never scheduled, reading like a missing retry rather than a starved
background task.

Raised to 30s each with the reasoning recorded at the helper. Both helpers
return as soon as their condition holds, so nothing slows down when tests
pass — only the genuine-failure case takes longer to report.

Verified 3x with all cores saturated: both suites clean.

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

* Make the flake class unrepeatable, not just fixed

Raising four deadlines fixed the four tests that happened to fire. The
class was still there: fourteen separate waitUntil helpers, most defaulting
to 1.0s, plus wait call sites with literal budgets. The fifth instance
would have landed the same way, on someone else's unrelated PR.

The rule, now written down in TestConstants.settleTimeout: **a wait
deadline is not a latency budget.** It exists so a genuine hang eventually
fails the suite, so size it for the worst-case scheduler, never for how
long the operation should take. Waits return as soon as their condition
holds, so a generous deadline is free in the passing case and only extends
genuine failures.

- Every wait helper now defaults to TestConstants.settleTimeout (30s), and
  the literal wait call sites below the floor were converted too — sixteen
  sites across ten files.
- TestTimingHygieneTests enforces it by scanning the test sources: wait
  defaults and wait call sites must be at least minimumSettleTimeout, and
  no test may assert an upper bound on elapsed wall-clock time (the
  assertion that started this, which cannot separate correct behaviour from
  a slow machine).
- Both rules waive per line with "test-timing-ok: <reason>", accepted on
  the line or in the comment block above it so the reason has room to be a
  sentence. One legitimate use so far: a NEGATIVE wait in NoiseCoverageTests
  asserting a promotion has *not* completed within 50ms, where a long
  deadline would only make the suite slow while still passing.

Injected production timeouts are deliberately not matched — the Noise
handshake timeouts are the behaviour under test, and short values are
correct there.

Verified the guard actually fails: a canary file with both banned shapes
was flagged with file and line, and the suite went green again once it was
removed. Full suite passes with all 18 cores saturated.

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

* Close the guard's blind spot: named short timeouts

A fifth flake landed on CI while the first guard was in review —
GossipSyncBoardTests timing out at 1.03s — and the guard did not catch it,
because the deadline was `TestConstants.shortTimeout` rather than a
literal. A literals-only scan cannot see a short value behind a symbol,
which is the more common way it is written: 81 wait sites used
shortTimeout (1s) or defaultTimeout (5s), every one of them below the
floor.

Rather than guess which of those were safe to raise, all 81 were converted
and the suite timed. Runtime went 15s -> 72s, which located the genuine
negative waits precisely: ten tests that assert something does *not*
happen and therefore always run their deadline out. Measurement instead of
a heuristic, since a mis-guess in either direction is invisible — too
short reintroduces the flake, too long silently costs a minute a run.

Those 28 sites now use `TestConstants.negativeWaitWindow`, a named
constant whose doc explains the inverted reasoning: for a negative wait,
starvation can only make the assertion *more* likely to hold, so short is
correct, and the name states the polarity instead of leaving a bare
literal that reads like the mistake. Suite is back to 15.3s.

The guard now also rejects `timeout: TestConstants.shortTimeout` and
`defaultTimeout`, while accepting `negativeWaitWindow` by name.

Re-verified with a canary carrying every banned shape — literal default,
both named constants, and an elapsed-time upper bound. All four were
flagged with file and line; the suite went green again on removal.

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

* Delete shortTimeout now that nothing may use it

The hygiene guard bans `TestConstants.shortTimeout` at every wait site
and the last users were converted, so Periphery correctly flagged the
constant itself as dead and failed CI. Remove it from both TestConstants
copies; the banned-name entry stays so the symbol cannot quietly return.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 23:45:20 +01:00

1070 lines
39 KiB
Swift

import CryptoKit
import Foundation
import Testing
import BitFoundation
@testable import bitchat
@Suite("Noise Coverage Tests", .serialized)
struct NoiseCoverageTests {
private let keychain = MockKeychain()
private let aliceStaticKey = Curve25519.KeyAgreement.PrivateKey()
private let bobStaticKey = Curve25519.KeyAgreement.PrivateKey()
private let charlieStaticKey = Curve25519.KeyAgreement.PrivateKey()
// Manager test dictionaries are keyed by the remote peer. Keep the
// historical names, but derive each wire ID from the static key that the
// corresponding manager authenticates during the handshake.
private var alicePeerID: PeerID {
PeerID(publicKey: bobStaticKey.publicKey.rawRepresentation)
}
private var bobPeerID: PeerID {
PeerID(publicKey: aliceStaticKey.publicKey.rawRepresentation)
}
private let charliePeerID = PeerID(str: "fedcba9876543210")
@Test("Protocol metadata and handshake patterns expose expected values")
func protocolMetadataAndHandshakePatterns() {
let ikName = NoiseProtocolName(pattern: NoisePattern.IK.patternName)
#expect(ikName.pattern == "IK")
#expect(ikName.dh == "25519")
#expect(ikName.cipher == "ChaChaPoly")
#expect(ikName.hash == "SHA256")
#expect(ikName.fullName == "Noise_IK_25519_ChaChaPoly_SHA256")
#expect(NoisePattern.XX.patternName == "XX")
#expect(NoisePattern.IK.patternName == "IK")
#expect(NoisePattern.NK.patternName == "NK")
let ikPatterns = NoisePattern.IK.messagePatterns
#expect(ikPatterns.count == 2)
#expect(ikPatterns[0] == [.e, .es, .s, .ss])
#expect(ikPatterns[1] == [.e, .ee, .se])
let nkPatterns = NoisePattern.NK.messagePatterns
#expect(nkPatterns.count == 2)
#expect(nkPatterns[0] == [.e, .es])
#expect(nkPatterns[1] == [.e, .ee])
}
@Test("Symmetric state supports long protocol names and mixKeyAndHash")
func symmetricStateLongNameAndMixKeyAndHash() {
let longName = String(repeating: "NoiseProtocol_", count: 3)
let symmetricState = NoiseSymmetricState(protocolName: longName)
let initialHash = symmetricState.getHandshakeHash()
#expect(initialHash.count == 32)
#expect(!symmetricState.hasCipherKey())
symmetricState.mixKeyAndHash(Data("input-key-material".utf8))
#expect(symmetricState.hasCipherKey())
#expect(symmetricState.getHandshakeHash() != initialHash)
}
@Test("Cipher state rejects duplicate and stale extracted nonces")
func cipherStateRejectsDuplicateAndStaleNonces() throws {
let key = SymmetricKey(size: .bits256)
let receiver = NoiseCipherState(key: key, useExtractedNonce: true)
let initialPayload = try makeExtractedNoncePayload(
key: key,
nonce: 0,
plaintext: Data("nonce-0".utf8)
)
let initialPlaintext = try receiver.decrypt(ciphertext: initialPayload)
#expect(initialPlaintext == Data("nonce-0".utf8))
#expect(throws: (any Error).self) {
try receiver.decrypt(ciphertext: initialPayload)
}
for nonce in 1...1024 {
let payload = try makeExtractedNoncePayload(
key: key,
nonce: UInt64(nonce),
plaintext: Data("nonce-\(nonce)".utf8)
)
let plaintext = try receiver.decrypt(ciphertext: payload)
#expect(plaintext == Data("nonce-\(nonce)".utf8))
}
#expect(throws: (any Error).self) {
try receiver.decrypt(ciphertext: initialPayload)
}
}
@Test("Cipher state handles large nonce jumps and associated-data mismatches")
func cipherStateHandlesLargeJumpsAndAADMismatch() throws {
let key = SymmetricKey(size: .bits256)
let extractedReceiver = NoiseCipherState(key: key, useExtractedNonce: true)
let jumped = try makeExtractedNoncePayload(
key: key,
nonce: 1500,
plaintext: Data("future".utf8)
)
let slightlyOlder = try makeExtractedNoncePayload(
key: key,
nonce: 1499,
plaintext: Data("older".utf8)
)
let tooOld = try makeExtractedNoncePayload(
key: key,
nonce: 100,
plaintext: Data("ancient".utf8)
)
#expect(try extractedReceiver.decrypt(ciphertext: jumped) == Data("future".utf8))
#expect(try extractedReceiver.decrypt(ciphertext: slightlyOlder) == Data("older".utf8))
#expect(throws: (any Error).self) {
try extractedReceiver.decrypt(ciphertext: tooOld)
}
let sender = NoiseCipherState(key: key)
let receiver = NoiseCipherState(key: key)
let plaintext = Data("associated-data".utf8)
let aad = Data("good-aad".utf8)
let ciphertext = try sender.encrypt(plaintext: plaintext, associatedData: aad)
#expect(throws: (any Error).self) {
try receiver.decrypt(ciphertext: ciphertext, associatedData: Data("bad-aad".utf8))
}
#expect(try receiver.decrypt(ciphertext: ciphertext, associatedData: aad) == plaintext)
#expect(throws: (any Error).self) {
try receiver.decrypt(ciphertext: Data(repeating: 0xAA, count: 15))
}
}
@Test("Cipher state covers nonce guard rails and extracted payload bounds")
func cipherStateCoversNonceGuardRailsAndExtractedPayloadBounds() throws {
let uninitializedCipher = NoiseCipherState()
#expect(throws: NoiseError.uninitializedCipher) {
try uninitializedCipher.encrypt(plaintext: Data("missing-key".utf8))
}
#expect(throws: NoiseError.uninitializedCipher) {
try uninitializedCipher.decrypt(ciphertext: Data(repeating: 0x00, count: 16))
}
#expect(try uninitializedCipher.extractNonceFromCiphertextPayloadForTesting(Data([0x00, 0x01, 0x02])) == nil)
let key = SymmetricKey(size: .bits256)
let highNonceCipher = NoiseCipherState(key: key)
highNonceCipher.setNonceForTesting(1_000_000_001)
#expect(throws: Never.self) {
_ = try highNonceCipher.encrypt(plaintext: Data("high-nonce".utf8))
}
let exhaustedCipher = NoiseCipherState(key: key)
exhaustedCipher.setNonceForTesting(UInt64(UInt32.max))
#expect(throws: NoiseError.nonceExceeded) {
try exhaustedCipher.encrypt(plaintext: Data("nonce-limit".utf8))
}
}
@Test("Handshake validation rejects malformed keys and messages")
func handshakeValidationRejectsMalformedInputs() throws {
let responder = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: bobStaticKey
)
#expect(throws: (any Error).self) {
try responder.readMessage(Data(repeating: 0x00, count: 31))
}
let invalidKeys = [
Data(),
Data(repeating: 0x00, count: 32),
Data([0x01] + Array(repeating: 0x00, count: 31)),
Data(repeating: 0xFF, count: 32)
]
for invalidKey in invalidKeys {
#expect(throws: (any Error).self) {
_ = try NoiseHandshakeState.validatePublicKey(invalidKey)
}
}
let valid = aliceStaticKey.publicKey.rawRepresentation
let roundTripped = try NoiseHandshakeState.validatePublicKey(valid)
#expect(roundTripped.rawRepresentation == valid)
let initiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responderForTamper = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: bobStaticKey
)
let message1 = try initiator.writeMessage()
_ = try responderForTamper.readMessage(message1)
var message2 = try responderForTamper.writeMessage()
message2[40] ^= 0x01
#expect(throws: (any Error).self) {
try initiator.readMessage(message2)
}
}
@Test("Handshake readers reject invalid ephemeral and truncated static payloads")
func handshakeReadersRejectInvalidEphemeralAndTruncatedStaticPayloads() throws {
let invalidEphemeralResponder = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: bobStaticKey
)
#expect(throws: NoiseError.invalidMessage) {
try invalidEphemeralResponder.readMessage(Data(repeating: 0x00, count: 32))
}
let truncatedStaticInitiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
_ = try truncatedStaticInitiator.writeMessage()
let responderEphemeralOnly = Curve25519.KeyAgreement.PrivateKey().publicKey.rawRepresentation
#expect(throws: NoiseError.invalidMessage) {
try truncatedStaticInitiator.readMessage(responderEphemeralOnly)
}
}
@Test("IK handshake completes and supports transport messages")
func ikHandshakeCompletesAndSupportsTransportMessages() throws {
let initiator = NoiseHandshakeState(
role: .initiator,
pattern: .IK,
keychain: keychain,
localStaticKey: aliceStaticKey,
remoteStaticKey: bobStaticKey.publicKey
)
let responder = NoiseHandshakeState(
role: .responder,
pattern: .IK,
keychain: keychain,
localStaticKey: bobStaticKey
)
let outboundPayload = Data("ik-outbound".utf8)
let returnPayload = Data("ik-return".utf8)
let message1 = try initiator.writeMessage(payload: outboundPayload)
#expect(try responder.readMessage(message1) == outboundPayload)
let message2 = try responder.writeMessage(payload: returnPayload)
#expect(try initiator.readMessage(message2) == returnPayload)
#expect(initiator.isHandshakeComplete())
#expect(responder.isHandshakeComplete())
let (initiatorSend, initiatorReceive, initiatorHash) = try initiator.getTransportCiphers(
useExtractedNonce: true
)
let (responderSend, responderReceive, responderHash) = try responder.getTransportCiphers(
useExtractedNonce: true
)
#expect(initiatorHash == responderHash)
let clientCiphertext = try initiatorSend.encrypt(plaintext: Data("ik-transport".utf8))
#expect(try responderReceive.decrypt(ciphertext: clientCiphertext) == Data("ik-transport".utf8))
let serverCiphertext = try responderSend.encrypt(plaintext: Data("ik-response".utf8))
#expect(try initiatorReceive.decrypt(ciphertext: serverCiphertext) == Data("ik-response".utf8))
}
@Test("NK handshake requires a responder static key and supports transport messages")
func nkHandshakeRequiresStaticAndSupportsTransportMessages() throws {
let missingStaticInitiator = NoiseHandshakeState(
role: .initiator,
pattern: .NK,
keychain: keychain,
localStaticKey: aliceStaticKey
)
#expect(throws: (any Error).self) {
try missingStaticInitiator.writeMessage()
}
let initiator = NoiseHandshakeState(
role: .initiator,
pattern: .NK,
keychain: keychain,
localStaticKey: aliceStaticKey,
remoteStaticKey: bobStaticKey.publicKey
)
let responder = NoiseHandshakeState(
role: .responder,
pattern: .NK,
keychain: keychain,
localStaticKey: bobStaticKey
)
let outboundPayload = Data("nk-outbound".utf8)
let returnPayload = Data("nk-return".utf8)
let message1 = try initiator.writeMessage(payload: outboundPayload)
#expect(try responder.readMessage(message1) == outboundPayload)
let message2 = try responder.writeMessage(payload: returnPayload)
#expect(try initiator.readMessage(message2) == returnPayload)
#expect(initiator.isHandshakeComplete())
#expect(responder.isHandshakeComplete())
let (initiatorSend, initiatorReceive, initiatorHash) = try initiator.getTransportCiphers(
useExtractedNonce: true
)
let (responderSend, responderReceive, responderHash) = try responder.getTransportCiphers(
useExtractedNonce: true
)
#expect(initiatorHash == responderHash)
let clientCiphertext = try initiatorSend.encrypt(plaintext: Data("nk-transport".utf8))
#expect(try responderReceive.decrypt(ciphertext: clientCiphertext) == Data("nk-transport".utf8))
let serverCiphertext = try responderSend.encrypt(plaintext: Data("nk-response".utf8))
#expect(try initiatorReceive.decrypt(ciphertext: serverCiphertext) == Data("nk-response".utf8))
}
@Test("Responder-side NK writes require peer ephemeral input")
func responderWritesRequirePeerEphemeralInput() {
let nkResponder = NoiseHandshakeState(
role: .responder,
pattern: .NK,
keychain: keychain,
localStaticKey: bobStaticKey
)
#expect(throws: NoiseError.missingKeys) {
try nkResponder.writeMessage()
}
}
@Test("Direct DH helpers reject missing keys across all patterns")
func directDHHelpersRejectMissingKeysAcrossAllPatterns() throws {
let eeState = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
#expect(throws: NoiseError.missingKeys) {
try eeState.performDHOperationForTesting(.ee)
}
let esInitiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
#expect(throws: NoiseError.missingKeys) {
try esInitiator.performDHOperationForTesting(.es)
}
let esResponder = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: nil
)
#expect(throws: NoiseError.missingKeys) {
try esResponder.performDHOperationForTesting(.es)
}
let seInitiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: nil
)
#expect(throws: NoiseError.missingKeys) {
try seInitiator.performDHOperationForTesting(.se)
}
let seResponder = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: bobStaticKey
)
#expect(throws: NoiseError.missingKeys) {
try seResponder.performDHOperationForTesting(.se)
}
let ssState = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: nil
)
#expect(throws: NoiseError.missingKeys) {
try ssState.performDHOperationForTesting(.ss)
}
#expect(throws: Never.self) {
try eeState.performDHOperationForTesting(.e)
try eeState.performDHOperationForTesting(.s)
}
}
@Test("Prepared handshake writers cover remaining missing-key branches")
func preparedHandshakeWritersCoverRemainingMissingKeyBranches() {
let eeResponder = NoiseHandshakeState(
role: .responder,
pattern: .NK,
keychain: keychain,
localStaticKey: bobStaticKey
)
eeResponder.setCurrentPatternForTesting(1)
#expect(throws: NoiseError.missingKeys) {
try eeResponder.writeMessage()
}
let seInitiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
seInitiator.setCurrentPatternForTesting(2)
#expect(throws: NoiseError.missingKeys) {
try seInitiator.writeMessage()
}
let seResponder = NoiseHandshakeState(
role: .responder,
pattern: .IK,
keychain: keychain,
localStaticKey: bobStaticKey
)
seResponder.setCurrentPatternForTesting(1)
seResponder.setRemoteEphemeralPublicKeyForTesting(Curve25519.KeyAgreement.PrivateKey().publicKey)
#expect(throws: NoiseError.missingKeys) {
try seResponder.writeMessage()
}
}
@Test("Completed handshakes reject additional reads and writes")
func completedHandshakesRejectAdditionalReadsAndWrites() throws {
let initiator = NoiseHandshakeState(
role: .initiator,
pattern: .IK,
keychain: keychain,
localStaticKey: aliceStaticKey,
remoteStaticKey: bobStaticKey.publicKey
)
let responder = NoiseHandshakeState(
role: .responder,
pattern: .IK,
keychain: keychain,
localStaticKey: bobStaticKey
)
let message1 = try initiator.writeMessage(payload: Data("first".utf8))
_ = try responder.readMessage(message1)
let message2 = try responder.writeMessage(payload: Data("second".utf8))
_ = try initiator.readMessage(message2)
#expect(throws: NoiseError.handshakeComplete) {
try initiator.writeMessage()
}
#expect(throws: NoiseError.handshakeComplete) {
try responder.readMessage(message1)
}
}
@Test("XX final message requires a local static key")
func xxFinalMessageRequiresLocalStaticKey() throws {
let initiator = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: nil
)
let responder = NoiseHandshakeState(
role: .responder,
pattern: .XX,
keychain: keychain,
localStaticKey: bobStaticKey
)
let message1 = try initiator.writeMessage()
_ = try responder.readMessage(message1)
let message2 = try responder.writeMessage()
_ = try initiator.readMessage(message2)
#expect(throws: (any Error).self) {
try initiator.writeMessage()
}
}
@Test("Responder start handshake is empty and transport ciphers require completion")
func responderStartHandshakeAndIncompleteTransportCiphers() throws {
let responderSession = NoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
localStaticKey: bobStaticKey
)
let incompleteHandshake = NoiseHandshakeState(
role: .initiator,
pattern: .XX,
keychain: keychain,
localStaticKey: aliceStaticKey
)
#expect(try responderSession.startHandshake().isEmpty)
#expect(responderSession.getState() == .handshaking)
#expect(throws: (any Error).self) {
_ = try incompleteHandshake.getTransportCiphers(useExtractedNonce: true)
}
}
@Test("Session manager callbacks establish and failed handshakes clean up state")
func sessionManagerCallbacksAndFailureCleanup() async throws {
let establishedRecorder = SessionCallbackRecorder()
let aliceManager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
aliceManager.onSessionEstablished = establishedRecorder.recordEstablished(
peerID:remoteKey:sessionGeneration:
)
bobManager.onSessionEstablished = establishedRecorder.recordEstablished(
peerID:remoteKey:sessionGeneration:
)
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
let didEstablish = await TestHelpers.waitUntil(
{ establishedRecorder.establishedCount == 2 },
timeout: 5.0
)
#expect(didEstablish)
#expect(establishedRecorder.establishedPeerIDs.contains(alicePeerID))
#expect(establishedRecorder.establishedPeerIDs.contains(bobPeerID))
let failureRecorder = SessionCallbackRecorder()
let failingManager = NoiseSessionManager(localStaticKey: charlieStaticKey, keychain: keychain)
failingManager.onSessionFailed = failureRecorder.recordFailure(peerID:error:)
#expect(throws: (any Error).self) {
try failingManager.handleIncomingHandshake(
from: charliePeerID,
message: Data(repeating: 0x00, count: 31)
)
}
let didFail = await TestHelpers.waitUntil(
{ failureRecorder.failureCount == 1 },
timeout: 5.0
)
#expect(didFail)
#expect(failingManager.getSession(for: charliePeerID) == nil)
}
@Test("Session manager cleans up initiator sessions after start-handshake failures")
func sessionManagerCleansUpInitiatorSessionsAfterStartHandshakeFailures() {
let manager = NoiseSessionManager(
localStaticKey: aliceStaticKey,
keychain: keychain,
sessionFactory: { peerID, role in
FailingNoiseSession(
peerID: peerID,
role: role,
keychain: self.keychain,
localStaticKey: self.aliceStaticKey
)
}
)
#expect(throws: FailingNoiseSession.Error.synthetic) {
try manager.initiateHandshake(with: alicePeerID)
}
#expect(manager.getSession(for: alicePeerID) == nil)
}
@Test("Session manager rekeys established sessions and replaces partial handshakes")
func sessionManagerRekeysAndReplacesSessions() throws {
let manager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
#expect(throws: NoiseSessionError.sessionNotFound) {
try manager.encrypt(Data("missing".utf8), for: alicePeerID)
}
#expect(throws: NoiseSessionError.sessionNotFound) {
try manager.decrypt(Data("missing".utf8), from: alicePeerID)
}
let initialHandshake = try manager.initiateHandshake(with: alicePeerID)
#expect(!initialHandshake.isEmpty)
let firstSession = try #require(manager.getSession(for: alicePeerID))
let restartedHandshake = try manager.initiateHandshake(with: alicePeerID)
let restartedSession = try #require(manager.getSession(for: alicePeerID))
#expect(!restartedHandshake.isEmpty)
#expect(restartedSession !== firstSession)
let restartedInitiator = NoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: bobStaticKey
)
let replacementMessage = try restartedInitiator.startHandshake()
let replacementResponse = try manager.handleIncomingHandshake(
from: alicePeerID,
message: replacementMessage
)
let replacementSession = try #require(manager.getSession(for: alicePeerID))
let localPeerID = PeerID(
publicKey: aliceStaticKey.publicKey.rawRepresentation
)
if localPeerID < alicePeerID {
#expect(replacementResponse == nil)
#expect(replacementSession === restartedSession)
} else {
#expect(replacementResponse != nil)
#expect(replacementSession !== restartedSession)
}
let aliceManager = NoiseSessionManager(localStaticKey: aliceStaticKey, keychain: keychain)
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
let establishedSession = try #require(
aliceManager.getSession(for: alicePeerID) as? SecureNoiseSession
)
establishedSession.setMessageCountForTesting(
UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
)
let sessionsNeedingRekey = aliceManager.getSessionsNeedingRekey()
#expect(sessionsNeedingRekey.contains { $0.peerID == alicePeerID && $0.needsRekey })
#expect(throws: NoiseSessionError.alreadyEstablished) {
try aliceManager.initiateHandshake(with: alicePeerID)
}
let rekeyInitiation = try aliceManager.initiateRekey(for: alicePeerID)
let rekeyHandshake = try #require(
aliceManager.claimHandshakeInitiation(
rekeyInitiation,
for: alicePeerID
)
)
#expect(!rekeyHandshake.isEmpty)
let rekeyedSession = try #require(aliceManager.getSession(for: alicePeerID))
#expect(rekeyedSession !== establishedSession)
#expect(rekeyedSession.getState() == .handshaking)
}
@Test("A stale decrypt generation cannot commit across session promotion")
func staleDecryptGenerationCannotCommitAcrossPromotion() throws {
let aliceManager = NoiseSessionManager(
localStaticKey: aliceStaticKey,
keychain: keychain,
recentInitiatorCompletionGracePeriod: 0,
sessionFactory: { peerID, role in
BlockingDecryptNoiseSession(
peerID: peerID,
role: role,
keychain: self.keychain,
localStaticKey: self.aliceStaticKey
)
}
)
let bobManager = NoiseSessionManager(localStaticKey: bobStaticKey, keychain: keychain)
try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager)
let oldSession = try #require(
aliceManager.getSession(for: alicePeerID) as? BlockingDecryptNoiseSession
)
let oldGeneration = try #require(aliceManager.sessionGeneration(for: alicePeerID))
// Prepare a fully authenticated responder candidate without promoting
// it yet. Its final XX message is the exact operation that replaces
// the old `sessions[peerID]` entry.
let replacementInitiator = NoiseSession(
peerID: bobPeerID,
role: .initiator,
keychain: keychain,
localStaticKey: bobStaticKey
)
let message1 = try replacementInitiator.startHandshake()
let message2 = try #require(
try aliceManager.handleIncomingHandshake(from: alicePeerID, message: message1)
)
let message3 = try #require(try replacementInitiator.processHandshakeMessage(message2))
let ciphertext = try bobManager.encrypt(Data("old session".utf8), for: bobPeerID)
oldSession.pauseNextDecrypt()
let decryptResult = ConcurrentTestResult<(plaintext: Data, sessionGeneration: UUID)>()
var promotionResultForCleanup: ConcurrentTestResult<Data?>?
defer {
// A failed startup requirement must not strand a late thread in
// the blocking test double after the test has returned.
oldSession.resumeDecrypt()
_ = decryptResult.wait(timeout: TestConstants.settleTimeout)
if let promotionResultForCleanup {
_ = promotionResultForCleanup.wait(timeout: TestConstants.settleTimeout)
}
}
let decryptThread = Thread {
decryptResult.capture {
try aliceManager.decryptWithSessionGeneration(ciphertext, from: self.alicePeerID)
}
}
decryptThread.name = "NoiseCoverageTests.staleDecrypt.decrypt"
decryptThread.qualityOfService = .userInitiated
decryptThread.start()
try #require(oldSession.waitForDecryptStart(timeout: 5))
let promotionStarted = DispatchSemaphore(value: 0)
let promotionResult = ConcurrentTestResult<Data?>()
promotionResultForCleanup = promotionResult
let promotionThread = Thread {
promotionStarted.signal()
promotionResult.capture {
try aliceManager.handleIncomingHandshake(from: self.alicePeerID, message: message3)
}
}
promotionThread.name = "NoiseCoverageTests.staleDecrypt.promote"
promotionThread.qualityOfService = .userInitiated
promotionThread.start()
try #require(promotionStarted.wait(timeout: .now() + TestConstants.settleTimeout) == .success)
#expect(
// test-timing-ok: a NEGATIVE wait — it asserts the promotion has
// NOT completed yet, so a long deadline would only make the suite
// slow while still passing. A starved runner can only make this
// more likely to hold, never less.
promotionResult.wait(timeout: 0.05) == nil,
"Promotion must wait for the exact decrypting-session lease"
)
oldSession.resumeDecrypt()
let decrypted = try #require(decryptResult.wait(timeout: TestConstants.settleTimeout)).get()
_ = try #require(promotionResult.wait(timeout: TestConstants.settleTimeout)).get()
#expect(decrypted.plaintext == Data("old session".utf8))
#expect(decrypted.sessionGeneration == oldGeneration)
#expect(aliceManager.sessionGeneration(for: alicePeerID) != oldGeneration)
#expect(throws: NoiseEncryptionError.sessionNotEstablished) {
try aliceManager.encrypt(
Data("stale send".utf8),
for: alicePeerID,
expectedSessionGeneration: oldGeneration
)
}
var staleCommitRan = false
let staleCommit = aliceManager.withCurrentSessionGeneration(
for: alicePeerID,
expected: decrypted.sessionGeneration
) {
staleCommitRan = true
return true
}
#expect(staleCommit == nil)
#expect(!staleCommitRan)
}
@Test("Secure noise sessions enforce limits and renegotiation thresholds")
func secureNoiseSessionsEnforceLimitsAndThresholds() throws {
let initiator = SecureNoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
localStaticKey: bobStaticKey
)
try establishSessions(initiator: initiator, responder: responder)
responder.setMessageCountForTesting(0)
responder.setLastActivityTimeForTesting(Date())
#expect(!responder.needsRenegotiation())
responder.setMessageCountForTesting(
UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9)
)
#expect(responder.needsRenegotiation())
responder.setMessageCountForTesting(0)
responder.setLastActivityTimeForTesting(
Date().addingTimeInterval(-(NoiseSecurityConstants.sessionTimeout + 1))
)
#expect(responder.needsRenegotiation())
initiator.setMessageCountForTesting(NoiseSecurityConstants.maxMessagesPerSession)
#expect(throws: (any Error).self) {
try initiator.encrypt(Data("exhausted".utf8))
}
initiator.setMessageCountForTesting(0)
#expect(throws: (any Error).self) {
try initiator.encrypt(Data(repeating: 0xAB, count: NoiseSecurityConstants.maxMessageSize + 1))
}
responder.setLastActivityTimeForTesting(Date())
#expect(throws: (any Error).self) {
try responder.decrypt(
Data(repeating: 0xCD, count: NoiseSecurityConstants.maxMessageSize + 1)
)
}
let transportCiphertext = try initiator.encrypt(Data("secure-session".utf8))
#expect(try responder.decrypt(transportCiphertext) == Data("secure-session".utf8))
}
@Test("Secure noise sessions expire based on session start time")
func secureNoiseSessionsExpireBasedOnSessionStartTime() throws {
let initiator = SecureNoiseSession(
peerID: alicePeerID,
role: .initiator,
keychain: keychain,
localStaticKey: aliceStaticKey
)
let responder = SecureNoiseSession(
peerID: bobPeerID,
role: .responder,
keychain: keychain,
localStaticKey: bobStaticKey
)
try establishSessions(initiator: initiator, responder: responder)
initiator.setSessionStartTimeForTesting(
Date().addingTimeInterval(-(NoiseSecurityConstants.sessionTimeout + 1))
)
#expect(throws: (any Error).self) {
try initiator.encrypt(Data("expired".utf8))
}
responder.setSessionStartTimeForTesting(
Date().addingTimeInterval(-(NoiseSecurityConstants.sessionTimeout + 1))
)
#expect(throws: (any Error).self) {
try responder.decrypt(Data())
}
}
@Test("Rate limiter handles global message caps and per-peer resets")
func rateLimiterGlobalMessageCapAndReset() async throws {
let globalLimiter = NoiseRateLimiter()
for index in 0..<NoiseSecurityConstants.maxGlobalMessagesPerSecond {
#expect(globalLimiter.allowMessage(from: PeerID(str: "peer-\(index)")))
}
#expect(!globalLimiter.allowMessage(from: charliePeerID))
let peerLimiter = NoiseRateLimiter()
for _ in 0..<NoiseSecurityConstants.maxMessagesPerSecond {
#expect(peerLimiter.allowMessage(from: alicePeerID))
}
#expect(!peerLimiter.allowMessage(from: alicePeerID))
peerLimiter.reset(for: alicePeerID)
try await sleep(0.05)
#expect(peerLimiter.allowMessage(from: alicePeerID))
}
@Test("Cipher state decrypts high extracted nonces and rejects truncated extracted payloads")
func cipherStateDecryptsHighExtractedNoncesAndRejectsTruncatedPayloads() throws {
let key = SymmetricKey(size: .bits256)
let receiver = NoiseCipherState(key: key, useExtractedNonce: true)
let highNoncePayload = try makeExtractedNoncePayload(
key: key,
nonce: 1_000_000_001,
plaintext: Data("high-nonce".utf8)
)
#expect(try receiver.decrypt(ciphertext: highNoncePayload) == Data("high-nonce".utf8))
#expect(throws: NoiseError.invalidCiphertext) {
try receiver.decrypt(ciphertext: extractedNoncePrefix(7))
}
}
private func establishSessions(initiator: NoiseSession, responder: NoiseSession) throws {
let message1 = try initiator.startHandshake()
let response2 = try responder.processHandshakeMessage(message1)
let message2 = try #require(response2)
let response3 = try initiator.processHandshakeMessage(message2)
let message3 = try #require(response3)
let final = try responder.processHandshakeMessage(message3)
#expect(final == nil)
}
private func establishManagerSessions(
aliceManager: NoiseSessionManager,
bobManager: NoiseSessionManager
) throws {
let message1 = try aliceManager.initiateHandshake(with: alicePeerID)
let response2 = try bobManager.handleIncomingHandshake(from: bobPeerID, message: message1)
let message2 = try #require(response2)
let response3 = try aliceManager.handleIncomingHandshake(from: alicePeerID, message: message2)
let message3 = try #require(response3)
let final = try bobManager.handleIncomingHandshake(from: bobPeerID, message: message3)
#expect(final == nil)
}
private func makeExtractedNoncePayload(
key: SymmetricKey,
nonce: UInt64,
plaintext: Data,
associatedData: Data = Data()
) throws -> Data {
var fullNonce = Data(count: 12)
withUnsafeBytes(of: nonce.littleEndian) { bytes in
fullNonce.replaceSubrange(4..<12, with: bytes)
}
let sealedBox = try ChaChaPoly.seal(
plaintext,
using: key,
nonce: ChaChaPoly.Nonce(data: fullNonce),
authenticating: associatedData
)
return extractedNoncePrefix(nonce) + sealedBox.ciphertext + sealedBox.tag
}
private func extractedNoncePrefix(_ nonce: UInt64) -> Data {
withUnsafeBytes(of: nonce.bigEndian) { bytes in
Data(bytes.suffix(4))
}
}
}
private final class SessionCallbackRecorder: @unchecked Sendable {
private let lock = NSLock()
private var establishedEntries: [(PeerID, Data)] = []
private var failureEntries: [(PeerID, String)] = []
var establishedCount: Int {
lock.lock()
defer { lock.unlock() }
return establishedEntries.count
}
var failureCount: Int {
lock.lock()
defer { lock.unlock() }
return failureEntries.count
}
var establishedPeerIDs: [PeerID] {
lock.lock()
defer { lock.unlock() }
return establishedEntries.map(\.0)
}
func recordEstablished(
peerID: PeerID,
remoteKey: Curve25519.KeyAgreement.PublicKey,
sessionGeneration _: UUID
) {
lock.lock()
establishedEntries.append((peerID, remoteKey.rawRepresentation))
lock.unlock()
}
func recordFailure(peerID: PeerID, error: Error) {
lock.lock()
failureEntries.append((peerID, String(describing: error)))
lock.unlock()
}
}
private final class FailingNoiseSession: NoiseSession {
enum Error: Swift.Error {
case synthetic
}
override func startHandshake() throws -> Data {
throw Error.synthetic
}
}
private final class BlockingDecryptNoiseSession: NoiseSession, @unchecked Sendable {
private let controlLock = NSLock()
private var shouldPauseNextDecrypt = false
private let decryptStarted = DispatchSemaphore(value: 0)
private let resumeDecryptSemaphore = DispatchSemaphore(value: 0)
func pauseNextDecrypt() {
controlLock.lock()
shouldPauseNextDecrypt = true
controlLock.unlock()
}
func waitForDecryptStart(timeout: TimeInterval) -> Bool {
decryptStarted.wait(timeout: .now() + timeout) == .success
}
func resumeDecrypt() {
resumeDecryptSemaphore.signal()
}
override func decrypt(_ ciphertext: Data) throws -> Data {
controlLock.lock()
let shouldPause = shouldPauseNextDecrypt
shouldPauseNextDecrypt = false
controlLock.unlock()
if shouldPause {
decryptStarted.signal()
resumeDecryptSemaphore.wait()
}
return try super.decrypt(ciphertext)
}
}
private final class ConcurrentTestResult<Value>: @unchecked Sendable {
private let lock = NSLock()
private let completed = DispatchGroup()
private var storedResult: Result<Value, Error>?
init() {
completed.enter()
}
func capture(_ operation: () throws -> Value) {
let result = Result(catching: operation)
lock.lock()
storedResult = result
lock.unlock()
completed.leave()
}
func wait(timeout: TimeInterval) -> Result<Value, Error>? {
guard completed.wait(timeout: .now() + timeout) == .success else { return nil }
lock.lock()
defer { lock.unlock() }
return storedResult
}
}