// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include #include #include #include #include #include "../core/security/CryptoManager.h" #include "../core/security/SecretStore.h" using koutnet::CryptoManager; namespace { const QString kPass = QStringLiteral("correct horse battery staple"); const QString kPeer = QStringLiteral("192.0.2.10"); } class CryptoManagerTest : public QObject { Q_OBJECT private Q_SLOTS: // first, because everything under it makes keys and this is the promise that // none of them reach the user's keyring. These suites used to fill the real // the store with identity_priv_b64_peer-a and its friends, and the unscoped // cases wrote over the developer's own entries with test keys. void secretsStayOutOfTheRealStore() { QVERIFY2(koutnet::SecretStore::isInMemoryOnly(), "SecretStore is talking to the real store; this run would write test keys " "into the session store and leave them there"); QVERIFY(koutnet::SecretStore::isAvailable()); const QString key = QStringLiteral("store_isolation_probe"); QVERIFY(koutnet::SecretStore::write(key, QStringLiteral("value"))); QString readBack; QVERIFY(koutnet::SecretStore::read(key, &readBack)); QCOMPARE(readBack, QStringLiteral("value")); QVERIFY(koutnet::SecretStore::remove(key)); QVERIFY2(!koutnet::SecretStore::read(key, &readBack), "a removed secret was still readable"); } void keysLoad() { CryptoManager crypto; QVERIFY2(crypto.isValid(), "no keypair, every other test would pass " "trivially because the code falls through " "to plaintext"); QVERIFY(!crypto.fingerprint().isEmpty()); } // Guards a real bug: the migration filled the store and called remove() on // the config file, and nobody checked the removal reached the disk. The keys // are seeded in the pre-store form (@ByteArray(...)) the deletion must cope // with. void plaintextKeysLeaveTheConfigFile() { const QStringList keys = {QStringLiteral("security/identity_priv_b64"), QStringLiteral("security/dh_priv_b64")}; QString path; { QSettings settings; path = settings.fileName(); settings.setValue(keys.at(0), QByteArrayLiteral("aWRlbnRpdHk=")); settings.setValue(keys.at(1), QByteArrayLiteral("ZGlmZmllaGVsbG1hbg==")); settings.setValue(QStringLiteral("app/username"), QStringLiteral("tester")); settings.sync(); } QString detail; QVERIFY2(koutnet::SecretStore::purgePlaintextConfigKeys(keys, &detail), qUtf8Printable(detail)); QSettings cleanedSettings; cleanedSettings.sync(); for (const QString &key : keys) QVERIFY(!cleanedSettings.contains(key)); QCOMPARE(cleanedSettings.value(QStringLiteral("app/username")).toString(), QStringLiteral("tester")); #ifndef Q_OS_WIN // Native QSettings uses a file on Unix and the registry on Windows. QFile file(path); QVERIFY(file.open(QIODevice::ReadOnly)); const QByteArray contents = file.readAll(); QVERIFY2(!contents.contains(QByteArrayLiteral("identity_priv_b64")), contents.constData()); QVERIFY2(!contents.contains(QByteArrayLiteral("dh_priv_b64")), contents.constData()); QVERIFY2(contents.contains(QByteArrayLiteral("tester")), contents.constData()); #endif // Runs on every start, so an already clean file has to count as success. QVERIFY(koutnet::SecretStore::purgePlaintextConfigKeys(keys, &detail)); } // The identity id and seed the TLS layer derives its certificate from must // be stable within a process, and two scopes must not collide - if they did, // every two-peer test below would be proving one peer talking to itself. void identityIdAndSeedAreStable() { CryptoManager a(QStringLiteral("id-a")); CryptoManager b(QStringLiteral("id-b")); QVERIFY(a.isValid()); QVERIFY(b.isValid()); QVERIFY(!a.ownIdentityId().isEmpty()); QCOMPARE(a.ownIdentityId(), a.ownIdentityId()); QCOMPARE(a.identitySeed().size(), CryptoManager::kKeyLen); QVERIFY2(a.ownIdentityId() != b.ownIdentityId(), "both managers came up as the same identity, so no test below " "is actually exercising two peers"); QVERIFY2(a.fingerprint() != b.fingerprint(), "two scopes shared an identity key"); } void roundTrip_data() { QTest::addColumn("plain"); QTest::newRow("ascii") << QStringLiteral("hello"); QTest::newRow("empty") << QString(); QTest::newRow("cyrillic") << QStringLiteral("привет, как дела"); QTest::newRow("emoji") << QStringLiteral("ok \xF0\x9F\x91\x8D"); QTest::newRow("long") << QString(200000, QLatin1Char('x')); } void roundTrip() { QFETCH(QString, plain); CryptoManager crypto; const QString sealed = crypto.encrypt(plain, kPass); QCOMPARE(crypto.decrypt(sealed, kPass), plain); } void cipherTextIsNotThePlainText() { CryptoManager crypto; const QString plain = QStringLiteral("meet me at seven"); QVERIFY(!crypto.encrypt(plain, kPass).contains(plain)); } // No passphrase is not a failure: the caller is relying on the TLS channel, // and the body rides it verbatim. This is the whole point of the TLS-first // transport - there is no session key to invent. void cleartextPassesThroughWithoutAPassphrase() { CryptoManager crypto; const QString plain = QStringLiteral("plain over the tls channel"); QCOMPARE(crypto.encrypt(plain, QString()), plain); QCOMPARE(crypto.decrypt(plain, QString()), plain); } // The flip side: once a passphrase is held, a body that arrived without the // marker is a stripped packet, not a message to render. void cleartextIsRefusedWhenAPassphraseIsExpected() { CryptoManager crypto; const QString got = crypto.decrypt(QStringLiteral("bare text"), kPass); QVERIFY2(got != QStringLiteral("bare text"), "a stripped packet downgraded a keyed channel to cleartext"); QVERIFY(got.contains(QStringLiteral("cleartext"))); } void wrongPassphraseFails() { CryptoManager crypto; const QString plain = QStringLiteral("meet me at seven"); const QString sealed = crypto.encrypt(plain, kPass); QVERIFY(crypto.decrypt(sealed, QStringLiteral("wrong")) != plain); } // the point of authenticated encryption: a flipped bit has to be refused rather than // decrypted into something that merely looks wrong. The flip goes into the // decoded bytes, not the base64 text, whose spare bits can absorb an edit. void tamperedCipherTextFails() { CryptoManager crypto; const QString plain = QStringLiteral("balance: 100"); const QString sealed = crypto.encrypt(plain, kPass); const QString marker = QStringLiteral("KNC2:"); QVERIFY(sealed.startsWith(marker)); const QByteArray body = QByteArray::fromBase64(sealed.mid(marker.length()).toLatin1()); QVERIFY(body.size() > 64); for (qsizetype at : {qsizetype(2), body.size() / 2, body.size() - 2}) { QByteArray broken = body; broken[at] = char(broken.at(at) ^ 0x01); QCOMPARE(broken.size(), body.size()); QVERIFY(broken != body); const QString rebuilt = marker + QString::fromLatin1(broken.toBase64()); QVERIFY2(crypto.decrypt(rebuilt, kPass) != plain, qPrintable(QStringLiteral("a flipped bit at byte %1 was accepted").arg(at))); } } void garbageDoesNotCrash_data() { QTest::addColumn("junk"); QTest::newRow("empty") << QString(); QTest::newRow("plain word") << QStringLiteral("nonsense"); QTest::newRow("bad base64") << QStringLiteral("!!!!not base64!!!!"); QTest::newRow("short base64") << QStringLiteral("AAAA"); QTest::newRow("nul bytes") << QStringLiteral("AA\0AA"); } void garbageDoesNotCrash() { QFETCH(QString, junk); CryptoManager crypto; crypto.decrypt(junk, kPass); crypto.decrypt(junk, QString()); } void rateLimitTrips() { CryptoManager crypto; int accepted = 0; for (int i = 0; i < 50; ++i) { if (crypto.checkRate(kPeer, 10)) ++accepted; } QVERIFY2(accepted <= 12, "the rate limit let a flood through"); QVERIFY2(accepted >= 10, "the rate limit refused traffic under the cap"); } // two managers in one process would otherwise load the same keypair from the // store - or the same plaintext leftovers - and end up as the same peer, a // test that passes proving nothing. The storage scope separates their // entries. void twoManagersHaveSeparateIdentities() { CryptoManager a(QStringLiteral("peer-a")); CryptoManager b(QStringLiteral("peer-b")); QVERIFY(a.isValid()); QVERIFY(b.isValid()); QVERIFY2(a.fingerprint() != b.fingerprint(), "both managers came up as the same identity, so no test below " "is actually exercising two peers"); } // The async receive path must agree with the synchronous one, byte for byte. void asyncDecryptRoundTripsAPassphraseMessage() { CryptoManager crypto; const QString plain = QStringLiteral("meet me at seven"); const QString sealed = crypto.encrypt(plain, kPass); QString got; bool delivered = false; crypto.decryptAsync(sealed, kPass, [&](const QString &text, bool ok) { got = text; delivered = ok; }); QTRY_VERIFY_WITH_TIMEOUT(delivered, 30000); QCOMPARE(got, plain); } void asyncDecryptWithTheWrongPassphraseFails() { CryptoManager crypto; const QString plain = QStringLiteral("meet me at seven"); const QString sealed = crypto.encrypt(plain, kPass); QString got; bool delivered = false; crypto.decryptAsync(sealed, QStringLiteral("wrong"), [&](const QString &text, bool ok) { got = text; delivered = ok; }); QTRY_VERIFY_WITH_TIMEOUT(delivered, 30000); QVERIFY(got != plain); QVERIFY(got.contains(QStringLiteral("invalid key"))); } // A cleartext body on a keyless channel resolves immediately, but must not // overtake a passphrase message already waiting on its derivation - the // window would otherwise show the answer before the question. void asyncDecryptKeepsQueueOrder() { CryptoManager crypto; const QString slowPass = QStringLiteral("a passphrase the cache has never seen"); const QString slowPlain = QStringLiteral("first, slow"); const QString slowSealed = crypto.encrypt(slowPlain, slowPass); QStringList order; QString slowResult; crypto.decryptAsync(slowSealed, slowPass, [&](const QString &text, bool) { slowResult = text; order << QStringLiteral("slow"); }); QString fastResult; crypto.decryptAsync(QStringLiteral("cleartext on a keyless channel"), QString(), [&](const QString &text, bool) { fastResult = text; order << QStringLiteral("fast"); }); QTRY_VERIFY_WITH_TIMEOUT(order.size() == 2, 30000); QCOMPARE(slowResult, slowPlain); QCOMPARE(fastResult, QStringLiteral("cleartext on a keyless channel")); QCOMPARE(order, QStringList({QStringLiteral("slow"), QStringLiteral("fast")})); } // A cleartext body on a keyed channel is refused the same way async as sync. void asyncDecryptRefusesCleartextOnAKeyedChannel() { CryptoManager crypto; QString got; bool delivered = false; crypto.decryptAsync(QStringLiteral("bare text"), kPass, [&](const QString &text, bool ok) { got = text; delivered = ok; }); QVERIFY(delivered); QVERIFY(got.contains(QStringLiteral("cleartext"))); } void atRestSealRoundTrips() { const QByteArray key = CryptoManager::generateAtRestKey(); QCOMPARE(key.size(), CryptoManager::kKeyLen); const QByteArray payload = QByteArrayLiteral("the whole chat log, in one blob"); const QByteArray sealed = CryptoManager::sealAtRest(key, payload); QVERIFY(sealed.size() >= CryptoManager::kNonceLen + payload.size() + CryptoManager::kTagLen); QVERIFY2(!sealed.contains(payload), "the sealed log still contains its own plaintext"); QByteArray opened; QVERIFY(CryptoManager::openAtRest(key, sealed, &opened)); QCOMPARE(opened, payload); } void atRestSealIsTiedToItsKey() { const QByteArray key = CryptoManager::generateAtRestKey(); const QByteArray otherKey = CryptoManager::generateAtRestKey(); QVERIFY2(key != otherKey, "two fresh at-rest keys must not collide"); const QByteArray sealed = CryptoManager::sealAtRest(key, QByteArrayLiteral("log")); QByteArray opened; QVERIFY2(!CryptoManager::openAtRest(otherKey, sealed, &opened), "a log opened under the wrong key would be a tampered log"); } void atRestSealDetectsTampering() { const QByteArray key = CryptoManager::generateAtRestKey(); const QByteArray sealed = CryptoManager::sealAtRest(key, QByteArrayLiteral("the chat log")); QByteArray damaged = sealed; damaged[sealed.size() - 1] = char(uchar(damaged[sealed.size() - 1]) ^ 0x01); QByteArray opened; QVERIFY(!CryptoManager::openAtRest(key, damaged, &opened)); } void atRestSealRefusesWrongSizeKey() { QByteArray opened; QVERIFY(!CryptoManager::openAtRest(QByteArray(15, '\0'), QByteArray(CryptoManager::kNonceLen + CryptoManager::kTagLen, '\0'), &opened)); QVERIFY(CryptoManager::sealAtRest(QByteArray(15, '\0'), QByteArrayLiteral("data")).isEmpty()); } }; // QTEST_MAIN would run against the real user configuration, where CryptoManager // keeps its keypair; test mode moves QSettings into a scratch directory. int main(int argc, char *argv[]) { QStandardPaths::setTestModeEnabled(true); // Keep test keys out of the persistent secret store. 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("crypto-manager")); CryptoManagerTest tc; QTEST_SET_MAIN_SOURCE_PATH return QTest::qExec(&tc, argc, argv); } #include "CryptoManagerTest.moc"