Release 0.8.0 with replay-safe prioritized transport

This commit is contained in:
sergeych committed 2026-10-21 16:35:20 +04:00
1 parent 237d404bcd
commit 009d62a155
31 files changed
+1188 -130

No files matched your search

@@ -127,10 +127,14 @@ class AuthenticatedEnvelopeTest {
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
try {
ready.await()
withTimeout(2000) { runCatching { client.call(mutate, 1) } }
withTimeout(2000) { serverJob.join() }
assertEquals(1, withTimeout(2000) { client.call(mutate, 1) })
runCurrent()
assertTrue(attacked)
assertTrue(executions <= 1, "The replay must never execute the application operation again")
assertEquals(1, executions, "The replay must never execute the application operation again")
assertTrue(serverJob.isActive)
assertEquals(2, client.call(mutate, 2))
runCurrent()
assertEquals(2, executions)
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
}
@@ -0,0 +1,88 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import net.sergeych.crypto2.SigningSecretKey
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.*
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class ConnectionInitializationTest {
private class PolicyRejected : RemoteInterface.SecurityException("Peer rejected by policy")
private class InitializationAborted : LocalInterface.BreakConnectionException("Initialization aborted")
@Test fun serverSecurityRejectionClosesConnection() = rejectsInitialization(true, PolicyRejected())
@Test fun clientSecurityRejectionClosesConnection() = rejectsInitialization(false, PolicyRejected())
@Test fun serverBreakSubclassClosesConnection() = rejectsInitialization(true, InitializationAborted())
@Test fun clientBreakSubclassClosesConnection() = rejectsInitialization(false, InitializationAborted())
private fun rejectsInitialization(rejectOnServer: Boolean, rejection: Throwable) = runTest(timeout = 10.seconds) {
initCrypto()
val (a, b) = createTestDevice()
val serverKey = SigningSecretKey.new()
val clientKey = SigningSecretKey.new()
val clientInterface = KiloInterface<Unit>()
val serverInterface = KiloInterface<Unit>()
var policyCalled = false
var identityMatched = false
var laterHandlerCalled = false
var clientConnected = false
(if (rejectOnServer) serverInterface else clientInterface).apply {
onConnected {
identityMatched = remoteIdentity == if (rejectOnServer) clientKey.verifyingKey else serverKey.verifyingKey
policyCalled = true
throw rejection
}
onConnected { laterHandlerCalled = true }
}
val server = KiloServerConnection(serverInterface, b, Unit, serverKey)
val client = KiloClientConnection(clientInterface, a, Unit, clientKey)
val serverRun = async { runCatching { server.run() } }
val clientRun = async { runCatching { client.run { if (it) clientConnected = true } } }
try {
withTimeout(2000) { serverRun.await(); clientRun.await() }
assertTrue(policyCalled, "Initialization policy must run")
assertTrue(identityMatched, "Policy must receive the verified remote identity")
assertFalse(laterHandlerCalled, "Rejection must stop subsequent initialization handlers")
assertFalse(clientConnected, "Rejected initialization must not announce a connected client")
if (!rejectOnServer) assertSame(rejection, clientRun.await().exceptionOrNull())
val echo by command<String, String>()
assertIs<RemoteInterface.ClosedException>(runCatching { client.call(echo, "after rejection") }.exceptionOrNull())
} finally {
serverRun.cancelAndJoin()
clientRun.cancelAndJoin()
}
}
@Test fun ordinaryHandlerFailuresStillAllowInitialization() = runTest(timeout = 10.seconds) {
initCrypto()
val (a, b) = createTestDevice()
val echo by command<String, String>()
var serverInitialized = false
var clientInitialized = false
val serverInterface = KiloInterface<Unit>().apply {
onConnected { throw IllegalStateException("Nonfatal handler failure") }
onConnected { serverInitialized = true }
on(echo) { it }
}
val clientInterface = KiloInterface<Unit>().apply {
onConnected { throw IllegalStateException("Nonfatal handler failure") }
onConnected { clientInitialized = true }
}
val ready = CompletableDeferred<Unit>()
val server = KiloServerConnection(serverInterface, b, Unit)
val client = KiloClientConnection(clientInterface, a, Unit)
val serverJob = launch { server.run() }
val clientJob = launch { client.run { if (it) ready.complete(Unit) } }
try {
ready.await()
assertTrue(serverInitialized)
assertTrue(clientInitialized)
assertEquals("ok", client.call(echo, "ok"))
} finally {
serverJob.cancelAndJoin()
clientJob.cancelAndJoin()
}
}
}
@@ -0,0 +1,114 @@
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import net.sergeych.crypto2.initCrypto
import net.sergeych.kiloparsec.*
import net.sergeych.utools.pack
import net.sergeych.utools.unpack
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class OutgoingSecurityTest {
@Test fun replayedReplyLeavesWaiterForValidReply() = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<String, String>()
val (a, b) = createTestDevice()
var armed = false
var saved: UByteArray? = null
val adversary = object : Transport.Device by b {
override suspend fun send(block: UByteArray) {
val bytes = block
val decoded = unpack<Transport.Block>(bytes)
if (armed && decoded is Transport.Block.Response) {
saved?.let { b.send(pack<Transport.Block>(decoded.copy(packedResult = it))) }
saved = decoded.packedResult
}
b.send(bytes)
}
}
val ready = CompletableDeferred<Unit>()
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, adversary, Unit)
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
val sj = launch { server.run() }
val cj = launch { client.run { if (it) ready.complete(Unit) } }
try {
ready.await(); armed = true
assertEquals("first", client.call(echo, "first"))
assertEquals("second", client.call(echo, "second"))
assertTrue(sj.isActive); assertTrue(cj.isActive)
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
}
@Test fun localReplySendFailureDoesNotForgePlaintextErrorOrClose() = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<Int, Int>()
val (a, b) = createTestDevice()
var fail = false
var plaintextErrors = 0
val device = object : Transport.Device by b {
override suspend fun send(block: UByteArray) {
val bytes = block
val decoded = unpack<Transport.Block>(bytes)
if (decoded is Transport.Block.Error) plaintextErrors++
if (fail && decoded is Transport.Block.Response) throw RemoteInterface.Exception("Local write failure")
b.send(bytes)
}
}
val ready = CompletableDeferred<Unit>()
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, device, Unit)
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
val sj = launch { server.run() }
val cj = launch { client.run { if (it) ready.complete(Unit) } }
try {
ready.await(); fail = true
assertNull(withTimeoutOrNull(100) { client.call(echo, 1) })
assertEquals(0, plaintextErrors)
fail = false
assertEquals(2, client.call(echo, 2))
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
}
@Test fun allSecurePathsShareOrderedNonceAdmission() = runTest(timeout = 20.seconds) {
initCrypto()
val echo by command<Int, Int>()
val notify by command<Int, Unit>()
val (a, b) = createTestDevice()
fun observing(device: Transport.Device, nonces: MutableList<ULong>, skipHandshakeReply: Boolean = false) = object : Transport.Device by device {
override suspend fun send(block: UByteArray) {
val bytes = block
when (val decoded = unpack<Transport.Block>(bytes)) {
is Transport.Block.Call -> if (decoded.name != "L0Request")
nonces += unpack<KiloParams.Package>(unpack<UByteArray>(decoded.packedArgs)).nonce
is Transport.Block.Response -> if (!skipHandshakeReply || decoded.forId != 1u)
nonces += unpack<KiloParams.Package>(unpack<UByteArray>(decoded.packedResult)).nonce
else -> Unit
}
device.send(bytes)
}
}
val an = mutableListOf<ULong>(); val bn = mutableListOf<ULong>()
val api = KiloInterface<Unit>().apply { on(echo) { it }; on(notify) {} }
val ready = CompletableDeferred<Unit>()
val server = KiloServerConnection(api, observing(b, bn, true), Unit)
val client = KiloClientConnection(api, observing(a, an), Unit)
val sj = launch { server.run() }
val cj = launch { client.run { if (it) ready.complete(Unit) } }
try {
ready.await()
// Real JVM parallel preparation, requests in both directions, replies and pushes.
withContext(Dispatchers.Default) {
(0 until 32).map { n -> async {
val remote: RemoteInterface = if (n % 2 == 0) client else server
remote.push(notify, n)
assertEquals(n, remote.call(echo, n))
} }.awaitAll()
}
for (nonces in listOf(an, bn)) {
assertEquals(0uL, nonces.first())
assertTrue(nonces.zipWithNext().all { (x, y) -> y > x }, "Equal-priority admission must follow nonce allocation: $nonces")
assertTrue(nonces.size >= 49)
}
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
}
}
@@ -0,0 +1,97 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import net.sergeych.crypto2.*
import net.sergeych.kiloparsec.*
import net.sergeych.utools.pack
import net.sergeych.utools.unpack
import kotlin.test.*
import kotlin.time.Duration.Companion.seconds
class ReplayDeliveryTest {
@Test fun replayWindowBoundaries() = runTest {
initCrypto()
val a = SafeKeyExchange(); val b = SafeKeyExchange()
val (da, db) = createTestDevice()
val ta = Transport(da, LocalInterface<Unit>(), Unit)
val tb = Transport(db, LocalInterface<Unit>(), Unit)
val sender = KiloParams(false, ta, a.clientSessionKey(b.publicKey), Unit, null, ta)
val receiver = KiloParams(true, tb, b.serverSessionKey(a.publicKey), Unit, null, tb)
val packets = (0..4096).map { sender.encrypt(pack(it)) }
assertEquals(4096, unpack<Int>(receiver.decrypt(packets[4096])))
assertEquals(2, unpack<Int>(receiver.decrypt(packets[2])))
assertEquals(1, unpack<Int>(receiver.decrypt(packets[1])))
assertFails { receiver.decrypt(packets[0]) }
assertFails { receiver.decrypt(packets[1]) }
da.close(); db.close()
}
@Test fun localSendFailurePreservesHealthyConnection() = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<String,String>()
val (a,b) = createTestDevice()
val ready = CompletableDeferred<Unit>()
var fail = true
val localFailure = object: Transport.Device by a {
override suspend fun send(block: UByteArray) {
val decoded = unpack<Transport.Block>(block)
if(fail && decoded is Transport.Block.Call && decoded.name == "L0Call")
throw RemoteInterface.Exception("Outgoing block queue is full")
a.send(block)
}
}
val server=KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, b, Unit)
val client=KiloClientConnection(KiloInterface<Unit>(),localFailure,Unit)
val sj=launch { runCatching { server.run() } }
val cj=launch { runCatching { client.run { if(it) ready.complete(Unit) } } }
try {
ready.await()
val result=runCatching { client.call(echo,"x") }
assertIs<RemoteInterface.Exception>(result.exceptionOrNull())
assertFalse(result.exceptionOrNull() is RemoteInterface.SecurityException)
assertTrue(cj.isActive); assertTrue(sj.isActive)
fail = false
assertEquals("recovered", client.call(echo,"recovered"))
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
}
@Test fun adjacentReorderingSurvives() = reorderedPushes(1, false)
@Test fun deepReorderingDiscardsWithoutClosing() = reorderedPushes(4096, true)
private fun reorderedPushes(overtakers: Int, shouldDiscard: Boolean) = runTest(timeout = 20.seconds) {
initCrypto()
val notify by command<Int,Unit>()
val (a,b)=createTestDevice()
val ready=CompletableDeferred<Unit>()
val newerReceived=CompletableDeferred<Unit>()
val heldReceived=CompletableDeferred<Unit>()
var held: UByteArray?=null
val reorder=object: Transport.Device by a {
override suspend fun send(block: UByteArray) {
val decoded=unpack<Transport.Block>(block)
if(decoded is Transport.Block.Call && decoded.name=="L0Call" && held==null) held=block
else a.send(block)
}
}
val server=KiloServerConnection(KiloInterface<Unit>().apply { on(notify) {
if(it==overtakers) newerReceived.complete(Unit)
if(it==0) heldReceived.complete(Unit)
} }, b, Unit)
val client=KiloClientConnection(KiloInterface<Unit>(),reorder,Unit)
val sj=launch { runCatching { server.run() } }
val cj=launch { runCatching { client.run { if(it) ready.complete(Unit) } } }
try {
ready.await()
for(i in 0..overtakers) client.push(notify,i)
newerReceived.await()
a.send(held!!)
if(shouldDiscard) {
runCurrent()
assertTrue(sj.isActive); assertTrue(cj.isActive)
assertFalse(heldReceived.isCompleted)
client.ping()
} else {
withTimeout(2000) { heldReceived.await() }
assertTrue(sj.isActive); assertTrue(cj.isActive)
}
} finally { sj.cancelAndJoin(); cj.cancelAndJoin() }
}
}
+28
View File
@@ -0,0 +1,28 @@
@file:OptIn(ExperimentalUnsignedTypes::class)
package net.sergeych.kiloparsec
import kotlin.random.Random
import kotlin.test.*
class ReplayWindowTest {
@Test fun boundariesWraparoundAndLargeJumpsMatchReference() {
val window = ReplayWindow()
val seen = mutableSetOf<ULong>()
var highest: ULong? = null
val random = Random(41)
val inputs = mutableListOf(4096uL, 1uL, 2uL, 0uL, 1uL, 8191uL, 4096uL, 8192uL)
repeat(15000) { inputs += random.nextInt(0, 30000).toULong() }
inputs += listOf(ULong.MAX_VALUE - 1u, ULong.MAX_VALUE, ULong.MAX_VALUE - 4095u, ULong.MAX_VALUE - 4096u)
for (n in inputs) {
val h = highest
val reject = n in seen || (h != null && n <= h && h - n >= 4096u)
assertEquals(reject, window.containsOrStale(n), "nonce=$n highest=$h")
if (!reject) {
window.record(n)
seen += n
if (h == null || n > h) highest = n
assertTrue(window.containsOrStale(n))
}
}
}
}
@@ -0,0 +1,123 @@
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package net.sergeych.kiloparsec.adapter
import createTestDevice
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import net.sergeych.kiloparsec.*
import net.sergeych.utools.pack
import net.sergeych.utools.unpack
import kotlin.test.*
class OutQueueTest {
@Test fun priorityWithinWindowAndOldestProgress() {
val queue = OutQueue<ULong>()
queue.push(100u, 100u, -100)
for (n in 101uL..5000uL) queue.push(n, n, 100)
val sent = mutableListOf<ULong>()
while (true) sent += queue.pop() ?: break
assertEquals((101uL..2830uL).toList(), sent.take(2730))
assertEquals(100uL, sent[2730])
assertEquals(4901, sent.toSet().size)
}
@Test fun gapsAndMaximumNonceDoNotOverflow() {
val queue = OutQueue<ULong>()
queue.push(ULong.MAX_VALUE, ULong.MAX_VALUE, 100)
queue.push(ULong.MAX_VALUE - 2731u, ULong.MAX_VALUE - 2731u, -100)
assertEquals(ULong.MAX_VALUE - 2731u, queue.pop())
assertEquals(ULong.MAX_VALUE, queue.pop())
assertNull(queue.pop())
}
@Test fun writerHandlesCancellationCapacityAndContinuesAfterLocalFailure() = runTest {
val gate = CompletableDeferred<Unit>()
val entered = CompletableDeferred<Unit>()
val observed = mutableListOf<Int>()
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 2, continueOnWriteFailure = true) {
val n = it[0].toInt()
if (n == 0) { entered.complete(Unit); gate.await() }
if (n == 3) throw IllegalStateException("Local carrier rejection")
observed += n
}
val first = async { writer.enqueue(ubyteArrayOf(0u), 0u).invoke() }
entered.await()
val cancelled = async { writer.enqueue(ubyteArrayOf(1u), 1u).invoke() }
runCurrent()
val second = async { writer.enqueue(ubyteArrayOf(2u), 2u).invoke() }
runCurrent()
assertFailsWith<RemoteInterface.Exception> { writer.enqueue(ubyteArrayOf(9u), 9u) }
cancelled.cancelAndJoin()
gate.complete(Unit)
first.await(); second.await()
assertFailsWith<IllegalStateException> { writer.enqueue(ubyteArrayOf(3u), 3u).invoke() }
writer.enqueue(ubyteArrayOf(4u), 4u).invoke()
assertEquals(listOf(0, 2, 4), observed)
writer.close(); runCurrent()
assertFailsWith<RemoteInterface.ClosedException> { writer.enqueue(ubyteArrayOf(5u), 5u) }
}
@Test fun writerUsesNonceBoundBeforePriority() = runTest {
val gate = CompletableDeferred<Unit>()
val entered = CompletableDeferred<Unit>()
val order = mutableListOf<Int>()
val writer = PriorityBlockWriter(backgroundScope) { bytes ->
val n = (unpack<Transport.Block>(bytes) as Transport.Block.Call).id.toInt()
if (n == 0) { entered.complete(Unit); gate.await() }
order += n
}
fun frame(n: Int, priority: Int) = pack<Transport.Block>(Transport.Block.Call(n.toUInt(), "x", ubyteArrayOf()).also { it.priority = priority })
val first = async { writer.enqueue(frame(0, 0), 0u).invoke() }
entered.await()
val old = writer.enqueue(frame(1, 0), 1u)
val newer = writer.enqueue(frame(2, 100), 2732u)
gate.complete(Unit); first.await(); old(); newer()
assertEquals(3, order.size)
assertEquals(listOf(0, 1, 2), order)
writer.close()
}
@Test fun encryptedBacklogCrossingWindowStillDeliversEveryMessage() = runTest {
net.sergeych.crypto2.initCrypto()
val a = net.sergeych.crypto2.SafeKeyExchange()
val b = net.sergeych.crypto2.SafeKeyExchange()
val (da, db) = createTestDevice()
val ta = Transport(da, LocalInterface<Unit>(), Unit)
val tb = Transport(db, LocalInterface<Unit>(), Unit)
val sender = KiloParams(false, ta, a.clientSessionKey(b.publicKey), Unit, null, ta)
val receiver = KiloParams(true, tb, b.serverSessionKey(a.publicKey), Unit, null, tb)
val gate = CompletableDeferred<Unit>()
val entered = CompletableDeferred<Unit>()
val order = mutableListOf<Int>()
// Larger test capacity reaches the boundary in one batch; production retains 128.
val writer = PriorityBlockWriter(backgroundScope, maxQueuedItems = 5000) { bytes ->
val frame = unpack<Transport.Block>(bytes) as Transport.Block.Call
if (frame.id == 0u) { entered.complete(Unit); gate.await() }
order += unpack<Int>(receiver.decrypt(unpack(frame.packedArgs)))
}
suspend fun admit(n: Int, priority: Int): suspend () -> Unit {
val encoded = sender.encode(pack(n))
val frame = Transport.Block.Call(n.toUInt(), "L0Call", pack(encoded.bytes)).also { it.priority = priority }
return writer.enqueue(pack<Transport.Block>(frame), encoded.nonce)
}
try {
val first = admit(0, 0)
entered.await()
val completions = mutableListOf(admit(1, -100))
for (n in 2..4097) completions += admit(n, 100)
gate.complete(Unit); first()
completions.forEach { it() }
assertEquals(4098, order.size)
assertEquals((0..4097).toSet(), order.toSet())
assertEquals(2731, order.indexOf(1))
} finally { writer.close(); da.close(); db.close() }
}
@Test fun closingWriterReleasesCurrentAndQueuedSenders() = runTest {
val entered = CompletableDeferred<Unit>()
val writer = PriorityBlockWriter(backgroundScope) { entered.complete(Unit); awaitCancellation() }
val first = async { runCatching { writer.send(ubyteArrayOf(0u)) } }
entered.await()
val second = async { runCatching { writer.enqueue(ubyteArrayOf(1u), 1u).invoke() } }
runCurrent(); writer.close()
assertTrue(first.await().isFailure)
assertTrue(second.await().isFailure)
}
}