// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // The presence half of discovery without sockets or a TLS channel: the beacon // (payload, multicast targets, nonce counter), the guards (per-address rate // cap, counter-based replay gate) and the observed peer table are driven // through the station, sink and dial seams. The one thing that writes real // files is the nonce park, and main() puts QStandardPaths in test mode so a // run here never touches a user's app data. #include #include #include #include #include #include #include #include #include "../network/PresenceService.h" #include "../network/Protocol.h" namespace koutnet { namespace { // TEST-NET-2 addresses, so a "peer" can never collide with a local one. const QString kPeerIp = QStringLiteral("198.51.100.7"); const QString kPeerAltIp = QStringLiteral("198.51.100.8"); const QString kOtherIp = QStringLiteral("198.51.100.20"); double nowEpoch() { return QDateTime::currentMSecsSinceEpoch() / 1000.0; } QJsonObject presenceFrom(const QString &ip, quint64 nonce, const QString &identity, quint16 tlsPort = 0) { QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgPresence; payload[QStringLiteral("ip")] = ip; payload[QStringLiteral("nonce")] = QString::number(nonce, 16); if (!identity.isEmpty()) payload[QStringLiteral("from_id")] = identity; if (tlsPort != 0) payload[QStringLiteral("tls_port")] = tlsPort; return payload; } // The service owns no sockets, so a harness stands in for the NetworkManager // it is extracted from: a station it can read back, a sink that records every // beacon datagram, a pin table that answers trusted-identity questions, and a // dial seam that dedupes by address exactly the way the owner's pin table does. struct Harness { PresenceService service; QString primary = QStringLiteral("10.0.0.5"); QSet localIps{QStringLiteral("10.0.0.5"), QStringLiteral("10.0.0.6")}; quint16 tlsPort = 0; QString identityId; quint16 udpPort = protocol::kUdpPortDefault; QHash pins; // address -> pinned identity QSet dialedAddresses; int dialCount = 0; QString lastDialedId; QString lastDialedAddress; quint16 lastDialedPort = 0; QVector> sinkDatagrams; // destination, payload Harness() { service.setStation([this] { PresenceService::StationInfo station; station.primaryAddress = primary; station.localAddresses = localIps; station.tlsPort = tlsPort; station.identityId = identityId; return station; }); service.setDatagramSink([this](const QByteArray &data, const QHostAddress &to, quint16) { sinkDatagrams.append({to.toString(), data}); }); service.setLocalPort([this] { return udpPort; }); service.setTrustedIdentity([this](const QString &address) { return pins.value(address); }); service.setAdvertisedTlsDial([this](const QString &peerId, const QString &address, quint16 port) { if (dialedAddresses.contains(address)) return; dialedAddresses.insert(address); ++dialCount; lastDialedId = peerId; lastDialedAddress = address; lastDialedPort = port; }); } }; QJsonObject decodeBeacon(const QByteArray &frame) { QString type; QJsonObject msg; const bool good = protocol::decodeFrame(frame, type, msg); return good ? msg : QJsonObject(); } } // namespace class PresenceServiceTest : public QObject { Q_OBJECT private Q_SLOTS: void counterAdvancesAndSurvivesARestart(); void ownAddressesAreNeverFiled(); void badHostsAreNowhereToFile(); void rateLimitDropsTheFlood(); void replayedNonceIsIgnored(); void firstPresenceAnnouncesThenRefreshes(); void identityIsFiledUnderItsFirstAddress(); void trustedPinIdentityWinsOverAnnounced(); void advertisedTlsPortIsDialedOnce(); void e2eVouchFeedsTheFieldOnlyWhenPinned(); void beaconCarriesTheStationFields(); void beaconRidesTheMulticastGroups(); void avatarSourceLandsInThePeerTable(); void theCapEvictsTheOldestPeer(); void stalePeersLeave(); void authenticatedSeatReassignsThePinHolder(); }; // 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 PresenceServiceTest::counterAdvancesAndSurvivesARestart() { Harness h; QFile::remove(h.service.nonceCounterPath()); h.service.reloadCounter(); const quint64 firstNonce = h.service.takeNonce(); const quint64 secondNonce = h.service.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 PresenceService restarted; restarted.reloadCounter(); QCOMPARE(restarted.takeNonce(), secondNonce + 1); } // Presence packets are broadcast, so they come back at us across mirrors, // VPN adapters and the router; nothing about ourselves may be filed. void PresenceServiceTest::ownAddressesAreNeverFiled() { Harness h; QSignalSpy online(&h.service, &PresenceService::userOnline); h.service.acceptPresence(QStringLiteral("10.0.0.5"), presenceFrom(kPeerIp, 1, QStringLiteral("id"))); h.service.acceptPresence(kPeerIp, presenceFrom(QStringLiteral("10.0.0.6"), 2, QStringLiteral("id"))); h.service.acceptPresence(QStringLiteral("10.0.0.6"), presenceFrom(kPeerIp, 3, QStringLiteral("id"))); QCOMPARE(h.service.peers().size(), 0); QCOMPARE(online.count(), 0); } void PresenceServiceTest::badHostsAreNowhereToFile() { Harness h; h.service.acceptPresence(QString(), presenceFrom(kPeerIp, 1, QStringLiteral("id"))); h.service.acceptPresence(QStringLiteral("0.0.0.0"), presenceFrom(kPeerIp, 2, QStringLiteral("id"))); h.service.acceptPresence(QStringLiteral("::"), presenceFrom(kPeerIp, 3, QStringLiteral("id"))); QCOMPARE(h.service.peers().size(), 0); } // Presence is the cheapest packet to forge, so a flood from one address must // not grow the table nor drown the arrival signals. Cap is 5/s per address. void PresenceServiceTest::rateLimitDropsTheFlood() { Harness h; QSignalSpy online(&h.service, &PresenceService::userOnline); QSignalSpy refreshed(&h.service, &PresenceService::peerRefreshed); for (int i = 0; i < 50; ++i) h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, quint64(i + 1), QStringLiteral("id"))); 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.service.peers().size(), 1); } void PresenceServiceTest::replayedNonceIsIgnored() { Harness h; QSignalSpy refreshed(&h.service, &PresenceService::peerRefreshed); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 5, QStringLiteral("id"))); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 5, QStringLiteral("id"))); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 4, QStringLiteral("id"))); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 6, QStringLiteral("id"))); QCOMPARE(refreshed.count(), 1); // only the strictly-larger 6 passed QCOMPARE(h.service.peers().size(), 1); } void PresenceServiceTest::firstPresenceAnnouncesThenRefreshes() { Harness h; QSignalSpy online(&h.service, &PresenceService::userOnline); QSignalSpy refreshed(&h.service, &PresenceService::peerRefreshed); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("id"))); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 2, QStringLiteral("id"))); QCOMPARE(online.count(), 1); QCOMPARE(refreshed.count(), 1); QCOMPARE(refreshed.takeFirst().at(0).toString(), kPeerIp); } void PresenceServiceTest::identityIsFiledUnderItsFirstAddress() { Harness h; h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("id"))); h.service.acceptPresence(kPeerAltIp, presenceFrom(kPeerAltIp, 1, QStringLiteral("id"))); QCOMPARE(h.service.peers().size(), 1); QVERIFY(h.service.peers().contains(kPeerIp)); QCOMPARE(h.service.keyForIdentity(QStringLiteral("id")), kPeerIp); } void PresenceServiceTest::trustedPinIdentityWinsOverAnnounced() { Harness h; h.pins[kPeerIp] = QStringLiteral("real"); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("ghost"))); QCOMPARE(h.service.peers().value(kPeerIp).value(QStringLiteral("from_id")).toString(), QStringLiteral("real")); QCOMPARE(h.service.keyForIdentity(QStringLiteral("real")), kPeerIp); } void PresenceServiceTest::advertisedTlsPortIsDialedOnce() { Harness h; h.pins[kPeerIp] = QStringLiteral("real"); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("ghost"), 4222)); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 2, QStringLiteral("ghost"), 4222)); QCOMPARE(h.dialCount, 1); QCOMPARE(h.lastDialedId, QStringLiteral("real")); QCOMPARE(h.lastDialedPort, quint16(4222)); // a peer heard on one address but advertising another gets the dial at the // advertised one - what it asked to be called, not where it was overheard h.service.acceptPresence(kOtherIp, presenceFrom(kPeerAltIp, 1, QStringLiteral("id"), 4333)); QCOMPARE(h.dialCount, 2); QCOMPARE(h.lastDialedAddress, kPeerAltIp); } void PresenceServiceTest::e2eVouchFeedsTheFieldOnlyWhenPinned() { Harness h; h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("id"))); QVERIFY(!h.service.peers().value(kPeerIp).contains(QStringLiteral("e2e"))); h.service.setE2eVouch([](const QString &) { return false; }); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 2, QStringLiteral("id"))); QCOMPARE(h.service.peers().value(kPeerIp).value(QStringLiteral("e2e")).toBool(), false); h.service.setE2eVouch([](const QString &) { return true; }); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 3, QStringLiteral("id"))); QCOMPARE(h.service.peers().value(kPeerIp).value(QStringLiteral("e2e")).toBool(), true); } void PresenceServiceTest::beaconCarriesTheStationFields() { Harness h; h.primary = QStringLiteral("192.168.4.5"); h.localIps = {QStringLiteral("192.168.4.5"), QStringLiteral("192.168.4.6")}; h.tlsPort = 9090; h.identityId = QStringLiteral("station-id"); h.service.setProfile(QStringLiteral("alfred"), QStringLiteral("Alfred"), QStringLiteral("keeping the house"), QStringLiteral("rev-3")); h.service.setStatus(2, QStringLiteral(":)")); h.udpPort = 42011; // non-default: the payload must not depend on the bind port const QJsonObject beacon = decodeBeacon(h.service.beaconFrame()); QVERIFY(!beacon.isEmpty()); QCOMPARE(beacon.value(QStringLiteral("type")).toString(), protocol::kMsgPresence); QCOMPARE(beacon.value(QStringLiteral("ip")).toString(), QStringLiteral("192.168.4.5")); QCOMPARE(beacon.value(QStringLiteral("tls_port")).toInt(), 9090); QCOMPARE(beacon.value(QStringLiteral("from_id")).toString(), QStringLiteral("station-id")); QCOMPARE(beacon.value(QStringLiteral("username")).toString(), QStringLiteral("alfred")); QCOMPARE(beacon.value(QStringLiteral("display_name")).toString(), QStringLiteral("Alfred")); QCOMPARE(beacon.value(QStringLiteral("bio")).toString(), QStringLiteral("keeping the house")); QCOMPARE(beacon.value(QStringLiteral("profile_rev")).toString(), QStringLiteral("rev-3")); QCOMPARE(beacon.value(QStringLiteral("presence")).toInt(), 2); QCOMPARE(beacon.value(QStringLiteral("status_emoji")).toString(), QStringLiteral(":)")); QCOMPARE(beacon.value(QStringLiteral("protocol_version")).toInt(), protocol::kProtocolVersion); QVERIFY(!beacon.value(QStringLiteral("nonce")).toString().isEmpty()); // The beacon is unencrypted and goes to the whole segment, so it carries only // what a peer needs to place a call. The interface list and the OS name used // to ride along on every beacon. QVERIFY(!beacon.contains(QStringLiteral("all_ips"))); QVERIFY(!beacon.contains(QStringLiteral("os"))); // every beacon is paid in a strictly increasing nonce const quint64 firstNonce = beacon.value(QStringLiteral("nonce")).toString().toULongLong(nullptr, 16); const QJsonObject second = decodeBeacon(h.service.beaconFrame()); const quint64 secondNonce = second.value(QStringLiteral("nonce")).toString().toULongLong(nullptr, 16); QVERIFY(secondNonce > firstNonce); } // start() fires the first beacon immediately and rides the sink's multicast // groups first; the rest goes out per interface, so only the first two // datagrams are guaranteed on every machine. void PresenceServiceTest::beaconRidesTheMulticastGroups() { Harness h; h.service.start(); QVERIFY(h.service.isRunning()); h.service.stop(); QVERIFY(!h.service.isRunning()); QVERIFY2(h.sinkDatagrams.size() >= 2, "start() must beacon immediately"); QCOMPARE(h.sinkDatagrams.at(0).first, QStringLiteral("224.0.0.251")); QCOMPARE(h.sinkDatagrams.at(1).first, QStringLiteral("ff02::fb")); const QJsonObject beacon = decodeBeacon(h.sinkDatagrams.at(0).second); QVERIFY(!beacon.isEmpty()); QCOMPARE(beacon.value(QStringLiteral("type")).toString(), protocol::kMsgPresence); } void PresenceServiceTest::avatarSourceLandsInThePeerTable() { Harness h; h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("id"))); h.service.setAvatarSource(kPeerIp, QStringLiteral("file:///tmp/me.png")); QCOMPARE(h.service.peers().value(kPeerIp).value(QStringLiteral("avatar")).toString(), QStringLiteral("file:///tmp/me.png")); h.service.setAvatarSource(kPeerIp, QString()); QVERIFY(!h.service.peers().value(kPeerIp).contains(QStringLiteral("avatar"))); } void PresenceServiceTest::theCapEvictsTheOldestPeer() { Harness h; h.service.acceptPresence(QStringLiteral("198.51.100.1"), presenceFrom(QStringLiteral("198.51.100.1"), 1, QStringLiteral("id-1"))); QTest::qWait(2); // age the first peer so "oldest" is unambiguous for (int i = 2; i <= PresenceService::kMaxPeers; ++i) { const QString ip = QStringLiteral("198.51.100.%1").arg(i); h.service.acceptPresence(ip, presenceFrom(ip, quint64(i), QStringLiteral("id-%1").arg(i))); } QCOMPARE(h.service.peers().size(), PresenceService::kMaxPeers); h.service.acceptPresence(QStringLiteral("198.51.100.513"), presenceFrom(QStringLiteral("198.51.100.513"), 513, QStringLiteral("id-513"))); QCOMPARE(h.service.peers().size(), PresenceService::kMaxPeers); QVERIFY(!h.service.peers().contains(QStringLiteral("198.51.100.1"))); QVERIFY(h.service.peers().contains(QStringLiteral("198.51.100.513"))); QVERIFY(h.service.keyForIdentity(QStringLiteral("id-1")).isEmpty()); } void PresenceServiceTest::stalePeersLeave() { Harness h; QSignalSpy offline(&h.service, &PresenceService::userOffline); h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("gone"))); h.service.pruneStalePeers(nowEpoch() + 30); // age the peer into staleness QCOMPARE(h.service.peers().size(), 0); QCOMPARE(offline.count(), 1); QCOMPARE(offline.takeFirst().at(0).toString(), kPeerIp); QVERIFY(h.service.keyForIdentity(QStringLiteral("gone")).isEmpty()); } void PresenceServiceTest::authenticatedSeatReassignsThePinHolder() { Harness h; // the spoofed presence parks "ghost" at 7; the real identity is overheard // at 8. When the certificate for identity "real" authenticates from 7 - // an address presence filed under a stranger's id - the seat moves to the // holder of the real certificate. h.service.acceptPresence(kPeerIp, presenceFrom(kPeerIp, 1, QStringLiteral("ghost"))); h.service.acceptPresence(kPeerAltIp, presenceFrom(kPeerAltIp, 1, QStringLiteral("real"))); QCOMPARE(h.service.keyForIdentity(QStringLiteral("real")), kPeerAltIp); h.service.authenticatedSeat(QStringLiteral("real"), kPeerIp); QCOMPARE(h.service.keyForIdentity(QStringLiteral("real")), kPeerIp); // ...but not when the seat the identity already holds is the authenticated // one; two identities do not tussle over a seat a certificate has claimed. h.service.acceptPresence(kOtherIp, presenceFrom(kOtherIp, 1, QStringLiteral("real"))); h.pins[kOtherIp] = QStringLiteral("champion"); h.service.authenticatedSeat(QStringLiteral("real"), kOtherIp); QCOMPARE(h.service.keyForIdentity(QStringLiteral("real")), kPeerIp); } } // namespace koutnet int main(int argc, char *argv[]) { // The nonce park file goes under AppDataLocation; test mode keeps a run here // from touching a real user's app data. QStandardPaths::setTestModeEnabled(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("presence-service")); koutnet::PresenceServiceTest tc; QTEST_SET_MAIN_SOURCE_PATH return QTest::qExec(&tc, argc, argv); } #include "PresenceServiceTest.moc"