// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // The interesting cases are the ones a real peer never produces - a huge blob, // a hostile field, a flood of presences - so receive paths are fed directly, // no sockets bound. Identity now lives on the pinned TLS channel; the only // socket-bearing tests are the five TLS ones at the bottom. #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../core/security/CryptoManager.h" #include "../core/security/IdentityCertificate.h" #include "../core/security/SecretStore.h" #include "../network/DiscoverySweep.h" #include "../network/NetworkManager.h" #include "../network/PresenceService.h" #include "../network/Protocol.h" #include "../network/StunClient.h" #include "../network/TlsChannel.h" namespace koutnet { namespace { // TEST-NET-2, so the peer's claimed address can never collide with one this // machine holds, which would drop the packet as our own echoed broadcast. const QString kPeerIp = QStringLiteral("198.51.100.7"); // A second address the same peer sends from - discovery happened over one // interface, a VPN came up, and the beacon leaves by the other. const QString kPeerAltIp = QStringLiteral("198.51.100.8"); const QString kOtherIp = QStringLiteral("198.51.100.20"); const QString kSelfLabel = QStringLiteral("198.51.100.1"); double nowEpoch() { return QDateTime::currentMSecsSinceEpoch() / 1000.0; } QString freshNonce() { static int counter = 0; return QStringLiteral("%1").arg(++counter, 0, 16); } QByteArray toDatagram(const QJsonObject &obj) { return protocol::encodeFrame(obj); } // Presence is the only packet on the datagram path. It is broadcast, so it is // unsigned; the per-address counter nonce is what the receiver's replay gate // keys on, and the identity it announces stays provisional until a TLS dial // proves it with a certificate. QJsonObject presenceFrom(const CryptoManager &peer, const QString &username = QStringLiteral("peer"), const QString &ip = kPeerIp) { QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgPresence; payload[QStringLiteral("ip")] = ip; payload[QStringLiteral("ts")] = nowEpoch(); payload[QStringLiteral("nonce")] = freshNonce(); payload[QStringLiteral("username")] = username; payload[QStringLiteral("from_id")] = peer.ownIdentityId(); return payload; } // separate storage scopes, or both CryptoManagers would come up as the same // identity and every pin would match for the wrong reason. class Harness { public: Harness() : mine(QStringLiteral("nm-self")) , peer(QStringLiteral("nm-peer")) , net(&mine) { } CryptoManager mine; CryptoManager peer; NetworkManager net; }; } // namespace class NetworkManagerTest : public QObject { Q_OBJECT private Q_SLOTS: void presenceCounterSurvivesARestart(); void tlsChannelComesUpFromAnAdvertisingPeer(); void chatAndCallSignallingRideTheTlsChannel(); void filesRideTheTlsChannel(); void avatarRidesTheTlsChannel(); void voiceRidesTheTlsTransport(); void sweepBackoffGrowsThenCaps(); void stunCodec(); void malformedBytesAreRefused_data() { QTest::addColumn("raw"); QTest::newRow("empty") << QByteArray(); QTest::newRow("whitespace") << QByteArrayLiteral(" \n\t "); QTest::newRow("not json") << QByteArrayLiteral("hello there"); QTest::newRow("binary") << QByteArray("\x00\x01\x02\xFF\xFE", 5); QTest::newRow("open brace") << QByteArrayLiteral("{"); QTest::newRow("truncated object") << QByteArrayLiteral("{\"type\":\"chat\""); QTest::newRow("truncated string") << QByteArrayLiteral("{\"type\":\"cha"); QTest::newRow("trailing comma") << QByteArrayLiteral("{\"type\":\"chat\",}"); QTest::newRow("array not object") << QByteArrayLiteral("[{\"type\":\"chat\"}]"); QTest::newRow("bare null") << QByteArrayLiteral("null"); QTest::newRow("bare number") << QByteArrayLiteral("12345"); QTest::newRow("nul in the middle") << QByteArray("{\"type\":\"chat\"\x00,\"text\":\"x\"}", 27); QByteArray deep; deep.reserve(8192); deep.append(QByteArrayLiteral("{\"type\":\"chat\",\"text\":")); deep.append(QByteArray(2000, '[')); deep.append('1'); deep.append(QByteArray(2000, ']')); deep.append('}'); QTest::newRow("deeply nested") << deep; QByteArray deepObjects; for (int i = 0; i < 2000; ++i) deepObjects.append(QByteArrayLiteral("{\"a\":")); deepObjects.append('1'); deepObjects.append(QByteArray(2000, '}')); QTest::newRow("deeply nested objects") << deepObjects; QJsonObject huge; huge[QStringLiteral("type")] = protocol::kMsgChat; huge[QStringLiteral("text")] = QString(10 * 1024 * 1024, QLatin1Char('A')); QTest::newRow("ten megabytes of json") << toDatagram(huge); QTest::newRow("ten megabytes of junk") << (QByteArrayLiteral("{\"type\":") + QByteArray(10 * 1024 * 1024, 'z')); } void malformedBytesAreRefused() { QFETCH(QByteArray, raw); Harness h; QSignalSpy messages(&h.net, &NetworkManager::message); QSignalSpy online(&h.net, &NetworkManager::userOnline); QSignalSpy typing(&h.net, &NetworkManager::typing); QSignalSpy files(&h.net, &NetworkManager::fileMeta); h.net.handleDatagram(kPeerIp, raw); QCOMPARE(messages.count(), 0); QCOMPARE(online.count(), 0); QCOMPARE(typing.count(), 0); QCOMPARE(files.count(), 0); QVERIFY2(h.net.peers().isEmpty(), "a peer was recorded from a packet that never parsed"); } // The datagram path no longer carries any traffic but presence: chat, // group, call and file frames are the TLS channel's business now, and an // unsigned datagram claiming to be one of them must be dropped before a // signal can fire, whatever type name it wears. void datagramsBeyondPresenceAreDropped() { Harness h; QSignalSpy messages(&h.net, &NetworkManager::message); QSignalSpy online(&h.net, &NetworkManager::userOnline); QSignalSpy typing(&h.net, &NetworkManager::typing); QSignalSpy files(&h.net, &NetworkManager::fileMeta); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); const QList types{QString(protocol::kMsgChat), QString(protocol::kMsgPrivate), QString(protocol::kMsgGroup), QString(protocol::kMsgFileMeta), QString(protocol::kMsgFileData), QString(protocol::kMsgTyping), QString(protocol::kMsgCallReq), QString(protocol::kMsgCallAccept), QString(protocol::kMsgCallBusy), QString(protocol::kMsgCallReject), QString(protocol::kMsgCallEnd), QString(protocol::kMsgGroupInv), QString(protocol::kMsgReaction), QString(protocol::kMsgEdit), QString(protocol::kMsgDelete), QString(protocol::kMsgRead), QStringLiteral("sudo_make_me_a_sandwich")}; for (const QString &type : types) { QJsonObject o; o[QStringLiteral("type")] = type; o[QStringLiteral("text")] = QStringLiteral("trust me"); h.net.handleDatagram(kPeerIp, toDatagram(o)); } QCOMPARE(messages.count(), 0); QCOMPARE(typing.count(), 0); QCOMPARE(online.count(), 0); QCOMPARE(files.count(), 0); QVERIFY2(errors.isEmpty(), "a dropped datagram was reported as an error"); QVERIFY2(h.net.peers().isEmpty(), "a non-presence datagram filed a peer"); // presence itself is unaffected: the gate is on the datagram path, not // in the type table. h.net.handleDatagram(kPeerIp, toDatagram(presenceFrom(h.peer))); QCOMPARE(online.count(), 1); } // A few hosts stay on one interface for years, but nobody authenticates // presence - it is broadcast, there is no peer to sign for - so requiring a // signature once the peer is known only made it go stale. void presenceKeepsFlowing() { Harness h; QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); h.net.handleDatagram(kPeerIp, toDatagram(presenceFrom(h.peer))); QVERIFY(h.net.peers().contains(kPeerIp)); const double firstSeen = h.net.peers().value(kPeerIp).value(QStringLiteral("last_seen")).toDouble(); QVERIFY(firstSeen > 0.0); const QJsonObject again = presenceFrom(h.peer, QStringLiteral("peer-renamed")); QVERIFY(!again.contains(QStringLiteral("_sig"))); h.net.handleDatagram(kPeerIp, toDatagram(again)); QVERIFY2(errors.isEmpty(), "presence from an established peer was reported as unauthenticated"); QCOMPARE(h.net.peers().value(kPeerIp).value(QStringLiteral("username")).toString(), QStringLiteral("peer-renamed")); QVERIFY2(!h.net.peers().value(kPeerIp).contains(QStringLiteral("_sig")), "presence grew a signature it never carries"); } // Counter replay guard on the source address: the nonce must be strictly // greater than the last one seen from there, so a captured beacon cannot be // replayed to keep a ghost peer alive. void aReplayedPresencePacketIsRefused() { Harness h; QSignalSpy online(&h.net, &NetworkManager::userOnline); const QJsonObject first = presenceFrom(h.peer, QStringLiteral("original")); h.net.handleDatagram(kPeerIp, toDatagram(first)); QCOMPARE(online.count(), 1); QCOMPARE(h.net.peers().value(kPeerIp).value(QStringLiteral("username")).toString(), QStringLiteral("original")); QJsonObject replay = first; replay[QStringLiteral("username")] = QStringLiteral("attacker"); h.net.handleDatagram(kPeerIp, toDatagram(replay)); QCOMPARE(online.count(), 1); QCOMPARE(h.net.peers().value(kPeerIp).value(QStringLiteral("username")).toString(), QStringLiteral("original")); } // None of these fields is interpreted here, and that is the property pinned // down: chat ids are sanitised in HistoryManager, so no layer may do it half // way. void hostileFieldsStayInsideTheirHandler_data() { QTest::addColumn("chatId"); QTest::newRow("traversal") << QStringLiteral("../../../../etc/passwd"); QTest::newRow("absolute") << QStringLiteral("/etc/shadow"); QTest::newRow("windows") << QStringLiteral("..\\..\\hosts"); QTest::newRow("nul") << (QStringLiteral("public") + QChar(u'\0') + QStringLiteral("x")); QTest::newRow("newlines") << QStringLiteral("public\n[section]\nkey=value"); QTest::newRow("format string") << QStringLiteral("%s%s%s%n%p"); QTest::newRow("very long") << QString(100000, QLatin1Char('c')); QTest::newRow("empty") << QString(); } void hostileFieldsStayInsideTheirHandler() { QFETCH(QString, chatId); Harness h; QSignalSpy typing(&h.net, &NetworkManager::typing); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgTyping; o[QStringLiteral("chat_id")] = chatId; o[QStringLiteral("username")] = QStringLiteral("peer"); h.net.dispatch(kPeerIp, o); QCOMPARE(typing.count(), 1); QCOMPARE(typing.at(0).at(1).toString(), chatId); } void hostileNumbersDoNotEscapeTheirHandler_data() { QTest::addColumn("msgTs"); QTest::newRow("absurd") << QJsonValue(1e300); QTest::newRow("negative absurd") << QJsonValue(-1e300); QTest::newRow("infinity") << QJsonValue(std::numeric_limits::infinity()); QTest::newRow("nan") << QJsonValue(std::numeric_limits::quiet_NaN()); QTest::newRow("zero") << QJsonValue(0); QTest::newRow("string") << QJsonValue(QStringLiteral("not a timestamp")); QTest::newRow("object") << QJsonValue(QJsonObject{{QStringLiteral("a"), 1}}); QTest::newRow("array") << QJsonValue(QJsonArray{1, 2, 3}); QTest::newRow("null") << QJsonValue(QJsonValue::Null); } void hostileNumbersDoNotEscapeTheirHandler() { QFETCH(QJsonValue, msgTs); Harness h; QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgDelete; o[QStringLiteral("chat_id")] = QStringLiteral("public"); o[QStringLiteral("msg_ts")] = msgTs; h.net.dispatch(kPeerIp, o); QCOMPARE(messages.count(), 1); } void ahostileAllIpsListIsSurvivable_data() { QTest::addColumn("allIps"); QTest::newRow("not an array") << QJsonValue(QStringLiteral("192.0.2.1")); QTest::newRow("empty array") << QJsonValue(QJsonArray()); QTest::newRow("nested") << QJsonValue(QJsonArray{QJsonArray{QStringLiteral("a")}}); QTest::newRow("junk entries") << QJsonValue(QJsonArray{QStringLiteral("not an ip"), 42, QJsonValue::Null, QString()}); QJsonArray many; for (int i = 0; i < 5000; ++i) many.append(QStringLiteral("10.0.%1.%2").arg(i / 256).arg(i % 256)); QTest::newRow("five thousand addresses") << QJsonValue(many); } void ahostileAllIpsListIsSurvivable() { QFETCH(QJsonValue, allIps); Harness h; QSignalSpy online(&h.net, &NetworkManager::userOnline); QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("all_ips")] = allIps; h.net.handleDatagram(kPeerIp, toDatagram(presence)); QCOMPARE(online.count(), 1); QCOMPARE(h.net.peers().size(), 1); QVERIFY(h.net.peers().contains(kPeerIp)); } // Our own broadcast comes back on every interface we sent it on. void ourOwnPacketsAreDropped() { Harness h; QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = h.net.hostIp(); h.net.handleDatagram(kPeerIp, toDatagram(presence)); QVERIFY2(h.net.peers().isEmpty(), "a presence claiming an address of ours was filed"); h.net.handleDatagram(h.net.hostIp(), toDatagram(presenceFrom(h.peer))); QVERIFY2(h.net.peers().isEmpty(), "a presence arriving from an address of ours was filed"); } // one peer on two interfaces is one person, and the peer table records the // address its packets came from, not the one it asked to be called. void amultiHomedPeerIsOneContact() { Harness h; QSignalSpy online(&h.net, &NetworkManager::userOnline); h.net.handleDatagram(kPeerIp, toDatagram(presenceFrom(h.peer, QStringLiteral("peer"), kOtherIp))); QCOMPARE(online.count(), 1); QCOMPARE(h.net.peers().size(), 1); QVERIFY2(h.net.peers().contains(kPeerIp), "the peer was filed under the address it asked for rather than the one it sent from"); QVERIFY(!h.net.peers().contains(kOtherIp)); QCOMPARE(h.net.peers().value(kPeerIp).value(QStringLiteral("ip")).toString(), kPeerIp); QCOMPARE(h.net.peers().value(kPeerIp).value(QStringLiteral("advertised_ip")).toString(), kOtherIp); h.net.handleDatagram(kPeerAltIp, toDatagram(presenceFrom(h.peer, QStringLiteral("peer"), kPeerAltIp))); QCOMPARE(h.net.peers().size(), 1); QVERIFY(h.net.peers().contains(kPeerIp)); QCOMPARE(online.count(), 1); } // Presence is unsigned and broadcast, so it is the cheapest packet to // forge; the per-address cap keeps a spoofed flood from doing anything but // wasting a little bandwidth, and the peer table must not grow with it. void theRateLimitStopsAFlood() { Harness h; QSignalSpy online(&h.net, &NetworkManager::userOnline); QSignalSpy refreshed(&h.net, &NetworkManager::peerRefreshed); for (int i = 0; i < 50; ++i) h.net.handleDatagram(kPeerIp, toDatagram(presenceFrom(h.peer))); QCOMPARE(online.count(), 1); const int arrivals = online.count() + refreshed.count(); QVERIFY2(arrivals <= 10, "the per-IP presence cap let a whole flood through"); QVERIFY2(arrivals >= 1, "even the first presence of the burst was dropped"); QCOMPARE(h.net.peers().size(), 1); } // no socket exists before start(), so test the decision only: // which configured addresses get the unicast presence. void staticPeerTargetsAreChosenWithoutANetwork() { const QMap none; QVERIFY(PresenceService::staticUnicastTargets({}, none, kSelfLabel).isEmpty()); const QStringList configured = {QStringLiteral("10.13.4.9"), QStringLiteral("not an address"), QStringLiteral("172.16.0.1")}; QCOMPARE(PresenceService::staticUnicastTargets(configured, none, kSelfLabel), QStringList({QStringLiteral("10.13.4.9"), QStringLiteral("172.16.0.1")})); QMap known; known.insert(QStringLiteral("10.13.4.9"), QJsonObject()); const QStringList targets = PresenceService::staticUnicastTargets(configured, known, kSelfLabel); QVERIFY(!targets.contains(QStringLiteral("10.13.4.9"))); QVERIFY2(targets == QStringList({QStringLiteral("172.16.0.1")}), "a known peer was sent a presence reminder"); QCOMPARE(PresenceService::staticUnicastTargets(configured, none, QStringLiteral("172.16.0.1")), QStringList({QStringLiteral("10.13.4.9")})); } // A reaction is a message packet like any other off the channel: whatever // arrives is handed to the interface as it came, untouched by any cipher. void aReactionPacketCarriesItsFields() { Harness h; QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgReaction; o[QStringLiteral("chat_id")] = QStringLiteral("public"); o[QStringLiteral("msg_ts")] = 1774038261.5; o[QStringLiteral("emoji")] = QStringLiteral(":)"); o[QStringLiteral("added")] = false; h.net.dispatch(kPeerIp, o); QCOMPARE(messages.count(), 1); const QJsonObject got = messages.at(0).at(0).toJsonObject(); QCOMPARE(got.value(QStringLiteral("type")).toString(), QStringLiteral("reaction")); QCOMPARE(got.value(QStringLiteral("emoji")).toString(), QStringLiteral(":)")); QCOMPARE(got.value(QStringLiteral("added")).toBool(), false); QCOMPARE(got.value(QStringLiteral("msg_ts")).toDouble(), 1774038261.5); QCOMPARE(got.value(QStringLiteral("chat_id")).toString(), QStringLiteral("public")); } // A private message was what was actually being lost, and it has one more way // to go missing: the "to" field used to be compared against our primary // address alone. void aPrivateMessageToAnyOfOurAddressesArrives() { Harness h; QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgPrivate; o[QStringLiteral("to")] = h.net.hostIp(); o[QStringLiteral("text")] = QStringLiteral("still there?"); h.net.dispatch(kPeerAltIp, o); QCOMPARE(messages.count(), 1); QJsonObject elsewhere = o; elsewhere[QStringLiteral("to")] = kOtherIp; h.net.dispatch(kPeerAltIp, elsewhere); QCOMPARE(messages.count(), 1); } void aCallRequestWhileInACallIsMetWithBusyInsteadOfRinging() { Harness h; QSignalSpy ringing(&h.net, &NetworkManager::callRequest); QSignalSpy rejected(&h.net, &NetworkManager::callRejected); h.net.setActiveCalls({kOtherIp}); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallReq; o[QStringLiteral("username")] = QStringLiteral("peer"); h.net.dispatch(kPeerIp, o); QVERIFY2(ringing.isEmpty(), "a second call rang while one was live"); QVERIFY2(rejected.isEmpty(), "the busy reply leaked out of the state machine as a rejection"); // with no call live the same packet rings normally again. h.net.setActiveCalls({}); h.net.dispatch(kPeerIp, o); QCOMPARE(ringing.count(), 1); } // a call_accept without a pending request must be dropped, otherwise any // channel-holder could open our microphone. void aCallAcceptWithoutARequestWeSentIsDropped() { Harness h; QSignalSpy accepted(&h.net, &NetworkManager::callAccepted); QSignalSpy ended(&h.net, &NetworkManager::callEnded); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallAccept; o[QStringLiteral("username")] = QStringLiteral("peer"); h.net.dispatch(kPeerIp, o); h.net.dispatch(kPeerIp, o); QVERIFY2(accepted.isEmpty(), "a call_accept for a call nobody asked for completed a call"); QVERIFY2(ended.isEmpty(), "the forged accept left ringing state behind"); } void aCallAcceptAnswersOnlyTheRequestWeSent() { Harness h; QSignalSpy accepted(&h.net, &NetworkManager::callAccepted); h.net.m_router.openRequest(kPeerIp); // the "we dialed" side of a placed request QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallAccept; o[QStringLiteral("username")] = QStringLiteral("peer"); h.net.dispatch(kPeerIp, o); QCOMPARE(accepted.count(), 1); // the pending slot is spent: a second accept, and an accept from a peer // we never called, both complete nothing. h.net.dispatch(kPeerIp, o); QCOMPARE(accepted.count(), 1); } void aCallEndForACallThatDoesNotExistIsDropped() { Harness h; QSignalSpy ended(&h.net, &NetworkManager::callEnded); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallEnd; h.net.dispatch(kPeerIp, o); QVERIFY2(ended.isEmpty(), "a call_end for a call in no state cancelled something"); // but it cancels a ring: a call_req we let through, then the caller // giving up, is exactly the "caller abandoned the ring" case. QSignalSpy ringing(&h.net, &NetworkManager::callRequest); QJsonObject req; req[QStringLiteral("type")] = protocol::kMsgCallReq; req[QStringLiteral("username")] = QStringLiteral("peer"); h.net.dispatch(kPeerIp, req); QCOMPARE(ringing.count(), 1); h.net.dispatch(kPeerIp, o); QCOMPARE(ended.count(), 1); // and a call_end that never matched a ring must not fire twice. h.net.dispatch(kPeerIp, o); QCOMPARE(ended.count(), 1); } void aCallEndCancelsAnActiveCall() { Harness h; QSignalSpy ended(&h.net, &NetworkManager::callEnded); h.net.setActiveCalls({kPeerIp}); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallEnd; h.net.dispatch(kPeerIp, o); QCOMPARE(ended.count(), 1); } void aRejectAnswersOnlyTheRequestWeSent() { Harness h; QSignalSpy rejected(&h.net, &NetworkManager::callRejected); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgCallReject; h.net.dispatch(kPeerIp, o); QVERIFY2(rejected.isEmpty(), "a call_reject for a call nobody asked for surfaced a rejection"); h.net.m_router.openRequest(kPeerIp); h.net.dispatch(kPeerIp, o); QCOMPARE(rejected.count(), 1); // the slot is spent; an accept arriving for the same call is stale. h.net.dispatch(kPeerIp, o); QCOMPARE(rejected.count(), 1); } // A group sealed under its own key opens for a member holding that key, // with no shared passphrase set at all - the per-group state in action. void aGroupMessageSealedUnderItsOwnKeyIsReadBack() { Harness h; h.net.setGroupKey(QStringLiteral("g1"), QStringLiteral("k1")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("gid")] = QStringLiteral("g1"); o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("per group"), QStringLiteral("k1")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); const QJsonObject got = messages.at(0).at(0).toJsonObject(); QCOMPARE(got.value(QStringLiteral("text")).toString(), QStringLiteral("per group")); } // Message sealed under a different group key must not open here, should // show decrypt error, not the text. void aGroupMessageSealedUnderAnotherKeyNeverOpensHere() { Harness h; h.net.setGroupKey(QStringLiteral("g1"), QStringLiteral("k1")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("gid")] = QStringLiteral("g1"); o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("from another group"), QStringLiteral("k2")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); const QString text = messages.at(0).at(0).toJsonObject().value(QStringLiteral("text")).toString(); QVERIFY(!text.isEmpty()); QVERIFY(text != QStringLiteral("from another group")); } // A group that predates per-group keys keeps working on the shared // passphrase - the only key its members were ever given. The gid alone is // not what decides: the gid must have a key of its own to leave the // fallback. void aGroupWithoutItsOwnKeyUsesTheSharedPassphrase() { Harness h; h.net.setGroupPassphrase(QStringLiteral("gruppo")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("gid")] = QStringLiteral("old"); o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("still shared"), QStringLiteral("gruppo")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); const QJsonObject got = messages.at(0).at(0).toJsonObject(); QCOMPARE(got.value(QStringLiteral("text")).toString(), QStringLiteral("still shared")); } // an invite from a peer we share a pinned channel with delivers the group // key in the clear of that channel: the pin already proved to whom it goes. // The invite lands, the key is stored under the gid, and a message sealed // under it reads back afterwards. void anInviteDeliversTheGroupKeyOverTheChannel() { Harness h; QSignalSpy invites(&h.net, &NetworkManager::groupInvite); QJsonObject inv; inv[QStringLiteral("type")] = protocol::kMsgGroupInv; inv[QStringLiteral("gid")] = QStringLiteral("g2"); inv[QStringLiteral("gname")] = QStringLiteral("crew"); inv[QStringLiteral("key")] = QStringLiteral("k2"); h.net.dispatch(kPeerIp, inv); QCOMPARE(invites.count(), 1); QCOMPARE(invites.at(0).at(0).toString(), QStringLiteral("g2")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("gid")] = QStringLiteral("g2"); o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("invited and keyed"), QStringLiteral("k2")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); const QJsonObject got = messages.at(0).at(0).toJsonObject(); QCOMPARE(got.value(QStringLiteral("text")).toString(), QStringLiteral("invited and keyed")); } // A pinned group key is not replaced by a later invite carrying a different // key. Any peer we share a channel with can send an invite, so a silent // overwrite would hand the whole group to an attacker's key; the mismatch // is surfaced for the UI to confirm instead. void aConflictingGroupKeyIsRefusedAndSurfaced() { Harness h; h.net.setGroupKey(QStringLiteral("g3"), QStringLiteral("pinned")); QSignalSpy confirmation(&h.net, &NetworkManager::groupKeyConfirmationRequired); QJsonObject inv; inv[QStringLiteral("type")] = protocol::kMsgGroupInv; inv[QStringLiteral("gid")] = QStringLiteral("g3"); inv[QStringLiteral("gname")] = QStringLiteral("crew"); inv[QStringLiteral("key")] = QStringLiteral("intruder"); h.net.dispatch(kPeerIp, inv); QTRY_COMPARE(confirmation.count(), 1); QCOMPARE(confirmation.at(0).at(0).toString(), QStringLiteral("g3")); // the pinned key is untouched: a message sealed under it still reads, // and one sealed under the intruder key never opens. QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("gid")] = QStringLiteral("g3"); o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("still pinned"), QStringLiteral("pinned")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); QCOMPARE(messages.at(0).at(0).toJsonObject().value(QStringLiteral("text")).toString(), QStringLiteral("still pinned")); } // Re-delivery of the very same key is an idempotent re-invite, not a // rotation: no state change, and no question put to the UI. void anIdenticalGroupKeyReinviteIsSilent() { Harness h; h.net.setGroupKey(QStringLiteral("g4"), QStringLiteral("k1")); QSignalSpy confirmation(&h.net, &NetworkManager::groupKeyConfirmationRequired); QJsonObject inv; inv[QStringLiteral("type")] = protocol::kMsgGroupInv; inv[QStringLiteral("gid")] = QStringLiteral("g4"); inv[QStringLiteral("gname")] = QStringLiteral("crew"); inv[QStringLiteral("key")] = QStringLiteral("k1"); h.net.dispatch(kPeerIp, inv); QCOMPARE(confirmation.count(), 0); } // the Argon2id receive path: a passphrase-sealed message with a fresh salt // is decrypted on the worker thread and arrives through the queue. The text // is sealed under the shared passphrase rather than a session - that is // what a group message carries however it arrived. void aPassphraseMessageArrivesThroughTheAsyncPipeline() { Harness h; h.net.setGroupPassphrase(QStringLiteral("gruppo")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("il segreto"), QStringLiteral("gruppo")); h.net.dispatch(kPeerIp, o); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 1, 30000); const QJsonObject got = messages.at(0).at(0).toJsonObject(); QCOMPARE(got.value(QStringLiteral("text")).toString(), QStringLiteral("il segreto")); } // A sealed message arriving behind another sealed one must not overtake it: // the chat renders in arrival order, whatever the decryption cost of the // message in front. Over the channel a derivation can take hundreds of // milliseconds, which is the gap between the two sends here. void aQueuedMessageWaitsBehindAnAsyncOne() { Harness h; h.net.setGroupPassphrase(QStringLiteral("gruppo")); QSignalSpy messages(&h.net, &NetworkManager::message); QJsonObject slow; slow[QStringLiteral("type")] = protocol::kMsgChat; slow[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("first"), QStringLiteral("gruppo")); h.net.dispatch(kPeerIp, slow); QJsonObject fast; fast[QStringLiteral("type")] = protocol::kMsgChat; fast[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("second"), QStringLiteral("gruppo")); h.net.dispatch(kPeerIp, fast); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == 2, 30000); QCOMPARE(messages.at(0).at(0).toJsonObject().value(QStringLiteral("text")).toString(), QStringLiteral("first")); QCOMPARE(messages.at(1).at(0).toJsonObject().value(QStringLiteral("text")).toString(), QStringLiteral("second")); } // Fresh-salt flood fills the queue (1 in flight + 8 queued), rest is // dropped. GUI thread stays responsive. void anAsyncFloodDropsMessagesInsteadOfMemory() { Harness h; h.net.setGroupPassphrase(QStringLiteral("gruppo")); QSignalSpy messages(&h.net, &NetworkManager::message); for (int i = 0; i < 30; ++i) { QJsonObject o; o[QStringLiteral("type")] = protocol::kMsgGroup; o[QStringLiteral("text")] = h.peer.encrypt(QStringLiteral("spam-%1").arg(i), QStringLiteral("gruppo")); h.net.dispatch(kPeerIp, o); } // one in flight plus kMaxPendingDecrypts queued can get through; the // in-flight head holds a queue slot, so that is kMaxPendingDecrypts // arrivals in total. The rest were refused at the queue gate. QTRY_VERIFY_WITH_TIMEOUT(messages.count() >= 1, 60000); QTRY_VERIFY_WITH_TIMEOUT(messages.count() == koutnet::CryptoManager::kMaxPendingDecrypts, 60000); } void sendFileMissingReturnsFalse() { Harness h; QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); QVERIFY(!h.net.sendFile(kPeerIp, QStringLiteral("/no/such/file.bin"))); QCOMPARE(errors.count(), 1); } }; // A restarted process must not go back to nonce zero, or every peer that // ever accepted one of our presences would drop the post-restart beacons as // replays forever. The park file carries the counter across the restart. void NetworkManagerTest::presenceCounterSurvivesARestart() { koutnet::NetworkManager first(nullptr); QFile::remove(first.m_presence.nonceCounterPath()); first.m_presence.reloadCounter(); const quint64 firstNonce = first.m_presence.takeNonce(); const quint64 secondNonce = first.m_presence.takeNonce(); QVERIFY(secondNonce > firstNonce); // a fresh object is the "restarted process": it rehydrates the park file // and must emit strictly past the last value the old process did koutnet::NetworkManager restarted(nullptr); restarted.m_presence.reloadCounter(); QCOMPARE(restarted.m_presence.takeNonce(), secondNonce + 1); } void NetworkManagerTest::tlsChannelComesUpFromAnAdvertisingPeer() { // The one test here that opens real sockets: presence is fed in as bytes, // but the advertised TLS port is answered with a live TLS 1.3 handshake on // loopback, so the whole "a peer says where it listens, we dial and its // certificate proves who it is" story runs end to end. Harness h; // the far side is a real TlsChannel wearing the peer's identity. const koutnet::IdentityCertificate peerCert = koutnet::buildIdentityCertificate(h.peer.identitySeed(), h.peer.ownIdentityId()); QVERIFY(peerCert.isValid()); koutnet::TlsChannel peerCh(peerCert); QVERIFY(peerCh.listen(0)); // our side runs the real start() path, which builds its own TlsChannel // from the identity seed and binds the UDP presence port. QVERIFY(h.net.start()); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); // presence from the peer: loopback, and advertising where it listens. QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = QStringLiteral("127.0.0.1"); presence[QStringLiteral("tls_port")] = int(peerCh.listenPort()); h.net.handleDatagram(QStringLiteral("127.0.0.1"), toDatagram(presence)); // both ends authenticate: ours trusted the peer's certificate... QTRY_VERIFY_WITH_TIMEOUT(h.net.hasTlsPeer(h.peer.ownIdentityId()), 30000); // ...and the peer trusted ours (its TOFU gate pinned us in turn). QTRY_VERIFY_WITH_TIMEOUT(peerCh.hasPeer(h.mine.ownIdentityId()), 30000); QVERIFY(errors.isEmpty()); h.net.stop(); } void NetworkManagerTest::chatAndCallSignallingRideTheTlsChannel() { // Where the datagram path once sealed each message by hand, the TLS path // must hand the very frame it received onward: transport encryption replaced // the per-link session cipher. That is what this test pins down - both // directions over one authenticated channel, bodies arriving plaintext. Harness h; const koutnet::IdentityCertificate peerCert = koutnet::buildIdentityCertificate(h.peer.identitySeed(), h.peer.ownIdentityId()); QVERIFY(peerCert.isValid()); koutnet::TlsChannel peerCh(peerCert); QVERIFY(peerCh.listen(0)); // every frame the peer's channel receives, tagged with the sender's id. QSignalSpy peerFrames(&peerCh, &koutnet::TlsChannel::frameReceived); QVERIFY(h.net.start()); QSignalSpy messages(&h.net, &NetworkManager::message); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = QStringLiteral("127.0.0.1"); presence[QStringLiteral("tls_port")] = int(peerCh.listenPort()); h.net.handleDatagram(QStringLiteral("127.0.0.1"), toDatagram(presence)); QTRY_VERIFY_WITH_TIMEOUT(h.net.hasTlsPeer(h.peer.ownIdentityId()), 30000); // the peer pushes a chat frame down the channel; mine hands it to the UI // already decrypted by the transport. QJsonObject inbound; inbound[QStringLiteral("type")] = protocol::kMsgChat; inbound[QStringLiteral("text")] = QStringLiteral("hi over tls"); peerCh.sendPeer(h.mine.ownIdentityId(), protocol::encodeFrame(inbound)); QTRY_COMPARE_WITH_TIMEOUT(messages.count(), 1, 30000); const QJsonObject seen = messages.at(0).at(0).toJsonObject(); QCOMPARE(seen.value(QStringLiteral("text")).toString(), QStringLiteral("hi over tls")); QCOMPARE(seen.value(QStringLiteral("via_tls")).toBool(), true); // ours goes out as a plain protocol frame, not a sealed datagram. QVERIFY(h.net.sendPrivate(QStringLiteral("thanks"), QStringLiteral("127.0.0.1"))); QTRY_COMPARE_WITH_TIMEOUT(peerFrames.count(), 1, 30000); QString type; QJsonObject decoded; QVERIFY(protocol::decodeFrame(peerFrames.at(0).at(1).toByteArray(), type, decoded)); QCOMPARE(type, QString(protocol::kMsgPrivate)); QCOMPARE(decoded.value(QStringLiteral("text")).toString(), QStringLiteral("thanks")); // call signalling is control traffic and rides the same reliable channel. QVERIFY(h.net.canUseTls(QStringLiteral("127.0.0.1"))); h.net.sendCallRequest(QStringLiteral("127.0.0.1")); QTRY_COMPARE_WITH_TIMEOUT(peerFrames.count(), 2, 30000); QVERIFY(protocol::decodeFrame(peerFrames.at(1).at(1).toByteArray(), type, decoded)); QCOMPARE(type, QString(protocol::kMsgCallReq)); QVERIFY(errors.isEmpty()); h.net.stop(); } void NetworkManagerTest::filesRideTheTlsChannel() { // File bytes over the channel are not a sealed datagram stream: the meta // says encrypted=false and the chunks come back byte-identical, because // the transport did the protecting and ordering. In the other direction // mine must reassemble what the peer sends and answer with an ack over // the same channel. Harness h; const koutnet::IdentityCertificate peerCert = koutnet::buildIdentityCertificate(h.peer.identitySeed(), h.peer.ownIdentityId()); QVERIFY(peerCert.isValid()); koutnet::TlsChannel peerCh(peerCert); QVERIFY(peerCh.listen(0)); QSignalSpy peerFrames(&peerCh, &koutnet::TlsChannel::frameReceived); QSignalSpy filesMeta(&h.net, &NetworkManager::fileMeta); QSignalSpy fileChunks(&h.net, &NetworkManager::fileChunkBytes); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); QVERIFY(h.net.start()); QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = QStringLiteral("127.0.0.1"); presence[QStringLiteral("tls_port")] = int(peerCh.listenPort()); h.net.handleDatagram(QStringLiteral("127.0.0.1"), toDatagram(presence)); QTRY_VERIFY_WITH_TIMEOUT(h.net.hasTlsPeer(h.peer.ownIdentityId()), 30000); // --- peer -> mine: meta + chunks arrive, reassemble, ack rides back. --- const QByteArray payload = QByteArray("the quick brown fox jumps over the lazy dog\n").repeated(4000); const QString tid = QStringLiteral("a-file-tid"); QJsonObject meta; meta[QStringLiteral("type")] = protocol::kMsgFileMeta; meta[QStringLiteral("tid")] = tid; meta[QStringLiteral("filename")] = QStringLiteral("fox.txt"); meta[QStringLiteral("size")] = payload.size(); meta[QStringLiteral("is_image")] = false; meta[QStringLiteral("encrypted")] = false; meta[QStringLiteral("from_ip")] = QStringLiteral("127.0.0.1"); peerCh.sendPeer(h.mine.ownIdentityId(), protocol::encodeFrame(meta)); const int peerChunkBytes = 256 * 1024; const int totalChunks = (payload.size() + peerChunkBytes - 1) / peerChunkBytes; for (int idx = 0; idx < totalChunks; ++idx) { QCborMap c; c[QStringLiteral("type")] = protocol::kMsgFileData; c[QStringLiteral("tid")] = tid; c[QStringLiteral("idx")] = idx; c[QStringLiteral("total")] = totalChunks; c[QStringLiteral("data")] = payload.mid(idx * peerChunkBytes, peerChunkBytes); peerCh.sendPeer(h.mine.ownIdentityId(), protocol::encodeFrame(c)); } QTRY_COMPARE_WITH_TIMEOUT(fileChunks.count(), totalChunks, 30000); qint64 reaped = 0; for (int i = 0; i < fileChunks.count(); ++i) { const QVariantList args = fileChunks.at(i); // host, tid, idx, total, chunk QCOMPARE(args.at(0).toString(), QStringLiteral("127.0.0.1")); QCOMPARE(args.at(1).toString(), tid); reaped += args.at(4).toByteArray().size(); } QCOMPARE(reaped, qint64(payload.size())); QTRY_COMPARE_WITH_TIMEOUT(filesMeta.count(), 1, 30000); QCOMPARE(filesMeta.at(0).at(0).toString(), QStringLiteral("127.0.0.1")); QCOMPARE(filesMeta.at(0).at(1).toJsonObject().value(QStringLiteral("encrypted")).toBool(), false); // mine answers on the channel it was fed from: the peer must see the ack. QTRY_VERIFY_WITH_TIMEOUT(peerFrames.count() >= 1, 30000); QString type; QJsonObject decoded; QVERIFY(protocol::decodeFrame(peerFrames.at(0).at(1).toByteArray(), type, decoded)); QCOMPARE(type, QString(protocol::kMsgFileAck)); QCOMPARE(decoded.value(QStringLiteral("tid")).toString(), tid); // --- mine -> peer: a real temp file, sent through the app path. --- QTemporaryFile tmp; QVERIFY(tmp.open()); tmp.write(payload); tmp.flush(); tmp.close(); QVERIFY(h.net.sendFile(QStringLiteral("127.0.0.1"), tmp.fileName())); QTRY_VERIFY_WITH_TIMEOUT(peerFrames.count() >= 3, 30000); // ack + meta + one chunk QJsonObject sentMeta; QByteArray sentBytes; bool sawMeta = false; for (int i = 1; i < peerFrames.count(); ++i) { QVERIFY(protocol::decodeFrame(peerFrames.at(i).at(1).toByteArray(), type, decoded)); if (type == protocol::kMsgFileMeta) { sentMeta = decoded; sawMeta = true; } else if (type == protocol::kMsgFileData) { sentBytes += QByteArray::fromBase64(decoded.value(QStringLiteral("data")).toString().toLatin1()); } } QVERIFY2(sawMeta, "the peer never saw the outgoing meta"); QCOMPARE(sentMeta.value(QStringLiteral("encrypted")).toBool(), false); QCOMPARE(sentMeta.value(QStringLiteral("size")).toInt(), payload.size()); QCOMPARE(sentBytes.size(), payload.size()); QCOMPARE(sentBytes, payload); QVERIFY(errors.isEmpty()); h.net.stop(); } void NetworkManagerTest::avatarRidesTheTlsChannel() { // The picture is not a presence field: it is image bytes, and the TLS // channel is the only transport that could carry them ((a) as they are, and // (b) attached to the identity the certificate just proved). This pins the // whole path - the peer pushes a frame and checks it landed out-of-band, // ours downloads it to a local file the UI can load without any authority, // then ours sends its own avatar back and the peer sees it arrive. Harness h; const koutnet::IdentityCertificate peerCert = koutnet::buildIdentityCertificate(h.peer.identitySeed(), h.peer.ownIdentityId()); QVERIFY(peerCert.isValid()); koutnet::TlsChannel peerCh(peerCert); QVERIFY(peerCh.listen(0)); QSignalSpy peerFrames(&peerCh, &koutnet::TlsChannel::frameReceived); QSignalSpy avatars(&h.net, &NetworkManager::peerAvatar); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); // give the network manager a real avatar file, like main.cpp does. QTemporaryFile image; QVERIFY(image.open()); image.write(QByteArrayLiteral("\x89PNG\r\n\x1a\nfake-png-bytes")); image.flush(); image.close(); QVERIFY(h.net.start()); h.net.setAvatar(image.fileName()); QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = QStringLiteral("127.0.0.1"); presence[QStringLiteral("tls_port")] = int(peerCh.listenPort()); h.net.handleDatagram(QStringLiteral("127.0.0.1"), toDatagram(presence)); QTRY_VERIFY_WITH_TIMEOUT(h.net.hasTlsPeer(h.peer.ownIdentityId()), 30000); // once the channel is up, our picture rides out of its own accord... QTRY_VERIFY_WITH_TIMEOUT(peerFrames.count() >= 1, 30000); QString type; QJsonObject decoded; bool sawOwn = false; for (int i = 0; i < peerFrames.count(); ++i) { if (!protocol::decodeFrame(peerFrames.at(i).at(1).toByteArray(), type, decoded)) continue; if (type == protocol::kMsgAvatar && decoded.value(QStringLiteral("sha")).toString().size() == 64) { sawOwn = true; QCOMPARE(QByteArray::fromBase64(decoded.value(QStringLiteral("data")).toString().toLatin1()), QByteArrayLiteral("\x89PNG\r\n\x1a\nfake-png-bytes")); break; } } QVERIFY2(sawOwn, "the peer never saw our avatar frame"); // ...and a frame the peer sends lands as a local file under our port. QJsonObject inbound; inbound[QStringLiteral("type")] = protocol::kMsgAvatar; inbound[QStringLiteral("sha")] = QString::fromLatin1(QCryptographicHash::hash(QByteArrayLiteral("peer-faces"), QCryptographicHash::Sha256).toHex()); inbound[QStringLiteral("ext")] = QStringLiteral("png"); inbound[QStringLiteral("data")] = QString::fromLatin1(QByteArrayLiteral("we-are-prepared").toBase64()); peerCh.sendPeer(h.mine.ownIdentityId(), protocol::encodeFrame(inbound)); QTRY_COMPARE_WITH_TIMEOUT(avatars.count(), 1, 30000); const QString fromIp = avatars.at(0).at(0).toString(); const QString source = avatars.at(0).at(1).toString(); QCOMPARE(fromIp, QStringLiteral("127.0.0.1")); QVERIFY2(source.startsWith(QStringLiteral("file://")), qPrintable(source)); QFile mirror(source.mid(7)); // strip file:// for the local path QVERIFY(mirror.open(QIODevice::ReadOnly)); QCOMPARE(mirror.readAll(), QByteArrayLiteral("we-are-prepared")); // an empty frame clears it again (the peer deleted its avatar). QJsonObject gone = inbound; gone[QStringLiteral("data")] = QString(); peerCh.sendPeer(h.mine.ownIdentityId(), protocol::encodeFrame(gone)); QTRY_COMPARE_WITH_TIMEOUT(avatars.count(), 2, 30000); QVERIFY2(avatars.at(1).at(1).toString().isEmpty(), "an empty data frame should clear the avatar"); QVERIFY(errors.isEmpty()); h.net.stop(); } void NetworkManagerTest::voiceRidesTheTlsTransport() { // The voice TCP port is TLS-wrapped: a caller dials with its identity // certificate, the accept side only admits identities the chat channel has // already pinned, and the length-prefixed audio frames then travel inside // the handshake. A stranger with a valid certificate and no pin gets the // connection closed at the gate - no seat, no call, no microphone. Harness h; const koutnet::IdentityCertificate peerCert = koutnet::buildIdentityCertificate(h.peer.identitySeed(), h.peer.ownIdentityId()); QVERIFY(peerCert.isValid()); koutnet::TlsChannel peerCh(peerCert); QVERIFY(peerCh.listen(0)); QSignalSpy voiceConnected(&h.net, &NetworkManager::voiceConnected); QSignalSpy voiceData(&h.net, &NetworkManager::voiceDataFrom); QSignalSpy errors(&h.net, &NetworkManager::errorOccurred); QVERIFY(h.net.start()); QVERIFY2(h.net.m_voice.overTls(), "voice transport should be TLS when an identity is present"); QJsonObject presence = presenceFrom(h.peer); presence[QStringLiteral("ip")] = QStringLiteral("127.0.0.1"); presence[QStringLiteral("tls_port")] = int(peerCh.listenPort()); h.net.handleDatagram(QStringLiteral("127.0.0.1"), toDatagram(presence)); QTRY_VERIFY_WITH_TIMEOUT(h.net.hasTlsPeer(h.peer.ownIdentityId()), 30000); // the peer dials our voice port with its own identity certificate. QSslConfiguration cfg = QSslConfiguration::defaultConfiguration(); cfg.setProtocol(QSsl::TlsV1_3OrLater); cfg.setLocalCertificate(peerCert.cert); cfg.setPrivateKey(peerCert.key); cfg.setPeerVerifyMode(QSslSocket::VerifyNone); auto *peerVoice = new QSslSocket(this); peerVoice->setSslConfiguration(cfg); peerVoice->connectToHostEncrypted(QStringLiteral("127.0.0.1"), h.net.m_voice.port()); QTRY_COMPARE_WITH_TIMEOUT(voiceConnected.count(), 1, 30000); QCOMPARE(voiceConnected.at(0).at(0).toString(), QStringLiteral("127.0.0.1")); // ours out: the peer must read exactly the frame sendVoice wrote. const QByteArray frameA = QByteArray("pcm-sample-bytes\n").repeated(10); QVERIFY(h.net.sendVoice(QStringLiteral("127.0.0.1"), frameA)); QByteArray rx; const auto drain = [&] { const QByteArray more = peerVoice->readAll(); if (!more.isEmpty()) rx += more; }; connect(peerVoice, &QSslSocket::readyRead, this, drain); QTRY_VERIFY_WITH_TIMEOUT(rx.size() >= int(protocol::kFrameHeaderBytes) + frameA.size(), 30000); const quint32 announced = quint32((uchar(rx.at(0)) << 24) | (uchar(rx.at(1)) << 16) | (uchar(rx.at(2)) << 8) | uchar(rx.at(3))); QCOMPARE(int(announced), frameA.size()); QCOMPARE(rx.mid(int(protocol::kFrameHeaderBytes), frameA.size()), frameA); // theirs in: mine reassembles and surfaces the same bytes. QByteArray frameHead(4, '\0'); frameHead[0] = char((frameA.size() >> 24) & 0xFF); frameHead[1] = char((frameA.size() >> 16) & 0xFF); frameHead[2] = char((frameA.size() >> 8) & 0xFF); frameHead[3] = char(frameA.size() & 0xFF); peerVoice->write(frameHead + frameA); QTRY_COMPARE_WITH_TIMEOUT(voiceData.count(), 1, 30000); QCOMPARE(voiceData.at(0).at(0).toString(), QStringLiteral("127.0.0.1")); QCOMPARE(voiceData.at(0).at(1).toByteArray(), frameA); QVERIFY(errors.isEmpty()); // a stranger with an identity nobody has pinned is let through the TLS // handshake and then closed at the gate: listening, but never seated. const koutnet::CryptoManager stranger(QStringLiteral("nm-voice-stranger")); const koutnet::IdentityCertificate strangerCert = koutnet::buildIdentityCertificate(stranger.identitySeed(), stranger.ownIdentityId()); QVERIFY(strangerCert.isValid()); QSslConfiguration scfg = QSslConfiguration::defaultConfiguration(); scfg.setProtocol(QSsl::TlsV1_3OrLater); scfg.setLocalCertificate(strangerCert.cert); scfg.setPrivateKey(strangerCert.key); scfg.setPeerVerifyMode(QSslSocket::VerifyNone); auto *strangerSock = new QSslSocket(this); strangerSock->setSslConfiguration(scfg); QSignalSpy strangerGone(strangerSock, &QSslSocket::disconnected); strangerSock->connectToHostEncrypted(QStringLiteral("127.0.0.1"), h.net.m_voice.port()); QTRY_COMPARE_WITH_TIMEOUT(strangerGone.count(), 1, 30000); QCOMPARE(voiceConnected.count(), 1); // the gate did not seat the stranger QVERIFY(errors.isEmpty()); h.net.stop(); } } // namespace koutnet // Test mode keeps CryptoManager's config lookups in a scratch directory. No // sockets are bound; QCoreApplication is only needed for the classes' timers. int main(int argc, char *argv[]) { QStandardPaths::setTestModeEnabled(true); // See CryptoManagerTest's main(): test mode does not move the store, and the // identities below are not things to leave in a real keyring. koutnet::SecretStore::setInMemoryOnly(true); QCoreApplication app(argc, argv); // without a domain ki18n warns on every string, burying the test output. KLocalizedString::setApplicationDomain(QByteArrayLiteral("koutnet")); QCoreApplication::setOrganizationName(QStringLiteral("koutnet-tests")); QCoreApplication::setApplicationName(QStringLiteral("network-manager")); koutnet::NetworkManagerTest tc; QTEST_SET_MAIN_SOURCE_PATH return QTest::qExec(&tc, argc, argv); } void koutnet::NetworkManagerTest::sweepBackoffGrowsThenCaps() { // the /24 sweep cadence used to be untested timing logic. sweepTick() is the // pure decision it rides on, so we can check it without a socket or clock. // Jitter fixed at 1.0 for determinism; the math is interval-doubling, capped. constexpr double minMs = 2000.0; constexpr double maxMs = 120000.0; const double jitter = 1.0; // A known peer suppresses the sweep entirely and resets the gap. { double lastScan = 0.0; double interval = 8000.0; QVERIFY(!koutnet::discovery::sweepTick(5.0, lastScan, interval, /*peersEmpty=*/false, minMs, maxMs, jitter)); QCOMPARE(interval, minMs); QCOMPARE(lastScan, 5.0); } // Empty network: nothing is due until interval seconds elapse, then it doubles. { double lastScan = 0.0; double interval = minMs; // 2s -> due at t>2s QVERIFY(!koutnet::discovery::sweepTick(1.0, lastScan, interval, true, minMs, maxMs, jitter)); QCOMPARE(interval, minMs); // not yet due, unchanged QVERIFY(koutnet::discovery::sweepTick(2.5, lastScan, interval, true, minMs, maxMs, jitter)); QCOMPARE(interval, 4000.0); QCOMPARE(lastScan, 2.5); QVERIFY(!koutnet::discovery::sweepTick(4.0, lastScan, interval, true, minMs, maxMs, jitter)); // 4-2.5=1.5 < 4 QVERIFY(koutnet::discovery::sweepTick(7.0, lastScan, interval, true, minMs, maxMs, jitter)); // 7-2.5=4.5 > 4 QCOMPARE(interval, 8000.0); } // the gap keeps doubling but never exceeds the cap, and stays put there. { double lastScan = 0.0; double interval = minMs; double t = 0.0; for (int i = 0; i < 20; ++i) { t += (interval * jitter) / 1000.0 + 0.1; // advance past the due point QVERIFY(koutnet::discovery::sweepTick(t, lastScan, interval, true, minMs, maxMs, jitter)); } QCOMPARE(interval, maxMs); const double capped = interval; t += (interval * jitter) / 1000.0 + 0.1; QVERIFY(koutnet::discovery::sweepTick(t, lastScan, interval, true, minMs, maxMs, jitter)); QCOMPARE(interval, capped); // still the cap, never grows past it } } // The STUN codec is exercised offline with hand-built bytes, so the RFC 8489 // header, the XOR decoding and the refusal paths have a verdict without a // server anywhere near the test run. void koutnet::NetworkManagerTest::stunCodec() { const QByteArray txid = QByteArray::fromHex("0123456789abcdef01234567"); // a binding request: type 0x0001, an empty attribute block, the cookie // and the 12 transaction bytes. const QByteArray request = koutnet::encodeStunBindingRequest(txid); QCOMPARE(request.size(), 20); QCOMPARE(request.mid(0, 2), QByteArray::fromHex("0001")); QCOMPARE(request.mid(2, 2), QByteArray::fromHex("0000")); QCOMPARE(request.mid(4, 4), QByteArray::fromHex("2112a442")); QCOMPARE(request.mid(8, 12), txid); QVERIFY(koutnet::encodeStunBindingRequest(QByteArray(/*11 bytes*/ "12345678901")).isEmpty()); // A success response naming 198.51.100.1:5350 as XOR-MAPPED-ADDRESS. // X-Port keeps the network-order port xored against the top cookie half // (0x14E6 ^ 0x2112 -> 0x35F4); X-Address is the IPv4 xored with the cookie. QByteArray response = QByteArray::fromHex("010100082112a442"); response += txid; response += QByteArray::fromHex("00200008"); response += QByteArray::fromHex("000135f4e721c043"); QHostAddress address; quint16 port = 0; QVERIFY(koutnet::parseStunBindingResponse(response, txid, &address, &port)); QCOMPARE(address, QHostAddress(QStringLiteral("198.51.100.1"))); QCOMPARE(int(port), 5350); // a MAPPED-ADDRESS (non-XOR) answer survives too, for a server that never // learned the encrypted form. QByteArray classic = QByteArray::fromHex("010100082112a442") + txid + QByteArray::fromHex("00010008") + QByteArray::fromHex("000114e6c6336401"); QVERIFY(koutnet::parseStunBindingResponse(classic, txid, &address, &port)); QCOMPARE(address, QHostAddress(QStringLiteral("198.51.100.1"))); QCOMPARE(int(port), 5350); // refusals: a reply for a different transaction, an error type, a response // whose body is longer than what arrived, an empty attribute block and // bytes that are not a STUN message at all. QVERIFY(!koutnet::parseStunBindingResponse(response, QByteArray::fromHex("fedcba9876543210fedcba98"), &address, &port)); QByteArray errorReply = QByteArray::fromHex("011100082112a442") + txid; QVERIFY(!koutnet::parseStunBindingResponse(errorReply, txid, &address, &port)); QByteArray truncated = QByteArray::fromHex("010100102112a442") + txid + QByteArray::fromHex("0020"); QVERIFY(!koutnet::parseStunBindingResponse(truncated, txid, &address, &port)); QByteArray noAddress = QByteArray::fromHex("010100002112a442") + txid; QVERIFY(!koutnet::parseStunBindingResponse(noAddress, txid, &address, &port)); QVERIFY(!koutnet::parseStunBindingResponse(QByteArrayLiteral("definitely not stun"), txid, &address, &port)); } #include "NetworkManagerTest.moc"