Files
keepassxc/tests/TestBrowser.cpp
T
2026-11-13 14:53:01 +01:00

1381 lines
64 KiB
C++

/*
* Copyright (C) 2026 KeePassXC Team <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 or (at your option)
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TestBrowser.h"
#include "browser/BrowserHost.h"
#include "browser/BrowserMessageBuilder.h"
#include "browser/BrowserSettings.h"
#include "core/Group.h"
#include "core/Tools.h"
#include "crypto/Crypto.h"
#include "gui/UrlTools.h"
#include <QJsonObject>
#include <QTest>
#include <botan/sodium.h>
using namespace Botan::Sodium;
QTEST_GUILESS_MAIN(TestBrowser)
const QString PUBLICKEY = "UIIPObeoya1G8g1M5omgyoPR/j1mR1HlYHu0wHCgMhA=";
const QString SECRETKEY = "B8ei4ZjQJkWzZU2SK/tBsrYRwp+6ztEMf5GFQV+i0yI=";
const QString SERVERPUBLICKEY = "lKnbLhrVCOqzEjuNoUz1xj9EZlz8xeO4miZBvLrUPVQ=";
const QString SERVERSECRETKEY = "tbPQcghxfOgbmsnEqG2qMIj1W2+nh+lOJcNsHncaz1Q=";
const QString NONCE = "zBKdvTjL5bgWaKMCTut/8soM/uoMrFoZ";
const QString INCREMENTEDNONCE = "zRKdvTjL5bgWaKMCTut/8soM/uoMrFoZ";
const QString CLIENTID = "testClient";
void TestBrowser::initTestCase()
{
QVERIFY(Crypto::init());
m_browserService = browserService();
browserSettings()->setBestMatchOnly(false);
QLocale::setDefault(QLocale::c());
}
void TestBrowser::init()
{
m_browserAction.reset(new BrowserAction());
}
/**
* Tests for BrowserAction
*/
void TestBrowser::testChangePublicKeys()
{
QJsonObject json;
json["action"] = "change-public-keys";
json["publicKey"] = PUBLICKEY;
json["nonce"] = NONCE;
auto response = m_browserAction->processClientMessage(nullptr, json);
QCOMPARE(response["action"].toString(), QString("change-public-keys"));
QCOMPARE(response["publicKey"].toString() == PUBLICKEY, false);
QCOMPARE(response["success"].toString(), TRUE_STR);
}
void TestBrowser::testEncryptMessage()
{
QJsonObject message;
message["action"] = "test-action";
const int messageSize = 32;
QString invalidKey = "dGVzdHN0cmluZw==";
m_browserAction->m_publicKey = SERVERPUBLICKEY;
m_browserAction->m_secretKey = SERVERSECRETKEY;
m_browserAction->m_clientPublicKey = PUBLICKEY;
// Public key length is not valid
auto encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, invalidKey, SERVERSECRETKEY);
QVERIFY(encrypted.isEmpty());
// Secret key length is not valid
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, invalidKey);
QVERIFY(encrypted.isEmpty());
// Nonce length is not valid
encrypted = browserMessageBuilder()->encryptMessage(message, invalidKey, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(encrypted.isEmpty());
// Max message length is exceeded (set to 20)
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, 20);
QVERIFY(encrypted.isEmpty());
// Empty message
encrypted = browserMessageBuilder()->encryptMessage(QJsonObject(), NONCE, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(encrypted.isEmpty());
// Successful encryption, the message itself is 32 bytes
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP"));
// Test boundaries (-1, exact length, +1)
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize - 1);
QVERIFY(encrypted.isEmpty()); // Exceeds
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP"));
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize + 1);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP"));
// Test the same boundaries with MACBYTES-1
encrypted = browserMessageBuilder()->encryptMessage(
message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize - 1, MacBytes - 1);
QVERIFY(encrypted.isEmpty()); // Exceeds
encrypted =
browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize, MacBytes - 1);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/o="));
encrypted = browserMessageBuilder()->encryptMessage(
message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize + 1, MacBytes - 1);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/o="));
// Test the same boundaries with MACBYTES+1
encrypted = browserMessageBuilder()->encryptMessage(
message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize - 1, MacBytes + 1);
QVERIFY(encrypted.isEmpty()); // Exceeds
encrypted =
browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize, MacBytes + 1);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rPAA=="));
encrypted = browserMessageBuilder()->encryptMessage(
message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize + 1, MacBytes + 1);
QCOMPARE(encrypted, QString("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rPAA=="));
// Encrypt JSON with NULL character. Result will be {"action": "test"}.
message["action"] = "test\u0000-action";
encrypted = browserMessageBuilder()->encryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY);
QCOMPARE(encrypted, QString("MRqyE6YAJQcytKFDkFWIF5/swvgeupk4lNgHEm2OO3ujNr0OMzH1XK8="));
}
void TestBrowser::testDecryptMessage()
{
QString message = "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP";
const int messageSize = 32;
QString invalidKey = "dGVzdHN0cmluZw==";
m_browserAction->m_publicKey = SERVERPUBLICKEY;
m_browserAction->m_secretKey = SERVERSECRETKEY;
m_browserAction->m_clientPublicKey = PUBLICKEY;
// Public key length is not valid
auto decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, invalidKey, SERVERSECRETKEY);
QVERIFY(decrypted.isEmpty());
// Secret key length is not valid
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, invalidKey);
QVERIFY(decrypted.isEmpty());
// Nonce length is not valid
decrypted = browserMessageBuilder()->decryptMessage(message, invalidKey, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(decrypted.isEmpty());
// Max message length is exceeded (set to 20)
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, 20);
QVERIFY(decrypted.isEmpty());
// Empty message
decrypted = browserMessageBuilder()->decryptMessage(QString(), NONCE, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(decrypted.isEmpty());
// Successful decryption
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY);
QCOMPARE(decrypted["action"].toString(), QString("test-action"));
// Test boundaries (-1, exact length, +1)
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize - 1);
QVERIFY(decrypted.isEmpty()); // Exceeds
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize);
QCOMPARE(decrypted["action"].toString(), QString("test-action"));
decrypted = browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, messageSize + 1);
QCOMPARE(decrypted["action"].toString(), QString("test-action"));
// Test the same boundaries with MACBYTES-1
for (int i = messageSize - 1; i <= messageSize + 1; ++i) {
decrypted =
browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, i, MacBytes - 1);
QVERIFY(decrypted.isEmpty());
}
// Test the same boundaries with MACBYTES+1
for (int i = messageSize - 1; i <= messageSize + 1; ++i) {
decrypted =
browserMessageBuilder()->decryptMessage(message, NONCE, PUBLICKEY, SERVERSECRETKEY, i, MacBytes + 1);
QCOMPARE(decrypted["action"].toString(), QString("test-action"));
}
// Malformed base64
decrypted = browserMessageBuilder()->decryptMessage(
QString("+zjtntnk4r3GWSl/Ph7Vqip/swvgeupk4lNgHEmA3B4ujNr0OMz6eQtGwjtsj+/rP"),
NONCE,
PUBLICKEY,
SERVERSECRETKEY);
QVERIFY(decrypted.isEmpty());
// Malformed data (not base64 encoded)
const auto malformed = QString("asdadfsar346fw3242ed<fs=");
decrypted = browserMessageBuilder()->decryptMessage(malformed, NONCE, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(decrypted.isEmpty());
// Data had originally a value with NULL char. Encrypted value from testEncryptMessage().
const auto jsonWithNull = QString("MRqyE6YAJQcytKFDkFWIF5/swvgeupk4lNgHEm2OO3ujNr0OMzH1XK8=");
decrypted = browserMessageBuilder()->decryptMessage(jsonWithNull, NONCE, PUBLICKEY, SERVERSECRETKEY);
QCOMPARE(decrypted["action"].toString(), QString("test"));
}
void TestBrowser::testGetBase64FromKey()
{
unsigned char pk[crypto_box_PUBLICKEYBYTES];
for (unsigned int i = 0; i < crypto_box_PUBLICKEYBYTES; ++i) {
pk[i] = i;
}
auto response = browserMessageBuilder()->getBase64FromKey(pk, crypto_box_PUBLICKEYBYTES);
QCOMPARE(response, QString("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="));
}
void TestBrowser::testIncrementNonce()
{
auto result = browserMessageBuilder()->incrementNonce(NONCE);
QCOMPARE(result, INCREMENTEDNONCE);
const QString invalidNonce = "dGVzdHN0cmluZw==";
result = browserMessageBuilder()->incrementNonce(invalidNonce);
QVERIFY(result.isEmpty());
}
void TestBrowser::testBuildResponse()
{
const auto object = QJsonObject{{"test", true}};
const QJsonArray arr = {QJsonObject{{"test", true}}};
const auto val = QString("value1");
// Note: Passing a const QJsonObject will fail
const Parameters params{
{"test-param-1", val}, {"test-param-2", 2}, {"test-param-3", false}, {"object", object}, {"arr", arr}};
const auto action = QString("test-action");
const auto message = browserMessageBuilder()->buildResponse(action, NONCE, params, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(!message.isEmpty());
QCOMPARE(message["action"].toString(), action);
QCOMPARE(message["nonce"].toString(), NONCE);
const auto decrypted =
browserMessageBuilder()->decryptMessage(message["message"].toString(), NONCE, PUBLICKEY, SERVERSECRETKEY);
QVERIFY(!decrypted.isEmpty());
QCOMPARE(decrypted["test-param-1"].toString(), QString("value1"));
QCOMPARE(decrypted["test-param-2"].toInt(), 2);
QCOMPARE(decrypted["test-param-3"].toBool(), false);
const auto objectResult = decrypted["object"].toObject();
QCOMPARE(objectResult["test"].toBool(), true);
const auto arrResult = decrypted["arr"].toArray();
QCOMPARE(arrResult.size(), 1);
const auto firstArr = arrResult[0].toObject();
QCOMPARE(firstArr["test"].toBool(), true);
}
void TestBrowser::testSortPriority()
{
QFETCH(QString, entryUrl);
QFETCH(QString, siteUrl);
QFETCH(QString, formUrl);
QFETCH(int, expectedScore);
QScopedPointer<Entry> entry(new Entry());
entry->setUrl(entryUrl);
QCOMPARE(m_browserService->sortPriority(entry->getAllUrls(), siteUrl, formUrl), expectedScore);
}
void TestBrowser::testSortPriority_data()
{
const QString siteUrl = "https://github.com/login";
const QString formUrl = "https://github.com/session";
QTest::addColumn<QString>("entryUrl");
QTest::addColumn<QString>("siteUrl");
QTest::addColumn<QString>("formUrl");
QTest::addColumn<int>("expectedScore");
QTest::newRow("Exact Match") << siteUrl << siteUrl << siteUrl << 100;
QTest::newRow("Exact Match (site)") << siteUrl << siteUrl << formUrl << 100;
QTest::newRow("Exact Match (form)") << siteUrl << "https://github.net" << siteUrl << 100;
QTest::newRow("Exact Match No Trailing Slash") << "https://github.com" << "https://github.com/" << formUrl << 100;
QTest::newRow("Exact Match No Scheme") << "github.com/login" << siteUrl << formUrl << 100;
QTest::newRow("Exact Match with Query")
<< "https://github.com/login?test=test#fragment" << "https://github.com/login?test=test" << formUrl << 100;
QTest::newRow("Site Query Mismatch") << siteUrl << siteUrl + "?test=test" << formUrl << 90;
QTest::newRow("Path Mismatch (site)") << "https://github.com/" << siteUrl << formUrl << 85;
QTest::newRow("Path Mismatch (site) No Scheme") << "github.com" << siteUrl << formUrl << 85;
QTest::newRow("Path Mismatch (form)") << "https://github.com/" << "https://github.net" << formUrl << 85;
QTest::newRow("Path Mismatch (diff parent)") << "https://github.com/keepassxreboot" << siteUrl << formUrl << 80;
QTest::newRow("Path Mismatch (diff parent, form)")
<< "https://github.com/keepassxreboot" << "https://github.net" << formUrl << 70;
QTest::newRow("Subdomain Mismatch (site)") << siteUrl << "https://sub.github.com/" << "https://github.net/" << 60;
QTest::newRow("Subdomain Mismatch (form)") << siteUrl << "https://github.net/" << "https://sub.github.com/" << 50;
QTest::newRow("Scheme Mismatch") << "http://github.com" << siteUrl << formUrl << 0;
QTest::newRow("Scheme Mismatch w/path") << "http://github.com/login" << siteUrl << formUrl << 0;
QTest::newRow("Invalid URL") << "http://github" << siteUrl << formUrl << 0;
}
void TestBrowser::testSearchEntries()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"https://github.com/login_page",
"https://github.com/login",
"https://github.com/",
"github.com/login",
"http://github.com",
"http://github.com/login",
"github.com",
"github.com/login",
"https://github", // Invalid URL
"github.com"};
createEntries(urls, root);
browserSettings()->setMatchUrlScheme(false);
auto result =
m_browserService->searchEntries(db, "https://github.com", "https://github.com/session"); // db, url, submitUrl
QCOMPARE(result.length(), 9);
QCOMPARE(result[0]->url(), QString("https://github.com/login_page"));
QCOMPARE(result[1]->url(), QString("https://github.com/login"));
QCOMPARE(result[2]->url(), QString("https://github.com/"));
QCOMPARE(result[3]->url(), QString("github.com/login"));
QCOMPARE(result[4]->url(), QString("http://github.com"));
QCOMPARE(result[5]->url(), QString("http://github.com/login"));
// With matching there should be only 4 results + 4 without a scheme
browserSettings()->setMatchUrlScheme(true);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 7);
QCOMPARE(result[0]->url(), QString("https://github.com/login_page"));
QCOMPARE(result[1]->url(), QString("https://github.com/login"));
QCOMPARE(result[2]->url(), QString("https://github.com/"));
QCOMPARE(result[3]->url(), QString("github.com/login"));
}
void TestBrowser::testSearchEntriesByPath()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urlsRoot = {"https://root.example.com/", "root.example.com/login"};
auto entriesRoot = createEntries(urlsRoot, root);
auto* groupLevel1 = new Group();
groupLevel1->setParent(root);
groupLevel1->setName("TestGroup1");
QStringList urlsLevel1 = {"https://1.example.com/", "1.example.com/login"};
auto entriesLevel1 = createEntries(urlsLevel1, groupLevel1);
auto* groupLevel2 = new Group();
groupLevel2->setParent(groupLevel1);
groupLevel2->setName("TestGroup2");
QStringList urlsLevel2 = {"https://2.example.com/", "2.example.com/login"};
auto entriesLevel2 = createEntries(urlsLevel2, groupLevel2);
compareEntriesByPath(db, entriesRoot, "");
compareEntriesByPath(db, entriesLevel1, "TestGroup1/");
compareEntriesByPath(db, entriesLevel2, "TestGroup1/TestGroup2/");
}
void TestBrowser::compareEntriesByPath(QSharedPointer<Database> db, QList<Entry*> entries, QString path)
{
for (Entry* entry : entries) {
QString testUrl = "keepassxc://by-path/" + path + entry->title();
/* Look for an entry with that path. First using handleEntry, then through the search */
QCOMPARE(m_browserService->shouldIncludeEntry(entry, testUrl, ""), true);
auto result = m_browserService->searchEntries(db, testUrl, "");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0], entry);
}
}
void TestBrowser::testSearchEntriesByUUID()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
/* The URLs don't really matter for this test, we just need some entries */
QStringList urls = {"https://github.com/login_page",
"https://github.com/login",
"https://github.com/",
"github.com/login",
"http://github.com",
"http://github.com/login",
"github.com",
"github.com/login",
"https://github",
"github.com",
"",
"not an URL"};
auto entries = createEntries(urls, root);
for (Entry* entry : entries) {
QString testUrl = "keepassxc://by-uuid/" + entry->uuidToHex();
/* Look for an entry with that UUID. First using shouldIncludeEntry, then through the search */
QCOMPARE(m_browserService->shouldIncludeEntry(entry, testUrl, ""), true);
auto result = m_browserService->searchEntries(db, testUrl, "");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0], entry);
}
/* Test for entries that don't exist */
QStringList uuids = {"00000000000000000000000000000000",
"00000000000000000000000000000001",
"00000000000000000000000000000002/",
"invalid uuid",
"000000000000000000000000000000000000000"
"00000000000000000000000"};
for (QString uuid : uuids) {
QString testUrl = "keepassxc://by-uuid/" + uuid;
for (Entry* entry : entries) {
QCOMPARE(m_browserService->shouldIncludeEntry(entry, testUrl, ""), false);
}
auto result = m_browserService->searchEntries(db, testUrl, "");
QCOMPARE(result.length(), 0);
}
}
void TestBrowser::testSearchEntriesByReference()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
/* The URLs don't really matter for this test, we just need some entries */
QStringList urls = {"https://subdomain.example.com",
"example.com", // Only includes a partial URL for references
"https://another.domain.com", // Additional URL as full reference
"https://subdomain.somesite.com", // Additional URL as partial reference
"", // Full reference will be added to https://subdomain.example.com
"" // Partial reference will be added to https://subdomain.example.com
"https://www.notincluded.com"}; // Should not show in search
auto entries = createEntries(urls, root);
auto firstEntryUuid = entries.first()->uuidToHex();
auto secondEntryUuid = entries[1]->uuidToHex();
auto fullReference = QString("{REF:A@I:%1}").arg(firstEntryUuid);
auto partialReference = QString("https://subdomain.{REF:A@I:%1}").arg(secondEntryUuid);
entries[2]->attributes()->set(EntryAttributes::AdditionalUrlAttribute, fullReference);
entries[3]->attributes()->set(EntryAttributes::AdditionalUrlAttribute, partialReference);
entries[4]->setUrl(fullReference);
entries[5]->setUrl(partialReference);
auto result = m_browserService->searchEntries(db, "https://subdomain.example.com", "");
QCOMPARE(result.length(), 6);
QCOMPARE(result[0]->url(), urls[0]);
QCOMPARE(result[1]->url(), urls[1]);
QCOMPARE(result[2]->url(), urls[2]);
QCOMPARE(
result[2]->resolveMultiplePlaceholders(result[2]->attributes()->value(EntryAttributes::AdditionalUrlAttribute)),
urls[0]);
QCOMPARE(result[3]->url(), urls[3]);
QCOMPARE(
result[3]->resolveMultiplePlaceholders(result[3]->attributes()->value(EntryAttributes::AdditionalUrlAttribute)),
urls[0]);
QCOMPARE(result[4]->url(), fullReference);
QCOMPARE(result[4]->resolveMultiplePlaceholders(result[4]->url()), urls[0]); // Should be resolved to the main entry
QCOMPARE(result[5]->url(), partialReference);
QCOMPARE(result[5]->resolveMultiplePlaceholders(result[5]->url()), urls[0]); // Should be resolved to the main entry
}
void TestBrowser::testSearchEntriesWithPort()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"http://127.0.0.1:443", "http://127.0.0.1:80"};
createEntries(urls, root);
auto result = m_browserService->searchEntries(db, "http://127.0.0.1:443", "http://127.0.0.1");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0]->url(), QString("http://127.0.0.1:443"));
}
void TestBrowser::testSearchEntriesWithAdditionalURLs()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"https://github.com/", "https://www.example.com", "http://domain.com"};
auto entries = createEntries(urls, root);
// Add an additional URL to the first entry
entries.first()->attributes()->set(EntryAttributes::AdditionalUrlAttribute, "https://keepassxc.org");
auto result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0]->url(), QString("https://github.com/"));
// Search the additional URL. It should return the same entry
auto additionalResult = m_browserService->searchEntries(db, "https://keepassxc.org", "https://keepassxc.org");
QCOMPARE(additionalResult.length(), 1);
QCOMPARE(additionalResult[0]->url(), QString("https://github.com/"));
additionalResult = m_browserService->searchEntries(db, "https://keepassxc.org/", ""); // With slash at the end
QCOMPARE(additionalResult.length(), 1);
QCOMPARE(additionalResult[0]->url(), QString("https://github.com/"));
}
// Tests wildcards through the whole entry search pipeline using searchEntries()
void TestBrowser::testSearchEntriesWithWildcardURLs()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"https://github.com/login_page/*",
"https://github.com/*/second",
"https://github.com/*",
"http://github.com/*",
"github.com/*", // Defaults to https
"https://*.github.com/*",
"https://subdomain.*.github.com/*/second",
"https://*.sub.github.com/*",
"https://********", // Invalid wildcard URL
"https://*.thub.com/", // Partial suffix URL
"https://subdomain.yes.github.com/*",
"https://example.com:8448/*",
"https://example.com/*/*",
"https://example.com/$/*",
"https://127.128.129.*:8448/",
"https://127.128.*/",
"https://127.160.*.2/login",
"http://[2001:db8:85a3:8d3:1319:8a2e:370:*]/",
"https://[2001:db8:85a3:8d3:*]:443/",
"fe80::1ff:fe23:4567:890a",
"2001-db8-85a3-8d3-1319-8a2e-370-7348.ipv6-literal.net",
"\"https://thisisatest.com/login.php\"", // Exact URL
"https://*.good.test",
"https://login.*.example.com",
"https://10.1.*.3",
"https://test.domain.com/*",
"https://second.domain.com/foo/*",
"https://third.domain.com/foo*", // Should match path "foo" and "foo/*"
"https://*.newexample.com/login",
"https://*.anotherexample.com",
"https://*.anotherexample.com/"};
createEntries(urls, root, true);
browserSettings()->setMatchUrlScheme(false);
// Return first Additional URL
auto firstUrl = [&](Entry* entry) { return entry->attributes()->value(EntryAttributes::AdditionalUrlAttribute); };
auto result = m_browserService->searchEntries(
db, "https://github.com/login_page/second", "https://github.com/login_page/second");
QCOMPARE(result.length(), 5);
QCOMPARE(firstUrl(result[0]), QString("https://github.com/login_page/*"));
QCOMPARE(firstUrl(result[1]), QString("https://github.com/*/second"));
QCOMPARE(firstUrl(result[2]), QString("https://github.com/*"));
QCOMPARE(firstUrl(result[3]), QString("http://github.com/*"));
QCOMPARE(firstUrl(result[4]), QString("github.com/*"));
result = m_browserService->searchEntries(
db, "https://subdomain.sub.github.com/login_page/second", "https://subdomain.sub.github.com/login_page/second");
QCOMPARE(result.length(), 3);
QCOMPARE(firstUrl(result[0]), QString("https://*.github.com/*"));
QCOMPARE(firstUrl(result[1]), QString("https://subdomain.*.github.com/*/second"));
QCOMPARE(firstUrl(result[2]), QString("https://*.sub.github.com/*"));
result = m_browserService->searchEntries(
db, "https://subdomain.sub.github.com/other_page", "https://subdomain.sub.github.com/other_page");
QCOMPARE(result.length(), 2);
QCOMPARE(firstUrl(result[0]), QString("https://*.github.com/*"));
QCOMPARE(firstUrl(result[1]), QString("https://*.sub.github.com/*"));
result = m_browserService->searchEntries(
db, "https://subdomain.yes.github.com/other_page/second", "https://subdomain.yes.github.com/other_page/second");
QCOMPARE(result.length(), 3);
QCOMPARE(firstUrl(result[0]), QString("https://*.github.com/*"));
QCOMPARE(firstUrl(result[1]), QString("https://subdomain.*.github.com/*/second"));
QCOMPARE(firstUrl(result[2]), QString("https://subdomain.yes.github.com/*"));
// Exact URL
result =
m_browserService->searchEntries(db, "https://thisisatest.com/login.php", "https://thisisatest.com/login.php");
QCOMPARE(result.length(), 1);
QCOMPARE(firstUrl(result[0]), QString("\"https://thisisatest.com/login.php\""));
// With scheme matching enabled
browserSettings()->setMatchUrlScheme(true);
result = m_browserService->searchEntries(
db, "https://github.com/login_page/second", "https://github.com/login_page/second");
QCOMPARE(result.length(), 4);
QCOMPARE(firstUrl(result[0]), QString("https://github.com/login_page/*"));
QCOMPARE(firstUrl(result[1]), QString("https://github.com/*/second"));
QCOMPARE(firstUrl(result[2]), QString("https://github.com/*"));
QCOMPARE(firstUrl(result[3]), QString("github.com/*")); // Defaults to https
}
void TestBrowser::testHandleURL_data()
{
QTest::addColumn<QString>("entryUrl");
QTest::addColumn<QString>("siteUrl");
QTest::addColumn<QString>("formUrl");
QTest::addColumn<bool>("omitWwwSubdomain");
QTest::addColumn<bool>("allowWildcards");
QTest::addColumn<bool>("match");
auto pattern = "https://example.com";
auto siteUrl = "https://example.com/";
// Reject invalid URLs
QTest::newRow("empty entry URL") << "" << siteUrl << siteUrl << false << false << false;
QTest::newRow("illegal entry character")
<< "https://example.com/<login>" << siteUrl << siteUrl << false << false << false;
// Non-wildcard matching ignores path
QTest::addRow("ignore path %s %d", pattern, 0) << pattern << pattern << pattern << true << false << true;
QTest::addRow("ignore path %s %d", pattern, 1)
<< pattern << QString(pattern) + "/" << pattern << true << false << true;
QTest::addRow("ignore path %s %d", pattern, 2)
<< pattern << QString(pattern) + "/foobar" << pattern << true << false << true;
QTest::addRow("ignore path %s %d", pattern, 3)
<< pattern << QString(pattern) + "/*" << pattern << true << false << true;
// Strip www
pattern = "https://www.example.com/";
QTest::newRow("strip www") << pattern << siteUrl << siteUrl << true << false << true;
QTest::newRow("no strip www") << pattern << siteUrl << siteUrl << false << false << false;
// Non-wildcard URLs match all subdomains
pattern = "https://example.com/";
siteUrl = "https://www.example.com/";
QTest::newRow("match www subdomain") << pattern << siteUrl << siteUrl << false << false << true;
siteUrl = "https://abc.example.com/";
QTest::newRow("match other subdomain") << pattern << siteUrl << siteUrl << false << false << true;
// Host must not match parent or unrelated suffixes / prefixes
siteUrl = "https://example.com/";
QTest::newRow("reject parent domain")
<< "https://login.example.com/" << siteUrl << siteUrl << false << false << false;
QTest::newRow("reject hostname prefix")
<< pattern << "https://notexample.com/" << siteUrl << false << false << false;
QTest::newRow("reject hostname suffix")
<< pattern << "https://example.com.evil.org/" << siteUrl << false << false << false;
// Explicit port must match
siteUrl = "https://example.com:8443/";
QTest::newRow("same port") << "https://example.com:8443/" << siteUrl << siteUrl << false << false << true;
QTest::newRow("different port") << "https://example.com:9443/" << siteUrl << siteUrl << false << false << false;
// Wildcard URLs have strict subdomain and path matching
pattern = "https://example.com/*";
siteUrl = "https://abc.example.com/";
QTest::newRow("wildcard strict domain") << pattern << siteUrl << siteUrl << false << true << false;
pattern = "https://*.example.com/*";
QTest::newRow("wildcard subdomain") << pattern << siteUrl << siteUrl << false << true << true;
pattern = "https://*.example.com/";
siteUrl = "https://abc.example.com/abc";
QTest::newRow("wildcard strict path") << pattern << siteUrl << siteUrl << false << true << false;
pattern = "\"https://example.com/login\"";
siteUrl = "https://example.com/login";
QTest::newRow("quoted exact URL") << pattern << siteUrl << siteUrl << false << true << true;
QTest::newRow("quoted different path")
<< pattern << "https://example.com/other" << siteUrl << false << true << false;
// Unrelated form URLs must be rejected
pattern = "https://example.com/";
QTest::newRow("related form URL") << pattern << "https://other.example.com/" << pattern << false << false << true;
QTest::newRow("unrelated form URL") << pattern << "https://other.example.org/" << pattern << false << false
<< false;
// Local pages require a match between page and form url
siteUrl = "file:///tmp/login.html";
QTest::newRow("local page matching form URL") << pattern << siteUrl << pattern << false << false << true;
QTest::newRow("local page different form URL") << siteUrl << siteUrl << pattern << false << false << false;
QTest::newRow("local page empty form URL") << siteUrl << siteUrl << "" << false << false << false;
}
void TestBrowser::testHandleURL()
{
QFETCH(QString, entryUrl);
QFETCH(QString, siteUrl);
QFETCH(QString, formUrl);
QFETCH(bool, omitWwwSubdomain);
QFETCH(bool, allowWildcards);
QFETCH(bool, match);
QVERIFY(m_browserService->handleURL(entryUrl, siteUrl, formUrl, omitWwwSubdomain, allowWildcards) == match);
}
void TestBrowser::testHandleURLWithWildcards_data()
{
QTest::addColumn<QString>("entryUrl");
QTest::addColumn<QString>("siteUrl");
QTest::addColumn<bool>("match");
auto entryUrl = "https://test.domain.com/*";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << "https://test.domain.com/other_page/third" << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://test.domain.com" << true;
QTest::addRow("%s %d", entryUrl, 2) << entryUrl << "https://test.domain.com/" << true;
// https://second.domain.com/foo/ with any path (or without a path) should match https://second.domain.com/foo/*
entryUrl = "https://second.domain.com/foo/*";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << "https://second.domain.com/foo/third/" << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://second.domain.com/foo" << false;
QTest::addRow("%s %d", entryUrl, 2) << entryUrl << "https://second.domain.com/foo/" << true;
// "Should match path "foo" and "foo/*"
entryUrl = "https://third.domain.com/foo*";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << "https://third.domain.com/foo/third" << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://third.domain.com/foo" << true;
QTest::addRow("%s %d", entryUrl, 2) << entryUrl << "https://third.domain.com/foo/" << true;
auto siteUrl = "https://example.com:8448/login/page";
QTest::newRow("https://example.com:8448/*") << "https://example.com:8448/*" << siteUrl << true;
entryUrl = "https://example.com/*/*";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << siteUrl << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://example.com:8449/login/page" << true; // With port
siteUrl = "https://example.com/$/login_page";
QTest::addRow("%s %d", entryUrl, 2) << entryUrl << siteUrl << true;
QTest::newRow("https://example.com/$/*") << "https://example.com/$/*" << siteUrl << true;
// IP addresses and ports
siteUrl = "https://127.128.129.130:8448/";
QTest::newRow("https://127.128.129.*:8448/") << "https://127.128.129.*:8448/" << siteUrl << true;
entryUrl = "https://127.128.*/";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << siteUrl << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://127.128.129.130/" << true;
QTest::addRow("%s %d", entryUrl, 2) << entryUrl << "https://127.1.129.130/" << false;
QTest::newRow("https://127.160.*.2/login") << "https://127.160.*.2/login" << "https://127.160.8.2/login" << true;
// Wildcard domains
// https://*.good.test must not match with https://www.good.test.evil.test/
entryUrl = " https://*.good.test";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << "https://very.good.test/" << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << "https://www.good.test.evil.test/" << false;
// https://login.*.example.com must not match with https://notlogin.foo.example.com
QTest::newRow("https://login.*.example.com")
<< "https://login.*.example.com" << "https://notlogin.foo.example.com" << false;
// https://10.1.*.3 must not match with https://110.1.2.3
QTest::newRow("https://10.1.*.3") << "https://10.1.*.3" << "https://110.1.2.32" << false;
// Domain wildcards
// https://app.newexample.com/login should return "https://*.newexample.com/login"
QTest::newRow("https://*.newexample.com/login")
<< "https://*.newexample.com/login" << "https://app.newexample.com/login" << true;
// https://www.anotherexample.com/xyz should return nothing
QTest::newRow("https://www.anotherexample.com/xyz")
<< "https://www.anotherexample.com/xyz" << "https://*.example.com/" << false;
// https://www.anotherexample.com/ should return both https://*.example.com and https://*.example.com/
entryUrl = "https://*.anotherexample.com";
siteUrl = "https://www.anotherexample.com/";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << siteUrl << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << siteUrl << true;
// https://www.anotherexample.com should return both https://*.example.com and https://*.example.com/
entryUrl = "https://www.anotherexample.com";
siteUrl = "https://www.anotherexample.com";
QTest::addRow("%s %d", entryUrl, 0) << entryUrl << siteUrl << true;
QTest::addRow("%s %d", entryUrl, 1) << entryUrl << siteUrl << true;
}
void TestBrowser::testHandleURLWithWildcards()
{
QFETCH(QString, entryUrl);
QFETCH(QString, siteUrl);
QFETCH(bool, match);
auto entryQUrl = QUrl::fromUserInput(entryUrl.replace("*", UrlTools::URL_WILDCARD));
QVERIFY(m_browserService->handleURLWithWildcards(entryQUrl, siteUrl) == match);
}
void TestBrowser::testInvalidEntries()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
const QString url("https://github.com");
const QString submitUrl("https://github.com/session");
QStringList urls = {
"https://github.com/login",
"https:///github.com/", // Extra '/'
"http://github.com/**//*",
"http://*.github.com/login",
"//github.com", // fromUserInput() corrects this one.
"github.com/{}<>",
"http:/example.com",
};
createEntries(urls, root);
browserSettings()->setMatchUrlScheme(true);
auto result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 2);
QCOMPARE(result[0]->url(), QString("https://github.com/login"));
QCOMPARE(result[1]->url(), QString("//github.com"));
// Test the URL's directly
QCOMPARE(m_browserService->handleURL(urls[0], url, submitUrl), true);
QCOMPARE(m_browserService->handleURL(urls[1], url, submitUrl), false);
QCOMPARE(m_browserService->handleURL(urls[2], url, submitUrl), false);
QCOMPARE(m_browserService->handleURL(urls[3], url, submitUrl), false);
QCOMPARE(m_browserService->handleURL(urls[4], url, submitUrl), true);
QCOMPARE(m_browserService->handleURL(urls[5], url, submitUrl), false);
}
void TestBrowser::testSubdomainsAndPaths()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"https://www.github.com/login/page.xml",
"https://login.github.com/",
"https://github.com",
"http://www.github.com",
"http://login.github.com/pathtonowhere",
".github.com", // Invalid URL
"www.github.com/",
"https://github", // Invalid URL
"https://hub.com", // Should not return
"https://login.example.com"};
createEntries(urls, root);
browserSettings()->setMatchUrlScheme(false);
auto result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0]->url(), QString("https://github.com"));
// With www subdomain
result = m_browserService->searchEntries(db, "https://www.github.com", "https://www.github.com/session");
QCOMPARE(result.length(), 4);
QCOMPARE(result[0]->url(), QString("https://www.github.com/login/page.xml"));
QCOMPARE(result[1]->url(), QString("https://github.com")); // Accepts any subdomain
QCOMPARE(result[2]->url(), QString("http://www.github.com"));
QCOMPARE(result[3]->url(), QString("www.github.com/"));
// With www subdomain omitted
root->setCustomDataTriState(BrowserService::OPTION_OMIT_WWW, Group::Enable);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
root->setCustomDataTriState(BrowserService::OPTION_OMIT_WWW, Group::Inherit);
QCOMPARE(result.length(), 4);
QCOMPARE(result[0]->url(), QString("https://www.github.com/login/page.xml"));
QCOMPARE(result[1]->url(), QString("https://github.com"));
QCOMPARE(result[2]->url(), QString("http://www.github.com"));
QCOMPARE(result[3]->url(), QString("www.github.com/"));
// Check subdomain matching. "notlogin." should not match with "login."
QCOMPARE(m_browserService->searchEntries(db, "https://login.example.com", "").length(), 1);
QCOMPARE(m_browserService->searchEntries(db, "https://another.login.example.com", "").length(), 1);
QCOMPARE(m_browserService->searchEntries(db, "https://notlogin.example.com", "").length(), 0);
// With scheme matching there should be only 1 result
browserSettings()->setMatchUrlScheme(true);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0]->url(), QString("https://github.com"));
// Test site with subdomain in the site URL
QStringList entryURLs = {
"https://accounts.example.com",
"https://accounts.example.com/path",
"https://subdomain.example.com/",
"https://another.accounts.example.com/",
"https://another.subdomain.example.com/",
"https://example.com/",
"https://example" // Invalid URL
};
createEntries(entryURLs, root);
result = m_browserService->searchEntries(db, "https://accounts.example.com/", "https://accounts.example.com/");
QCOMPARE(result.length(), 3);
QCOMPARE(result[0]->url(), QString("https://accounts.example.com"));
QCOMPARE(result[1]->url(), QString("https://accounts.example.com/path"));
QCOMPARE(result[2]->url(), QString("https://example.com/")); // Accepts any subdomain
result = m_browserService->searchEntries(
db, "https://another.accounts.example.com/", "https://another.accounts.example.com/");
QCOMPARE(result.length(), 4);
QCOMPARE(result[0]->url(),
QString("https://accounts.example.com")); // Accepts any subdomain under accounts.example.com
QCOMPARE(result[1]->url(), QString("https://accounts.example.com/path"));
QCOMPARE(result[2]->url(), QString("https://another.accounts.example.com/"));
QCOMPARE(result[3]->url(), QString("https://example.com/")); // Accepts one or more subdomains
// Test local files. It should be a direct match.
QStringList localFiles = {"file:///Users/testUser/tests/test.html"};
createEntries(localFiles, root);
// With local files, url is always set to the file scheme + ://. Submit URL holds the actual URL.
result = m_browserService->searchEntries(db, "file://", "file:///Users/testUser/tests/test.html");
QCOMPARE(result.length(), 1);
}
QList<Entry*> TestBrowser::createEntries(QStringList& urls, Group* root, bool additionalUrl) const
{
QList<Entry*> entries;
for (int i = 0; i < urls.length(); ++i) {
auto entry = new Entry();
entry->setGroup(root);
entry->beginUpdate();
if (additionalUrl) {
entry->attributes()->set(EntryAttributes::AdditionalUrlAttribute, urls[i]);
} else {
entry->setUrl(urls[i]);
}
entry->setUsername(QString("User %1").arg(i));
entry->setUuid(QUuid::createUuid());
entry->setTitle(QString("Name_%1").arg(entry->uuidToHex()));
entry->endUpdate();
entries.push_back(entry);
}
return entries;
}
void TestBrowser::testBestMatchingCredentials()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
// Test with simple URL entries
QStringList urls = {"https://github.com/loginpage", "https://github.com/justsomepage", "https://github.com/"};
auto entries = createEntries(urls, root);
browserSettings()->setBestMatchOnly(true);
QString siteUrl = "https://github.com/loginpage";
auto result = m_browserService->searchEntries(db, siteUrl, siteUrl);
auto sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), siteUrl);
siteUrl = "https://github.com/justsomepage";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), siteUrl);
siteUrl = "https://github.com/";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(entries, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), siteUrl);
// Without best-matching the URL with the path should be returned first
browserSettings()->setBestMatchOnly(false);
siteUrl = "https://github.com/loginpage";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 3);
QCOMPARE(sorted[0]->url(), siteUrl);
// Test with subdomains
QStringList subdomainsUrls = {"https://sub.github.com/loginpage",
"https://sub.github.com/justsomepage",
"https://bus.github.com/justsomepage",
"https://subdomain.example.com/",
"https://subdomain.example.com",
"https://example.com"};
entries = createEntries(subdomainsUrls, root);
browserSettings()->setBestMatchOnly(true);
siteUrl = "https://sub.github.com/justsomepage";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), siteUrl);
siteUrl = "https://github.com/justsomepage";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), siteUrl);
siteUrl = "https://sub.github.com/justsomepage?wehavesomeextra=here";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), QString("https://sub.github.com/justsomepage"));
// The matching should not care if there's a / path or not.
siteUrl = "https://subdomain.example.com/";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 2);
QCOMPARE(sorted[0]->url(), QString("https://subdomain.example.com"));
QCOMPARE(sorted[1]->url(), QString("https://subdomain.example.com/"));
// Entries with https://example.com should be still returned even if the site URL has a subdomain. Those have the
// best match.
db = QSharedPointer<Database>::create();
root = db->rootGroup();
QStringList domainUrls = {"https://example.com", "https://example.com", "https://other.example.com"};
entries = createEntries(domainUrls, root);
siteUrl = "https://subdomain.example.com";
result = m_browserService->searchEntries(db, siteUrl, siteUrl);
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 2);
QCOMPARE(sorted[0]->url(), QString("https://example.com"));
QCOMPARE(sorted[1]->url(), QString("https://example.com"));
// https://github.com/keepassxreboot/keepassxc/issues/4754
db = QSharedPointer<Database>::create();
root = db->rootGroup();
QStringList fooUrls = {"https://example.com/foo", "https://example.com/bar"};
entries = createEntries(fooUrls, root);
for (const auto& url : fooUrls) {
result = m_browserService->searchEntries(db, url, url);
sorted = m_browserService->sortEntries(result, url, url);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), QString(url));
}
// https://github.com/keepassxreboot/keepassxc/issues/4734
db = QSharedPointer<Database>::create();
root = db->rootGroup();
QStringList testUrls = {"http://some.domain.tld/somePath", "http://some.domain.tld/otherPath"};
entries = createEntries(testUrls, root);
for (const auto& url : testUrls) {
result = m_browserService->searchEntries(db, url, url);
sorted = m_browserService->sortEntries(result, url, url);
QCOMPARE(sorted.size(), 1);
QCOMPARE(sorted[0]->url(), QString(url));
}
}
void TestBrowser::testBestMatchingWithAdditionalURLs()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
QStringList urls = {"https://github.com/loginpage", "https://test.github.com/", "https://github.com/"};
auto entries = createEntries(urls, root);
browserSettings()->setBestMatchOnly(true);
// Add an additional URL to the first entry
entries.first()->attributes()->set(EntryAttributes::AdditionalUrlAttribute, "https://test.github.com/anotherpage");
// The first entry should be triggered
auto result = m_browserService->searchEntries(
db, "https://test.github.com/anotherpage", "https://test.github.com/anotherpage");
auto sorted = m_browserService->sortEntries(
result, "https://test.github.com/anotherpage", "https://test.github.com/anotherpage");
QCOMPARE(sorted.length(), 1);
QCOMPARE(sorted[0]->url(), urls[0]);
}
void TestBrowser::testRestrictBrowserKey()
{
auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
// Group 0 (root): No browser key restriction given
QStringList urlsRoot = {"https://example.com/0"};
auto entriesRoot = createEntries(urlsRoot, root);
// Group 1: restricted to browser with 'key1'
auto* group1 = new Group();
group1->setParent(root);
group1->setName("TestGroup1");
group1->customData()->set(BrowserService::OPTION_RESTRICT_KEY, "key1");
QStringList urls1 = {"https://example.com/1"};
auto entries1 = createEntries(urls1, group1);
// Group 2: restricted to browser with 'key2'
auto* group2 = new Group();
group2->setParent(root);
group2->setName("TestGroup2");
group2->customData()->set(BrowserService::OPTION_RESTRICT_KEY, "key2");
QStringList urls2 = {"https://example.com/2"};
auto entries2 = createEntries(urls2, group2);
// Group 2b: inherits parent group (2) restriction
auto* group2b = new Group();
group2b->setParent(group2);
group2b->setName("TestGroup2b");
QStringList urls2b = {"https://example.com/2b"};
auto entries2b = createEntries(urls2b, group2b);
// Group 3: inherits parent group (root) - any browser can see
auto* group3 = new Group();
group3->setParent(root);
group3->setName("TestGroup3");
QStringList urls3 = {"https://example.com/3"};
auto entries3 = createEntries(urls3, group3);
// Browser 'key0': Groups 1 and 2 are excluded, so entries 0 and 3 will be found
auto siteUrl = QString("https://example.com");
auto result = m_browserService->searchEntries(db, siteUrl, siteUrl, {"key0"});
auto sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 2);
QCOMPARE(sorted[0]->url(), QString("https://example.com/3"));
QCOMPARE(sorted[1]->url(), QString("https://example.com/0"));
// Browser 'key1': Group 2 will be excluded, so entries 0, 1, and 3 will be found
result = m_browserService->searchEntries(db, siteUrl, siteUrl, {"key1"});
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 3);
QCOMPARE(sorted[0]->url(), QString("https://example.com/3"));
QCOMPARE(sorted[1]->url(), QString("https://example.com/1"));
QCOMPARE(sorted[2]->url(), QString("https://example.com/0"));
// Browser 'key2': Group 1 will be excluded, so entries 0, 2, 2b, 3 will be found
result = m_browserService->searchEntries(db, siteUrl, siteUrl, {"key2"});
sorted = m_browserService->sortEntries(result, siteUrl, siteUrl);
QCOMPARE(sorted.size(), 4);
QCOMPARE(sorted[0]->url(), QString("https://example.com/3"));
QCOMPARE(sorted[1]->url(), QString("https://example.com/2b"));
QCOMPARE(sorted[2]->url(), QString("https://example.com/2"));
QCOMPARE(sorted[3]->url(), QString("https://example.com/0"));
}
void TestBrowser::testHideEntry()
{
const auto db = QSharedPointer<Database>::create();
auto* root = db->rootGroup();
const auto entry = new Entry();
entry->setGroup(root);
entry->beginUpdate();
entry->setUrl(QString("https://github.com/"));
entry->setUsername(QString("User 1"));
entry->setUuid(QUuid::createUuid());
entry->setTitle(QString("Name_ 1"));
entry->endUpdate();
// Entry should be found normally
auto result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
QCOMPARE(result[0]->url(), QString("https://github.com/"));
// Hide entry from entry settings, group setting is inherited
entry->customData()->set(BrowserService::OPTION_HIDE_ENTRY, TRUE_STR);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 0);
// Disable hide from group settings, entry should be found
root->setCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY, Group::Disable);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
// Enable hide from group setting, entry should not be found
root->setCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY, Group::Enable);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 0);
// Remove the hide settings from entry, return group setting to inherit
entry->customData()->set(BrowserService::OPTION_HIDE_ENTRY, FALSE_STR);
root->setCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY, Group::Inherit);
// Entry should be found again
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
// Enable hide from group setting, entry should not be found
root->setCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY, Group::Enable);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 0);
// Disable hide from group settings, entry should be found
root->setCustomDataTriState(BrowserService::OPTION_HIDE_ENTRY, Group::Disable);
result = m_browserService->searchEntries(db, "https://github.com", "https://github.com/session");
QCOMPARE(result.length(), 1);
}
void TestBrowser::testBrowserHostMessaging()
{
BrowserHost browserHost;
QByteArray normalMessage(R"({"action": "test-action", "nonce": "testnonce"})");
auto result = browserHost.parseMessage(normalMessage, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
// Not a valid JSON
QByteArray notValid("A normal string");
result = browserHost.parseMessage(notValid, 0);
QVERIFY(result.isEmpty());
// Not a valid JSON
QByteArray notValid2("{A normal string}");
result = browserHost.parseMessage(notValid2, 0);
QVERIFY(result.isEmpty());
// Not a valid JSON
QByteArray notValid3("{A normal string");
result = browserHost.parseMessage(notValid3, 0);
QVERIFY(result.isEmpty());
// If multiple, only first one gets parsed. parseMessage() does not handle coalesced messages.
QByteArray multipleMessages(
R"({"action": "test-action", "nonce": "testnonce"}{"action": "test-action2", "nonce": "testnonce2"})");
result = browserHost.parseMessage(normalMessage, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
// Garbage at the start
QByteArray garbageAtStart(R"(GARBAGE{"action": "test-action", "nonce": "testnonce"})");
result = browserHost.parseMessage(garbageAtStart, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
// Garbage at the start with fragmentation
QByteArray garbageAtStartWithFragmentation(R"(GARBAGE{"action": "test-action", "nonce": "testno)");
result = browserHost.parseMessage(garbageAtStartWithFragmentation, 0);
QVERIFY(result.isEmpty());
// Garbage at the end
QByteArray garbageAtEnd(R"({"action": "test-action", "nonce": "testnonce"}GARBAGE)");
result = browserHost.parseMessage(garbageAtEnd, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
// Garbage at the end as NULL chars
QByteArray garbageAtEndNull(R"({"action": "test-action", "nonce": "testnonce"}GARBAGE)");
garbageAtEndNull.append('\0');
garbageAtEndNull.append('\0');
result = browserHost.parseMessage(garbageAtEndNull, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
// Garbage at the start and end
QByteArray garbageAtBoth(R"(GARBAGE{"action": "test-action", "nonce": "testnonce"}GARBAGE)");
result = browserHost.parseMessage(garbageAtBoth, 0);
QVERIFY(result.value("action") == "test-action" && result.value("nonce") == "testnonce");
}
void TestBrowser::testBrowserHostFragmentedMessaging()
{
BrowserHost browserHost;
// Data has been fragmented between two messages. This is the original for comparison.
const auto originalMessage =
QJsonObject{{"action", "get-database-groups"},
{"message", "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP"},
{"nonce", "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"},
{"clientID", "clientID"}};
// Second parse should return the original message
const QByteArray fragmentedFirst =
R"({"action":"get-database-groups","message":"+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP","nonce":"tZvLrBzkQ9GxXq)";
const QByteArray fragmentedSecond = R"(9PvKJj4iAnfPT0VZ3Q","clientID":"clientID"})";
auto result = browserHost.parseMessage(fragmentedFirst, 0);
result = browserHost.parseMessage(fragmentedSecond, 0);
QVERIFY(result == originalMessage);
// Different kind of fragmentation, comes from different socket
const QByteArray fragmentedTest =
R"({"action": "get-database-groups","message": "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP",)";
const QByteArray fragmentedTest2 = R"("nonce": "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q","clientID": "clientID"})";
result = browserHost.parseMessage(fragmentedTest, 1);
result = browserHost.parseMessage(fragmentedTest2, 1);
QVERIFY(result == originalMessage);
// Different kind of fragmentation, comes from different socket
const QByteArray fragmentedTest3 =
R"({"action": "get-database-groups","message": "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP")";
const QByteArray fragmentedTest4 = R"(,"nonce": "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q","clientID": "clientID"})";
result = browserHost.parseMessage(fragmentedTest3, 2);
result = browserHost.parseMessage(fragmentedTest4, 2);
QVERIFY(result == originalMessage);
// Maximum message size (set to 70) in the last check) exceeded during fragmented message parsing.
// It is multiplied by MAX_FRAGMENTED_FRAMES (3)
const QByteArray fragmentedTest5 =
R"({"action": "get-database-groups","message": "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP")";
const QByteArray fragmentedTest6 = R"(,"nonce": "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q","clientID": "clientID"})";
result = browserHost.parseMessage(fragmentedTest5, 2);
result = browserHost.parseMessage(fragmentedTest6, 2, 70);
QVERIFY(result.isEmpty());
// Test two fragmented frames after the first one
const QByteArray threeFragmented1 = R"({"action":"get-database-groups","message":)";
const QByteArray threeFragmented2 =
R"("+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP","nonce":"tZvLrBzkQ9GxXq)";
const QByteArray threeFragmented3 = R"(9PvKJj4iAnfPT0VZ3Q","clientID":"clientID"})";
result = browserHost.parseMessage(threeFragmented1, 3);
result = browserHost.parseMessage(threeFragmented2, 3);
result = browserHost.parseMessage(threeFragmented3, 3);
QVERIFY(result == originalMessage);
// Two sockets are receiving fragmented messages in mixed order from different sockets
const auto secondOriginalMessage =
QJsonObject{{"action", "get-database-hash"},
{"message", "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP"},
{"nonce", "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"},
{"clientID", "clientID2"}};
const QByteArray mixedOrderFirst1 =
R"({"action": "get-database-groups","message": "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP")";
const QByteArray mixedOrderFirst2 = R"(,"nonce": "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q","clientID": "clientID"})";
const QByteArray mixedOrderSecond1 =
R"({"action": "get-database-hash","message": "+zjtntnk4rGWSl/Ph7Vqip/swvgeupk4lNgHEm2OO3ujNr0OMz6eQtGwjtsj+/rP")";
const QByteArray mixedOrderSecond2 = R"(,"nonce": "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q","clientID": "clientID2"})";
auto resultFirst = browserHost.parseMessage(mixedOrderFirst1, 4);
auto resultSecond = browserHost.parseMessage(mixedOrderSecond1, 5);
resultFirst = browserHost.parseMessage(mixedOrderFirst2, 4);
resultSecond = browserHost.parseMessage(mixedOrderSecond2, 5);
QVERIFY(resultFirst == originalMessage);
QVERIFY(resultSecond == secondOriginalMessage);
}
void TestBrowser::testBrowserHostCoalescedMessaging()
{
BrowserHost browserHost;
// These two are sent together, or together and fragmented
const auto firstOriginalMessage = QJsonObject{{"nonce", "tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"}};
const auto secondOriginalMessage = QJsonObject{{"clientID", "clientID"}};
// A basic coalesced message
const QByteArray coalesced = R"({"nonce":"tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"}{"clientID":"clientID"})";
auto result = browserHost.parseSocketData(coalesced, 0);
QVERIFY(result.length() == 2);
QCOMPARE(result.at(0), firstOriginalMessage);
QCOMPARE(result.at(1), secondOriginalMessage);
// Coalesced but fragmented in first message
const QByteArray fragmented1 = R"({"nonce":"tZvLrBzkQ9GxXq9PvKJj4i)";
const QByteArray fragmented2 = R"(AnfPT0VZ3Q"}{"clientID":"clientID"})";
result = browserHost.parseSocketData(fragmented1, 0);
QVERIFY(result.isEmpty()); // No messages parsed yet
result = browserHost.parseSocketData(fragmented2, 0);
QVERIFY(result.length() == 2);
QCOMPARE(result.at(0), firstOriginalMessage);
QCOMPARE(result.at(1), secondOriginalMessage);
// Coalesced but fragmented in second message. First one should return the "nonce", and cache the start of "client".
const QByteArray fragmented3 = R"({"nonce":"tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"}{"client)";
const QByteArray fragmented4 = R"(ID":"clientID"})";
result = browserHost.parseSocketData(fragmented3, 0);
QCOMPARE(result.first(), firstOriginalMessage);
result = browserHost.parseSocketData(fragmented4, 0);
QCOMPARE(result.first(), secondOriginalMessage);
// Three fragmented messages with coalesced data
const QByteArray fragmented5 = R"({"nonce":"tZvLrBzkQ9GxXq9PvKJj4iAnfPT0VZ3Q"}{"cli)";
const QByteArray fragmented6 = R"(entID":"clie)";
const QByteArray fragmented7 = R"(ntID"})";
result = browserHost.parseSocketData(fragmented5, 0);
QVERIFY(result.length() == 1);
QCOMPARE(result.first(), firstOriginalMessage);
result = browserHost.parseSocketData(fragmented6, 0);
QVERIFY(result.isEmpty()); // Still caching
result = browserHost.parseSocketData(fragmented7, 0);
QVERIFY(result.length() == 1);
QCOMPARE(result.first(), secondOriginalMessage);
}