Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
## Fixed
- A device removed from a sync group on the local network now finds out the next time it reaches a device still in the group, and stops syncing, instead of staying linked. The device it reaches shares only the list of devices with it.
28 changes: 25 additions & 3 deletions app/src/main/java/io/github/aedev/flow/sync2/lan/LanLink.kt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ class LanLink internal constructor(
val peerPort: Int?,
private val sendKey: ByteArray,
private val receiveKey: ByteArray,
/** The connecting device was removed and hasn't read it yet, so it gets the roster only (spec/live.md, LAN groups). */
val peerRemoved: Boolean = false,
) {
private val sending = Mutex()
private var sent = 0L
Expand Down Expand Up @@ -129,6 +131,17 @@ internal suspend fun SyncConnection.receiveHello(): ByteArray? =
private fun Session.memberKey(did: String): ByteArray =
state.members[did]?.takeIf { it.role == Role.DEVICE && did != me }?.sig ?: reject(ProtocolError.SENDER)

/** The signing key of a device this one has seen removed, when it was a device in [epoch], the epoch of its hello. */
private fun Session.removedKey(
did: String,
epoch: Int,
): ByteArray? {
if (did in state.members) return null
val sender = state.senders[did]?.takeIf { it.role == Role.DEVICE } ?: return null
val until = sender.until ?: return null
return sender.sig.takeIf { epoch in sender.since..until }
}

/**
* The connecting side: hello sealed under [epoch], naming the [port] this device listens on.
* [LinkedException.LanUnreachable] when the member closes without answering.
Expand Down Expand Up @@ -199,7 +212,8 @@ suspend fun dialLink(

/**
* The accepting side: answers the hello in [first] under the epoch the client named, if this device holds its key.
* [first] is the connection's first frame, read here unless the caller already has it.
* [first] is the connection's first frame, read here unless the caller already has it. A client this device removed
* is answered too, and its link is [LanLink.peerRemoved].
*/
suspend fun acceptLink(
connection: SyncConnection,
Expand All @@ -212,7 +226,8 @@ suspend fun acceptLink(
val lanKey = purposeKey(session.epochKey(epoch), session.group, epoch, Purpose.LAN)
val hello = opened(opening, lanKey, 1)
val clientDid = hello.field("did")
val clientKey = session.memberKey(clientDid)
val removedKey = session.removedKey(clientDid, epoch)
val clientKey = removedKey ?: session.memberKey(clientDid)
val client = SyncBytes.fromHex(clientDid)
val clientNonce = hello.nonce()
val serverNonce = SyncCrypto.randomBytes(NONCE_SIZE)
Expand All @@ -232,5 +247,12 @@ suspend fun acceptLink(
val transcript = lanTranscript(LanRole.CLIENT, clientNonce, serverNonce, client, server)
if (!verify(clientKey, transcript, third.signature())) reject(ProtocolError.SIGNATURE)
val keys = lanSessionKeys(lanKey, clientNonce, serverNonce, client, server)
return LanLink(connection, clientDid, (hello["p"] as? JsonPrimitive)?.intOrNull, keys.serverToClient, keys.clientToServer)
return LanLink(
connection,
clientDid,
(hello["p"] as? JsonPrimitive)?.intOrNull,
keys.serverToClient,
keys.clientToServer,
peerRemoved = removedKey != null,
)
}
10 changes: 10 additions & 0 deletions app/src/main/java/io/github/aedev/flow/sync2/lan/LanPeer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ class LanPeer(
) = encode(fields + mapOf("ok" to JsonPrimitive(true), "re" to id), bytes)

fun error(code: String) = encode(mapOf("error" to JsonPrimitive(code), "ok" to JsonPrimitive(false), "re" to id), null)
if (link.peerRemoved && op != "roster") {
// An empty listing rather than an error, so its pull ends and it applies the roster it just took.
when (op) {
"list" -> ok(mapOf("blobs" to JsonArray(emptyList()), "paths" to JsonArray(emptyList())))
"key", "get" -> error("not_found")
"live" -> null
else -> error("invalid")
}?.let { link.send(it) }
return
}
val header = request.header
val reply =
runCatching {
Expand Down
25 changes: 18 additions & 7 deletions app/src/main/java/io/github/aedev/flow/sync2/lan/LanSync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class LanSync
launch {
val connection = connect(row.address) ?: return@launch
try {
converse(connectLink(connection, session), session, leaving = true)
converse(connectLink(connection, session), session, serveOnly = true)
Log.i(TAG, "LAN farewell delivered")
} catch (e: CancellationException) {
throw e
Expand Down Expand Up @@ -328,13 +328,24 @@ class LanSync
devices.lanPeers { it + did }
}

/** One session with the member that dialed this device over [connection]. Returns the closed link when it got that far. */
/**
* One session with the member that dialed this device over [connection]. Returns the closed link when it got that
* far, or null for a device this one removed: it is only served the roster, and its address isn't kept.
*/
private suspend fun meet(
connection: SyncConnection,
greeter: LanGreeter,
): LanLink? =
try {
greeter.greet(connection)?.let { (link, session) -> talk(link, session, "LAN session accepted") }
greeter.greet(connection)?.let { (link, session) ->
if (link.peerRemoved) {
converse(link, session, serveOnly = true)
Log.i(TAG, "LAN session served the roster to a removed device")
null
} else {
talk(link, session, "LAN session accepted")
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Expand Down Expand Up @@ -385,18 +396,18 @@ class LanSync

/**
* Answers the other member's requests until its pull is over. This device pulls too and sends
* live messages on the session, unless it is [leaving].
* live messages on the session, unless it [serveOnly]: when it is leaving, or the other was removed.
*/
private suspend fun converse(
link: LanLink,
session: Session,
leaving: Boolean = false,
serveOnly: Boolean = false,
envelope: ByteArray? = null,
) = coroutineScope {
val peer = LanPeer(link, session, local) { live.receive(it) }
val reader = peer.start(this)
val detach =
if (leaving) {
if (serveOnly) {
null
} else {
live.attach(
Expand All @@ -407,7 +418,7 @@ class LanSync
}
try {
envelope?.let { peer.sendLive(it) }
if (!leaving) peer.pull()
if (!serveOnly) peer.pull()
peer.awaitQuiet(QUIET_MS)
} finally {
detach?.invoke()
Expand Down
49 changes: 49 additions & 0 deletions app/src/test/java/io/github/aedev/flow/sync2/LanSyncTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import io.github.aedev.flow.sync.transport.SyncConnection
import io.github.aedev.flow.sync.transport.WsClient
import io.github.aedev.flow.sync.transport.WsServer
import io.github.aedev.flow.sync2.crypto.MemberSecrets
import io.github.aedev.flow.sync2.crypto.ProtocolError
import io.github.aedev.flow.sync2.crypto.ProtocolException
import io.github.aedev.flow.sync2.data.LAN_STORE
import io.github.aedev.flow.sync2.data.LinkedDatabase
Expand All @@ -25,6 +26,7 @@ import io.github.aedev.flow.sync2.lan.dialLink
import io.github.aedev.flow.sync2.lan.portFree
import io.github.aedev.flow.sync2.linking.DeviceMeta
import io.github.aedev.flow.sync2.linking.newEpoch
import io.github.aedev.flow.sync2.linking.removeDevices
import io.github.aedev.flow.sync2.linking.renameDevice
import io.github.aedev.flow.sync2.roster.Entry
import io.github.aedev.flow.sync2.roster.Op
Expand All @@ -46,6 +48,7 @@ import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
Expand Down Expand Up @@ -302,6 +305,52 @@ class LanSyncTest {
assertTrue("$error", error is ProtocolException || error is LinkedException)
}

/** [g]'s first member, having written an object, removes the second, which hasn't heard of it. */
private suspend fun TestScope.bRemoved(g: LinkedGroup): Pair<Member, Member> {
val (a, b) = member(g, g.a) to member(g, g.b)
a.write("aaaaaaaaaaa")
removeDevices(a.session(), g.a, listOf(SyncBytes.toHex(g.b.did)))
return a to b
}

@Test
fun a_removed_device_is_answered_with_the_roster_and_nothing_else() =
runTest {
val g = LinkedGroup(this).apply { create() }
val (a, b) = bRemoved(g)
val written = StorePaths.log(SyncBytes.toHex(g.a.did), 1)
linked(client = b, server = a) { link, _ ->
assertEquals(JsonPrimitive(true), ask(link, """{"after":-1,"id":0,"op":"roster"}""")["ok"])
val listed = ask(link, """{"id":1,"op":"list","vv":{}}""")
assertEquals(JsonArray(emptyList()), listed["paths"])
assertEquals(JsonPrimitive("not_found"), ask(link, """{"id":2,"op":"get","path":"$written"}""")["error"])
}
}

@Test
fun a_removed_device_learns_its_removal_from_a_member_it_dials() =
runTest {
val g = LinkedGroup(this).apply { create() }
val (a, b) = bRemoved(g)

dialed(client = b, server = a)

assertNull(b.local.getObject(StorePaths.log(SyncBytes.toHex(g.a.did), 1)))
val refused = runCatching { b.session() }.exceptionOrNull()
assertTrue("$refused", refused is LinkedException.Removed)
}

@Test
fun a_member_refuses_a_device_it_removed_when_it_dials_it() =
runTest {
val g = LinkedGroup(this).apply { create() }
val (a, b) = bRemoved(g)

val refused = runCatching { dialed(client = a, server = b) }.exceptionOrNull()

assertEquals("$refused", ProtocolError.SENDER, (refused as? ProtocolException)?.error)
}

@Test
fun members_that_appended_at_the_same_seq_both_end_on_the_fork_winner() =
runTest {
Expand Down
Loading