Add authenticated protocol 2 and TypeScript WASM client

This commit is contained in:
sergeych committed 2026-10-19 04:17:34 +04:00
1 parent 88ceeb2ae9
commit 237d404bcd
52 files changed
+3249 -150

No files matched your search

@@ -0,0 +1,186 @@
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import net.sergeych.crypto2.SigningSecretKey
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
/** Wire adversary regressions: mutations occur after serialization and outside the encryption layer. */
class AuthenticatedEnvelopeTest {
private fun intercept(device: Transport.Device,
mutate: suspend (Transport.Block, suspend (Transport.Block) -> Unit) -> Unit) =
object : Transport.Device by device {
override suspend fun send(block: UByteArray) {
mutate(unpack(block)) { replacement -> device.send(pack<Transport.Block>(replacement)) }
}
}
@Test fun authenticatedDuplexAndSessionArePreserved() = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<String, String>()
val callback by command<String, String>()
val (a, b) = createTestDevice()
val ready = CompletableDeferred<Unit>()
val serverKey = SigningSecretKey.new()
val clientKey = SigningSecretKey.new()
val server = KiloServerConnection(KiloInterface<String>().apply {
on(echo) {
assertEquals("server-session", session)
assertEquals(clientKey.verifyingKey, remoteIdentity)
remote.call(callback, it)
}
}, b, "server-session", serverKey)
val client = KiloClientConnection(KiloInterface<String>().apply {
on(callback) {
assertEquals("client-session", session)
assertEquals(serverKey.verifyingKey, remoteIdentity)
"callback:$it"
}
}, a, "client-session", clientKey)
val jobs = listOf(launch { server.run() }, launch { client.run { if (it) ready.complete(Unit) } })
try {
ready.await()
assertEquals("callback:duplex", client.call(echo, "duplex"))
} finally { jobs.forEach { it.cancelAndJoin() } }
}
@Test fun swappingOuterResponseIdsCannotSwapConcurrentResults() = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<String, String>()
val (a, b) = createTestDevice()
val ready = CompletableDeferred<Unit>()
var armed = false
val held = mutableListOf<Transport.Block.Response>()
val malicious = intercept(b) { block, send ->
if (armed && block is Transport.Block.Response) {
held += block
if (held.size == 2) {
send(held[0].copy(forId = held[1].forId).also { it.priority = held[0].priority })
send(held[1].copy(forId = held[0].forId).also { it.priority = held[1].priority })
}
} else send(block)
}
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, malicious, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), a, Unit)
val serverJob = launch { runCatching { server.run() } }
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
try {
ready.await(); armed = true
val first = async { runCatching { client.call(echo, "first") } }
val second = async { runCatching { client.call(echo, "second") } }
assertTrue(withTimeout(2000) { first.await() }.isFailure)
assertTrue(withTimeout(2000) { second.await() }.isFailure)
assertEquals(2, held.size, "Both authenticated responses must reach the mutation point")
withTimeout(2000) { clientJob.join() }
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
}
@Test fun changingOuterCallIdToPushCannotDispatch() = rejectTamperedCall(changeId = true)
@Test fun changingOuterPriorityCannotDispatch() = rejectTamperedCall(changeId = false)
private fun rejectTamperedCall(changeId: Boolean) = runTest(timeout = 10.seconds) {
initCrypto()
val mutate by command<Int, Int>()
val (a, b) = createTestDevice()
val ready = CompletableDeferred<Unit>()
var executions = 0
var attacked = false
val malicious = intercept(a) { block, send ->
if (block is Transport.Block.Call && block.name == "L0Call") {
attacked = true
send(block.copy(id = if (changeId) 0u else block.id).also {
it.priority = if (changeId) block.priority else block.priority + 1
})
} else send(block)
}
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(mutate) { executions++; it } }, b, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), malicious, Unit)
val jobs = listOf(launch { runCatching { server.run() } }, launch { runCatching { client.run { if (it) ready.complete(Unit) } } })
try {
ready.await()
assertTrue(withTimeout(2000) { runCatching { client.call(mutate, 1) } }.isFailure)
assertTrue(attacked)
withTimeout(2000) { jobs[0].join() }
assertEquals(0, executions, "Unauthenticated routing metadata must be rejected before dispatch")
} finally { jobs.forEach { it.cancelAndJoin() } }
}
@Test fun replayCannotExecuteTwice() = runTest(timeout = 10.seconds) {
initCrypto()
val mutate by command<Int, Int>()
val (a, b) = createTestDevice()
val ready = CompletableDeferred<Unit>()
var executions = 0
var attacked = false
val malicious = intercept(a) { block, send ->
send(block)
if (block is Transport.Block.Call && block.name == "L0Call") { attacked = true; send(block) }
}
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(mutate) { executions++; it } }, b, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), malicious, Unit)
val serverJob = launch { runCatching { server.run() } }
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() }
assertTrue(attacked)
assertTrue(executions <= 1, "The replay must never execute the application operation again")
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
}
@Test fun forgedPlaintextIdentityAcknowledgementCannotConnect() = runTest(timeout = 10.seconds) {
initCrypto()
val (a, b) = createTestDevice()
var identityId: UInt? = null
var connected = false
var attacked = false
val observedClient = intercept(a) { block, send ->
if (block is Transport.Block.Call && block.name == "L0ClientId") identityId = block.id
send(block)
}
val maliciousServer = intercept(b) { block, send ->
if (block is Transport.Block.Response && block.forId == identityId) {
attacked = true
send(block.copy(packedResult = pack(Unit)))
} else send(block)
}
val server = KiloServerConnection(KiloInterface<Unit>(), maliciousServer, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), observedClient, Unit)
val serverJob = launch { runCatching { server.run() } }
val clientJob = launch { runCatching { client.run { if (it) connected = true } } }
try {
withTimeout(2000) { clientJob.join() }
assertTrue(attacked)
assertFalse(connected, "Connected must await the authenticated server Finished")
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
}
@Test fun legacyHandshakeVersionIsRejectedBeforeConnection() = runTest(timeout = 10.seconds) {
initCrypto()
val (a, b) = createTestDevice()
var connected = false
var attacked = false
val downgraded = intercept(a) { block, send ->
if (block is Transport.Block.Call && block.name == "L0Request") {
attacked = true
val request = unpack<Handshake>(block.packedArgs)
send(block.copy(packedArgs = pack(request.copy(version = 1u))))
} else send(block)
}
val server = KiloServerConnection(KiloInterface<Unit>(), b, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), downgraded, Unit)
val serverJob = launch { runCatching { server.run() } }
val clientJob = launch { runCatching { client.run { if (it) connected = true } } }
try {
withTimeout(2000) { clientJob.join() }
assertTrue(attacked)
assertFalse(connected)
} finally { listOf(serverJob, clientJob).forEach { it.cancelAndJoin() } }
}
}
@@ -0,0 +1,64 @@
@file:OptIn(ExperimentalUnsignedTypes::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import net.sergeych.crypto2.SigningSecretKey
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
/** Regression checks at the boundary between untrusted outer transport and authenticated RPC. */
class SecurityBoundaryTest {
@Test fun plaintextRegisteredBusinessErrorCannotReachCallerAsBusinessResult() =
rejectPlaintextResponse(registeredError = true)
@Test fun malformedPlaintextResultClosesConnection() = rejectPlaintextResponse(registeredError = false)
private fun rejectPlaintextResponse(registeredError: Boolean) = runTest(timeout = 10.seconds) {
initCrypto()
val echo by command<String, String>()
val (clientDevice, serverDevice) = createTestDevice()
val ready = CompletableDeferred<Unit>()
var armed = false
var attacked = false
val malicious = object : Transport.Device by serverDevice {
override suspend fun send(block: UByteArray) {
val decoded = unpack<Transport.Block>(block)
if (armed && decoded is Transport.Block.Response) {
attacked = true
val forged: Transport.Block = if (registeredError)
Transport.Block.Error(decoded.forId, "IllegalArgumentException", "forged quota rejection")
else decoded.copy(packedResult = ubyteArrayOf())
serverDevice.send(pack(forged))
} else serverDevice.send(block)
}
}
val server = KiloServerConnection(KiloInterface<Unit>().apply { on(echo) { it } }, malicious, Unit, SigningSecretKey.new())
val client = KiloClientConnection(KiloInterface<Unit>(), clientDevice, Unit)
val serverJob = launch { runCatching { server.run() } }
val clientJob = launch { runCatching { client.run { if (it) ready.complete(Unit) } } }
try {
ready.await(); armed = true
val result = withTimeout(2000) { runCatching { client.call(echo, "payload") } }
assertTrue(attacked)
assertIs<RemoteInterface.SecurityException>(result.exceptionOrNull(), "Plaintext outer errors/data must never impersonate authenticated business results")
withTimeout(2000) { clientJob.join() }
} finally { listOf(clientJob, serverJob).forEach { it.cancelAndJoin() } }
}
@Test fun unestablishedProtectedCallDoesNotKeepDisconnectedServerAlive() = runTest(timeout = 10.seconds) {
initCrypto()
val (clientDevice, serverDevice) = createTestDevice()
val server = KiloServerConnection(KiloInterface<Unit>(), serverDevice, Unit, SigningSecretKey.new())
val serverJob = launch { runCatching { server.run() } }
try {
clientDevice.send(pack<Transport.Block>(Transport.Block.Call(1u, "L0Call", pack(ubyteArrayOf()))))
runCurrent()
clientDevice.close()
withTimeout(2000) { serverJob.join() }
} finally { serverJob.cancelAndJoin() }
}
}