Repository Public License
1import Foundation2import Network3import NavigatorCore4import Persistence5import Testing6@testable import SyncEngine78@Suite struct BridgePairingTests {9 @Test func pairingCodesAreNumericAndParsedLeniently() throws {10 let code = BridgePairingCode.generate()11 #expect(code.digits.count == 6 && code.digits.allSatisfy(\.isNumber))12 #expect(BridgePairingCode.generate(length: 9).digits.count == 9 && BridgePairingCode.generate(length: 2).digits.count == 6)13 #expect(try BridgePairingCode(" 123 456 ").digits == "123456" && BridgePairingCode("123-456").formatted == "123 456")14 for invalid in ["", "12345", "12345a", "123456", "1234567890123", "12 34"] { #expect(throws: BridgeError.invalidCode) { try BridgePairingCode(invalid) } }15 // Codes are not repeated in practice.16 #expect(Set((0..<200).map { _ in BridgePairingCode.generate(length: 12).digits }).count == 200)17 }1819 @Test func theSameCodeOnBothSidesGivesAWorkingChannel() async throws {20 let (initiator, responder, _) = try await pairedChannels()21 try await initiator.send(Data("hello from the typing device".utf8))22 try await responder.send(Data("hello from the showing device".utf8))23 #expect(try await responder.receive() == Data("hello from the typing device".utf8))24 #expect(try await initiator.receive() == Data("hello from the showing device".utf8))25 // Many messages, sent concurrently, arrive complete and in the order they were sent.26 await withTaskGroup(of: Void.self) { group in27 for index in 0..<200 { group.addTask { try? await initiator.send(Data("m\(index)".utf8)) } }28 }29 var received = Set<String>()30 for _ in 0..<200 { received.insert(String(decoding: try await responder.receive(), as: UTF8.self)) }31 #expect(received == Set((0..<200).map { "m\($0)" }))32 let large = Data((0..<2_000_000).map { UInt8(truncatingIfNeeded: $0) })33 try await responder.send(large)34 #expect(try await initiator.receive() == large)35 await #expect(throws: BridgeError.frameTooLarge(BridgeSecureChannel.maximumMessageBytes + 1)) {36 try await initiator.send(Data(count: BridgeSecureChannel.maximumMessageBytes + 1))37 }38 }3940 @Test func aWrongCodeFailsOnBothSidesAndTheCodeIsSpentAfterOneAttempt() async throws {41 let offer = BridgePairingOffer(code: try BridgePairingCode("482913"))42 let (a, b) = InMemoryBridgeTransport.pair()43 let responder = Task { try await offer.accept(over: b) }44 await #expect(throws: BridgeError.pairingFailed) { try await BridgePairing.initiate(code: try BridgePairingCode("482914"), over: a) }45 #expect(await failure(of: responder) is BridgeError)46 #expect(await offer.hasBeenUsed)47 // The right code, tried afterwards on a fresh connection, is refused: one attempt per code.48 let (c, d) = InMemoryBridgeTransport.pair()49 let second = Task { try await offer.accept(over: d) }50 await #expect(throws: BridgeError.self) { try await BridgePairing.initiate(code: try BridgePairingCode("482913"), over: c, timeout: .seconds(2)) }51 #expect(await failure(of: second) as? BridgeError == .codeAlreadyUsed)52 // A successful pairing also spends the code.53 let fresh = BridgePairingOffer()54 let (e, f) = InMemoryBridgeTransport.pair()55 async let good: BridgeSecureChannel = fresh.accept(over: f)56 _ = try await BridgePairing.initiate(code: fresh.code, over: e)57 _ = try await good58 let (_, h) = InMemoryBridgeTransport.pair()59 await #expect(throws: BridgeError.codeAlreadyUsed) { try await fresh.accept(over: h) }60 }6162 /// An attacker sitting between the two devices who does not know the code: it completes a key agreement63 /// with each side but cannot produce either confirmation.64 @Test func aManInTheMiddleWithoutTheCodeCannotPairWithEitherSide() async throws {65 let offer = BridgePairingOffer(code: try BridgePairingCode("730155"))66 let (victimA, attackerSideA) = InMemoryBridgeTransport.pair()67 let (attackerSideB, victimB) = InMemoryBridgeTransport.pair()68 let showing = Task { try await offer.accept(over: victimB) }69 let typing = Task { try await BridgePairing.initiate(code: try BridgePairingCode("730155"), over: victimA, timeout: .seconds(3)) }70 // The attacker plays "showing device" towards A and "typing device" towards B, with a guessed code.71 let fake = BridgePairingOffer(code: try BridgePairingCode("000000"))72 let towardsA = Task { try await fake.accept(over: attackerSideA, timeout: .seconds(3)) }73 let towardsB = Task { try await BridgePairing.initiate(code: try BridgePairingCode("000000"), over: attackerSideB, timeout: .seconds(3)) }74 #expect(await failure(of: typing) is BridgeError)75 #expect(await failure(of: showing) is BridgeError)76 #expect(await failure(of: towardsA) is BridgeError)77 #expect(await failure(of: towardsB) is BridgeError)78 #expect(await offer.hasBeenUsed)79 }8081 @Test func malformedHandshakeMessagesFailCleanly() async throws {82 let zeros = Data(count: 48), ones = Data(repeating: 0xFF, count: 48)83 var junkMessages: [Data] = [Data(), Data([0x01]), Data(count: 50), Data(repeating: 0xFF, count: 5_000)]84 junkMessages.append(Data([0x02, 0x02]) + zeros) // wrong message type85 junkMessages.append(Data([0x01, 0x09]) + zeros) // unknown protocol version86 junkMessages.append(Data([0x01, 0x02]) + zeros) // right shape, no knowledge of the code87 junkMessages.append(Data([0x01, 0x02]) + ones)88 junkMessages.append(Data([0x01, 0x02]) + zeros.dropLast())89 for junk in junkMessages {90 let (a, b) = InMemoryBridgeTransport.pair()91 let offer = BridgePairingOffer()92 try await a.send(junk)93 // Even a well-formed first message is only half a handshake: without the confirmation it fails.94 Task { try? await Task.sleep(for: .milliseconds(100)); try? await a.send(Data([0x03]) + Data(count: 32)) }95 await #expect(throws: BridgeError.self) { try await offer.accept(over: b, timeout: .seconds(2)) }96 }97 // A peer that never answers: the attempt times out instead of waiting for ever.98 let (a, _) = InMemoryBridgeTransport.pair()99 let clock = ContinuousClock()100 let elapsed = await clock.measure {101 await #expect(throws: BridgeError.timedOut) { try await BridgePairing.initiate(code: .generate(), over: a, timeout: .milliseconds(200)) }102 }103 #expect(elapsed < .seconds(5))104 // A reflected first message (the peer echoes our own masked key back as its answer) is refused.105 let (c, d) = InMemoryBridgeTransport.pair()106 let attempt = Task { try await BridgePairing.initiate(code: .generate(), over: c, timeout: .seconds(2)) }107 let hello = try await d.receive()108 var reflected = Data([0x02])109 reflected.append(hello.dropFirst())110 reflected.append(Data(count: 32))111 try await d.send(reflected)112 #expect(await failure(of: attempt) as? BridgeError == .pairingFailed)113 }114115 @Test func publicKeysNeverTravelInClearAndMasksDependOnCodeNoncesAndRole() throws {116 var key = Data((0..<32).map { (index: Int) -> UInt8 in UInt8(truncatingIfNeeded: index * 7 + 3) })117 key[31] &= 0x7F118 let code = try BridgePairingCode("123456"), other = try BridgePairingCode("123457")119 let nonces = Data(repeating: 9, count: 16)120 let masked = BridgePairing.mask(key, role: .initiator, code: code, nonces: nonces)121 #expect(masked != key && masked.count == 32)122 // Unmasking with the same inputs gives the key back; any other input gives something else.123 #expect(BridgePairing.mask(masked, role: .initiator, code: code, nonces: nonces) == key)124 #expect(BridgePairing.mask(masked, role: .initiator, code: other, nonces: nonces) != key)125 #expect(BridgePairing.mask(masked, role: .responder, code: code, nonces: nonces) != key)126 #expect(BridgePairing.mask(masked, role: .initiator, code: code, nonces: Data(repeating: 8, count: 16)) != key)127 // The top bit, always 0 in a real key, stays 0 under every code: it cannot be used to rule codes out.128 for digits in 0..<200 {129 let candidate = try BridgePairingCode(String(format: "%06d", digits * 4_999))130 #expect(BridgePairing.mask(masked, role: .initiator, code: candidate, nonces: nonces)[31] & 0x80 == 0)131 }132 // Wrong codes spread over the whole space: no two of 200 candidates unmask to the same value.133 let candidates = try (0..<200).map { BridgePairing.mask(masked, role: .initiator, code: try BridgePairingCode(String(format: "%06d", $0)), nonces: nonces) }134 #expect(Set(candidates).count == 200)135 }136137 /// What crosses the wire during a pairing shows neither public key, and differs entirely between two138 /// pairings made with the same code.139 @Test func twoPairingsWithTheSameCodeShareNothingOnTheWire() async throws {140 func handshake() async throws -> [Data] {141 let (a, b) = InMemoryBridgeTransport.pair()142 let tap = HostileTransport(b)143 let offer = BridgePairingOffer(code: try BridgePairingCode("555555"))144 let accepted = Task { try await offer.accept(over: tap) }145 let channel = try await BridgePairing.initiate(code: try BridgePairingCode("555555"), over: a)146 let other = try await accepted.value147 try await channel.send(Data("x".utf8))148 _ = try await other.receive()149 return await tap.seen150 }151 let first = try await handshake(), second = try await handshake()152 #expect(first.count == 3 && first[0].count == 50 && first[1].count == 33)153 #expect(first[0].dropFirst(2) != second[0].dropFirst(2) && first[1].dropFirst(1) != second[1].dropFirst(1))154 #expect(first[0].prefix(2) == Data([0x01, 0x02]))155 }156}157158@Suite struct BridgeChannelTests {159 @Test func aReplayedFrameIsRejectedAndClosesTheChannel() async throws {160 let (initiator, responder, hostile) = try await pairedChannels(wrapping: true)161 let transport = try #require(hostile)162 try await initiator.send(Data("one".utf8))163 #expect(try await responder.receive() == Data("one".utf8))164 await transport.set(.replayPrevious)165 await #expect(throws: BridgeError.sequenceViolation(expected: 1, received: 0)) { try await responder.receive() }166 // Closed for good: even a legitimate frame is no longer accepted.167 try? await initiator.send(Data("two".utf8))168 await #expect(throws: BridgeError.closed) { try await responder.receive() }169 }170171 @Test func reorderedDroppedTamperedAndTruncatedFramesAreRejected() async throws {172 for mode in [HostileTransport.Mode.swapNextTwo, .dropNext] {173 let (initiator, responder, hostile) = try await pairedChannels(wrapping: true)174 for text in ["one", "two", "three"] { try await initiator.send(Data(text.utf8)) }175 #expect(try await responder.receive() == Data("one".utf8))176 await hostile?.set(mode)177 await #expect(throws: BridgeError.sequenceViolation(expected: 1, received: 2)) { try await responder.receive() }178 await #expect(throws: BridgeError.closed) { try await responder.receive() }179 }180 // Flip one bit in each part of a frame: sequence number, ciphertext, tag.181 for index in [0, 7, 8, 10, 14, 30, 1_000] {182 let (initiator, responder, hostile) = try await pairedChannels(wrapping: true)183 try await initiator.send(Data("a message of some length".utf8))184 await hostile?.set(.flipBit(index))185 await #expect(throws: BridgeError.self, "bit at byte \(index)") { try await responder.receive() }186 await #expect(throws: BridgeError.closed) { try await responder.receive() }187 }188 let (initiator, responder, hostile) = try await pairedChannels(wrapping: true)189 try await initiator.send(Data("a message".utf8))190 await hostile?.set(.truncate)191 await #expect(throws: BridgeError.authenticationFailed) { try await responder.receive() }192 }193194 @Test func framesAreNotReadableOnTheWireAndCannotBeReflected() async throws {195 let (initiator, responder, hostile) = try await pairedChannels(wrapping: true)196 let secret = Data("SECRET-BOOKMARK-TITLE https://private.example/".utf8)197 try await initiator.send(secret)198 #expect(try await responder.receive() == secret)199 let seen = await hostile?.seen ?? []200 #expect(!seen.isEmpty && seen.allSatisfy { $0.range(of: Data("SECRET".utf8)) == nil && $0.range(of: Data("private.example".utf8)) == nil })201 // A frame sent by one side cannot be fed back to that same side: each direction has its own key.202 let (a, b) = InMemoryBridgeTransport.pair()203 let offer = BridgePairingOffer()204 async let other: BridgeSecureChannel = offer.accept(over: b)205 let tapped = HostileTransport(a)206 let channel = try await BridgePairing.initiate(code: offer.code, over: tapped)207 let peer = try await other208 try await peer.send(Data("from peer".utf8))209 #expect(try await channel.receive() == Data("from peer".utf8))210 await tapped.set(.replayPrevious)211 await #expect(throws: BridgeError.self) { try await channel.receive() }212 // Two pairings never share keys: a frame from one session means nothing in another.213 let (first, _, _) = try await pairedChannels()214 let (_, secondResponder, secondHostile) = try await pairedChannels(wrapping: true)215 _ = first; _ = secondHostile216 await secondResponder.close()217 await #expect(throws: BridgeError.closed) { try await secondResponder.receive() }218 await #expect(throws: BridgeError.closed) { try await secondResponder.send(Data([1])) }219 }220}221222@Suite struct BridgeSessionTests {223 func device(_ name: String) async throws -> (NavigatorDatabase, Profile, SyncCoordinator) {224 let (database, profile) = try await World.empty(name: name)225 return (database, profile, SyncCoordinator(database: database, configuration: SyncConfiguration(fallbackProfileID: profile.id)))226 }227228 /// Pairs two coordinators over a transport pair and runs one session on each side.229 func session(_ a: SyncCoordinator, _ b: SyncCoordinator, over transports: (any BridgeTransport, any BridgeTransport)) async throws -> (BridgeSyncReport, BridgeSyncReport) {230 let offer = BridgePairingOffer()231 async let accepted = offer.accept(over: transports.1)232 let initiatorChannel = try await BridgePairing.initiate(code: offer.code, over: transports.0)233 let responderChannel = try await accepted234 async let right = BridgeSyncSession(coordinator: b, channel: responderChannel, deviceName: "Showing device").run()235 let left = try await BridgeSyncSession(coordinator: a, channel: initiatorChannel, deviceName: "Typing device").run()236 return (left, try await right)237 }238239 @Test func aWholeDataSetMovesFromOneDatabaseToAnotherInMemory() async throws {240 let world = try await World.populated()241 let source = SyncCoordinator(database: world.database, configuration: SyncConfiguration(fallbackProfileID: world.profile.id))242 let (target, profile, destination) = try await device("New device")243 // Enough notes for several index and payload messages.244 for index in 0..<2_500 { try await world.database.notes.save(Note(title: "note \(index)", body: String(repeating: "text \(index) ", count: 60), createdAt: day(), updatedAt: day())) }245 let (left, right) = try await session(source, destination, over: InMemoryBridgeTransport.pair())246 #expect(left.sent == 2_509 && left.received == 0 && right.received == 2_509 && right.sent == 0)247 #expect(right.applied.applied == 2_509 && right.applied.rejected == 0 && right.applied.deferred.isEmpty)248 #expect(left.peerDeviceName == "Showing device" && right.peerDeviceName == "Typing device" && left.peerDeviceID != right.peerDeviceID)249 #expect(try await SyncedContent.of(target) == SyncedContent.of(world.database))250 #expect(try await target.bookmarks.all(profile: profile.id).count == 5)251 #expect(try await target.notes.notes(limit: 10_000).count == 2_501)252 #expect(try await target.canvases.document(world.canvas.id) == world.canvas)253 // What a capsule or a sync never carries stayed behind.254 #expect(try await target.history.visitCount() == 0)255 #expect(try await target.settings.allRaw().keys.allSatisfy { $0.hasPrefix("sync.") })256257 // Both sides then change things; a second session makes them equal again.258 try await target.notes.save(Note(title: "written on the new device", body: "b", createdAt: day(), updatedAt: day()))259 try await world.database.bookmarks.delete(world.link.id)260 var canvas = world.canvas261 canvas.title = "Renamed board"262 try await world.database.canvases.save(canvas)263 let (again, back) = try await session(source, destination, over: InMemoryBridgeTransport.pair())264 #expect(again.received == 1 && back.received == 2 && back.applied.deleted == 1)265 #expect(try await SyncedContent.of(target) == SyncedContent.of(world.database))266 #expect(try await target.bookmarks.bookmark(world.link.id) == nil)267 #expect(try await world.database.notes.notes(limit: 10_000).contains { $0.title == "written on the new device" })268 // Nothing left to exchange.269 let (idle, idleBack) = try await session(source, destination, over: InMemoryBridgeTransport.pair())270 #expect(idle.sent == 0 && idle.received == 0 && idleBack.sent == 0 && idleBack.received == 0)271 await world.database.close(); await target.close()272 }273274 @Test func aSessionOverATamperedLinkFailsWithoutApplyingAnything() async throws {275 let world = try await World.populated()276 let source = SyncCoordinator(database: world.database, configuration: SyncConfiguration(fallbackProfileID: world.profile.id))277 let (target, profile, destination) = try await device("B")278 let (a, b) = InMemoryBridgeTransport.pair()279 let hostile = HostileTransport(b)280 let offer = BridgePairingOffer()281 async let accepted = offer.accept(over: hostile)282 let initiatorChannel = try await BridgePairing.initiate(code: offer.code, over: a)283 let responderChannel = try await accepted284 await hostile.set(.flipBit(20))285 let right = Task { try await BridgeSyncSession(coordinator: destination, channel: responderChannel, deviceName: "B").run() }286 let left = Task { try await BridgeSyncSession(coordinator: source, channel: initiatorChannel, deviceName: "A").run() }287 #expect(await failure(of: right) != nil)288 #expect(await failure(of: left) != nil)289 #expect(try await target.bookmarks.all(profile: profile.id).isEmpty)290 #expect(try await target.notes.notes().isEmpty)291 await world.database.close(); await target.close()292 }293294 /// The Network.framework transport, over the loopback interface of this Mac. This is not a test between two295 /// devices: no Bonjour, no Wi-Fi, no local-network permission is involved.296 @Test func theTCPTransportCarriesASessionOverLoopback() async throws {297 let listener = try BridgeNetworkListener(serviceName: nil)298 let port = try await listener.start()299 async let incoming = listener.connections.first { _ in true }300 let client = try await NetworkBridgeTransport.connect(to: .hostPort(host: "127.0.0.1", port: port))301 let server = try #require(await incoming)302 // Framing: sizes from empty to large survive the stream.303 for size in [0, 1, 4, 65_535, 65_536, 1_000_000] {304 let frame = Data((0..<size).map { UInt8(truncatingIfNeeded: $0 &* 31) })305 try await client.send(frame)306 #expect(try await server.receive() == frame)307 }308 let world = try await World.populated()309 let source = SyncCoordinator(database: world.database, configuration: SyncConfiguration(fallbackProfileID: world.profile.id))310 let (target, _, destination) = try await device("Over TCP")311 let (left, right) = try await session(source, destination, over: (client, server))312 #expect(left.sent == 9 && right.applied.applied == 9)313 #expect(try await SyncedContent.of(target) == SyncedContent.of(world.database))314 // The session closed the link; further use reports it.315 await #expect(throws: BridgeError.self) { try await server.receive() }316 listener.stop()317 #expect(BridgeNetwork.serviceType == "_orixbridge._tcp")318 await world.database.close(); await target.close()319 }320}321322@Suite struct CloudSyncTests {323 @Test func theCloudAdapterIsOffByDefaultAndDoesNothing() async throws {324 let (database, _) = try await World.empty()325 // No container is created and no network call is made while it is disabled.326 let bridge = CloudKitBridge(containerIdentifier: "iCloud.dev.orixlab.navigator", database: database)327 #expect(bridge.isEnabled == false)328 await #expect(throws: CloudSyncError.disabled) { try await bridge.push([]) }329 await #expect(throws: CloudSyncError.disabled) { _ = try await bridge.pull() }330 await #expect(throws: CloudSyncError.disabled) { try await bridge.removeAllRemoteData() }331 let none: any CloudSyncAdapter = DisabledCloudSync()332 #expect(none.isEnabled == false)333 await #expect(throws: CloudSyncError.disabled) { _ = try await none.pull() }334 #expect(try await database.settings.allRaw().isEmpty)335 await database.close()336 }337}338