/*
 * Copyright (C) 2014-2026 CZ.NIC
 *
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * 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/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QDir>
#include <QString>
#include <QtTest/QtTest>

#include "src/datovka_shared/compat/compiler.h" /* macroStdMove */
#include "src/datovka_shared/identifiers/account_id.h"
#include "src/datovka_shared/isds/error.h"
#include "src/datovka_shared/isds/message_interface.h"
#include "src/datovka_shared/isds/types.h"
#include "src/datovka_shared/log/log.h"
#include "src/datovka_shared/settings/prefs.h"
#include "src/global.h"
#include "src/io/isds_sessions.h"
#include "src/isds/message_functions.h"
#include "src/isds/services_login.h"
#include "src/settings/preferences.h"
#include "src/settings/prefs_defaults.h"
#include "src/settings/prefs_specific.h"
#include "src/worker/message_emitter.h"
#include "src/worker/task_authenticate_message.h"
#include "src/worker/task_verify_message.h"
#include "tests/helper_qt.h"
#include "tests/test_task_verify_message.h"

class TestTaskVerifyMessage : public QObject {
	Q_OBJECT

public:
	TestTaskVerifyMessage(void);

	~TestTaskVerifyMessage(void);

private slots:
	void initTestCase(void);

	void cleanupTestCase(void);

	void verifyMessage(void);

	void authenticateMessage(void);

private:
	void loadCredentials(LoginCredentials &cred, int line);

	const bool m_testing; /*!< Testing account. */

	const QString m_testPath; /*!< Test path. */
	QDir m_testDir;  /*!< Directory containing testing data. */

	const QString m_credFName; /*!< Credentials file name. */

	/* Log-in using user name and password. */
	LoginCredentials m_third; /*!< Neither sender nor recipient. */
	LoginCredentials m_sender; /*!< Sender credentials. */

	const QString msgPath;
	const QString delInfoPath;
	const QString tamperedMsgPath;
};

TestTaskVerifyMessage::TestTaskVerifyMessage(void)
    : m_testing(true),
    m_testPath(QDir::currentPath() + QDir::separator() + QLatin1String("_test_dir")),
    m_testDir(m_testPath),
    m_credFName(QLatin1String(CREDENTIALS_FNAME)),
    m_third(),
    m_sender(),
    msgPath("data/DZ_6452235.zfo"),
    delInfoPath("data/DD_6452235.zfo"),
    tamperedMsgPath("data/DZ_6452235_tampered_dmhash.zfo")
{
}

TestTaskVerifyMessage::~TestTaskVerifyMessage(void)
{
}

void TestTaskVerifyMessage::initTestCase(void)
{
	if (!LoginCredentials::isReadableFile(m_credFName)) {
		QSKIP("Missing login credentials file. Skipping remaining tests.");
	}

	QVERIFY(GlobInstcs::logPtr == Q_NULLPTR);
	GlobInstcs::logPtr = new (::std::nothrow) LogDevice;
	QVERIFY(GlobInstcs::logPtr != Q_NULLPTR);

	QVERIFY(GlobInstcs::msgProcEmitterPtr == Q_NULLPTR);
	GlobInstcs::msgProcEmitterPtr =
	    new (::std::nothrow) MessageProcessingEmitter;
	QVERIFY(GlobInstcs::msgProcEmitterPtr != Q_NULLPTR);

	QVERIFY(GlobInstcs::iniPrefsPtr == Q_NULLPTR);
	GlobInstcs::iniPrefsPtr = new (::std::nothrow) INIPreferences;
	QVERIFY(GlobInstcs::iniPrefsPtr != Q_NULLPTR);

	/* Set configuration subdirectory to some value. */
	GlobInstcs::iniPrefsPtr->_confSubdir = QLatin1String(".datovka_test");

	QVERIFY(GlobInstcs::prefsPtr == Q_NULLPTR);
	GlobInstcs::prefsPtr = new (::std::nothrow) Prefs;
	QVERIFY(GlobInstcs::prefsPtr != Q_NULLPTR);
	PrefsDefaults::setDefaults(*GlobInstcs::prefsPtr);

	/* Create ISDS session container. */
	QVERIFY(GlobInstcs::isdsSessionsPtr == Q_NULLPTR);
	GlobInstcs::isdsSessionsPtr = new (::std::nothrow) IsdsSessions;
	if (GlobInstcs::isdsSessionsPtr == Q_NULLPTR) {
		QSKIP("Cannot create session container.");
	}
	QVERIFY(GlobInstcs::isdsSessionsPtr != Q_NULLPTR);

	loadCredentials(m_third, 1);
	loadCredentials(m_sender, 2);
}

void TestTaskVerifyMessage::cleanupTestCase(void)
{
	/* Destroy ISDS session container. */
	delete GlobInstcs::isdsSessionsPtr; GlobInstcs::isdsSessionsPtr = Q_NULLPTR;

	/* The configuration directory should be non-existent. */
	if (GlobInstcs::iniPrefsPtr != Q_NULLPTR) {
		QVERIFY(!QDir(GlobInstcs::iniPrefsPtr->confDir()).exists());
	}

	/* Delete testing directory. */
	m_testDir.removeRecursively();
	QVERIFY(!m_testDir.exists());

	delete GlobInstcs::prefsPtr; GlobInstcs::prefsPtr = Q_NULLPTR;

	delete GlobInstcs::iniPrefsPtr; GlobInstcs::iniPrefsPtr = Q_NULLPTR;

	delete GlobInstcs::msgProcEmitterPtr; GlobInstcs::msgProcEmitterPtr = Q_NULLPTR;

	delete GlobInstcs::logPtr; GlobInstcs::logPtr = Q_NULLPTR;
}

void TestTaskVerifyMessage::verifyMessage(void)
{
	Isds::Message message, delInfo, tamperedMessage;
	QVERIFY(message.isNull());
	QVERIFY(delInfo.isNull());

	message = Isds::messageFromFile(msgPath, Isds::LT_MESSAGE);
	QVERIFY(!message.isNull());
	QVERIFY(!message.envelope().isNull());
	QVERIFY(!message.envelope().dmHash().isNull());

	delInfo = Isds::messageFromFile(delInfoPath, Isds::LT_DELIVERY);
	QVERIFY(!delInfo.isNull());
	QVERIFY(!delInfo.envelope().isNull());
	QVERIFY(!delInfo.envelope().dmHash().isNull());

	tamperedMessage = Isds::messageFromFile(tamperedMsgPath, Isds::LT_MESSAGE);
	QVERIFY(!tamperedMessage.isNull());
	QVERIFY(!tamperedMessage.envelope().isNull());
	QVERIFY(!tamperedMessage.envelope().dmHash().isNull());

	QVERIFY(message.envelope().dmId() == 6452235LL);
	QVERIFY(message.envelope().dmId() == delInfo.envelope().dmId());
	QVERIFY(message.envelope().dmId() == tamperedMessage.envelope().dmId());

	QVERIFY(!tamperedMessage.envelope().dmHash().isNull());

	{
		const Isds::Hash messageHash(message.envelope().dmHash());
		const Isds::Hash delInfoHash(delInfo.envelope().dmHash());
		const Isds::Hash tamperedMessageHash(tamperedMessage.envelope().dmHash());

		QVERIFY(messageHash == message.envelope().dmHash());
		QVERIFY(delInfoHash == delInfo.envelope().dmHash());
		QVERIFY(tamperedMessageHash == tamperedMessage.envelope().dmHash());
		QVERIFY(messageHash == delInfoHash);
		QVERIFY(messageHash != tamperedMessageHash);
		QVERIFY(delInfoHash != tamperedMessageHash);
	}

	TaskVerifyMessage *task = Q_NULLPTR;

	/* Test with account that is nor sender, neither recipient. */
	task = new (::std::nothrow) TaskVerifyMessage(
	    AcntId(m_third.userName, m_testing), message.raw());
	QVERIFY(task != Q_NULLPTR);
	task->setAutoDelete(false);

	task->run();

	QVERIFY(task->m_result == TaskVerifyMessage::VERIFY_ISDS_ERR);

	delete task; task = Q_NULLPTR;

	/* Test with actual sender. */
	task = new (::std::nothrow) TaskVerifyMessage(
	    AcntId(m_sender.userName,m_testing), message.raw());
	QVERIFY(task != Q_NULLPTR);
	task->setAutoDelete(false);

	task->run();

	QVERIFY(task->m_result == TaskVerifyMessage::VERIFY_SUCCESS);

	delete task; task = Q_NULLPTR;

	/* Test with actual sender but invalid hash. */
	task = new (::std::nothrow) TaskVerifyMessage(
	    AcntId(m_sender.userName, m_testing), tamperedMessage.raw());
	QVERIFY(task != Q_NULLPTR);
	task->setAutoDelete(false);

	task->run();

	/* Local hash check should fail. */
	QVERIFY(task->m_result == TaskVerifyMessage::VERIFY_ISDS_ERR);

	delete task; task = Q_NULLPTR;
}

void TestTaskVerifyMessage::authenticateMessage(void)
{
	Isds::Message message, delInfo, tamperedMessage;
	QVERIFY(message.isNull());
	QVERIFY(delInfo.isNull());

	message = Isds::messageFromFile(msgPath, Isds::LT_MESSAGE);
	QVERIFY(!message.isNull());
	QVERIFY(!message.envelope().isNull());
	QVERIFY(!message.envelope().dmHash().isNull());

	delInfo = Isds::messageFromFile(delInfoPath, Isds::LT_DELIVERY);
	QVERIFY(!delInfo.isNull());
	QVERIFY(!delInfo.envelope().isNull());
	QVERIFY(!delInfo.envelope().dmHash().isNull());

	tamperedMessage = Isds::messageFromFile(tamperedMsgPath, Isds::LT_MESSAGE);
	QVERIFY(!tamperedMessage.isNull());
	QVERIFY(!tamperedMessage.envelope().isNull());
	QVERIFY(!tamperedMessage.envelope().dmHash().isNull());

	QVERIFY(!message.raw().isEmpty());
	QVERIFY(!delInfo.raw().isEmpty());
	QVERIFY(!tamperedMessage.raw().isEmpty());

	const QString transactId("authTransactId");

	TaskAuthenticateMessage *task = Q_NULLPTR;

	/* Basic message as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    message.raw(), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Basic message as size dependent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    message.raw(),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Basic message as size VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    message.raw(), TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Delivery info as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    delInfo.raw(), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Delivery info as size depenedent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    delInfo.raw(),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Delivery info as VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    delInfo.raw(), TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Basic message as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    message.raw(), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Basic message as size dependent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    message.raw(),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Basic message as VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    message.raw(), TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Delivery info as size depenedent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    delInfo.raw(), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Delivery info as size depenedent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    delInfo.raw(),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Sender. Delivery info as VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    delInfo.raw(), TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_SUCCESS);

		delete task; task = Q_NULLPTR;
	}

	/* Tampered message. */

	/* Tampered basic message as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    tamperedMessage.raw(), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* Tampered basic message as size dependent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    tamperedMessage.raw(),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* Tampered basic message as size VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_third.userName, m_testing), transactId,
		    tamperedMessage.raw(), TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* Invalid data. */

	QByteArray badRaw(delInfo.raw());
	badRaw[0] = ~badRaw[0];

	/* Invalid delivery info as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    badRaw, TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* Invalid delivery info as size depenedent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    badRaw, TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* Invalid delivery info as VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    badRaw, TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_NOT_EQUAL);

		delete task; task = Q_NULLPTR;
	}

	/* '\0' as basic. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    QByteArray(1, '\0'), TaskAuthenticateMessage::MSG_BASIC);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_ISDS_ERROR);

		delete task; task = Q_NULLPTR;
	}

	/* '\0' as size depenedent. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    QByteArray(1, '\0'),
		    TaskAuthenticateMessage::MSG_VODZ_SIZE_DEPENDENT);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_ISDS_ERROR);

		delete task; task = Q_NULLPTR;
	}

	/* '\0' as VODZ. */
	{
		task = new (::std::nothrow) TaskAuthenticateMessage(
		    AcntId(m_sender.userName, m_testing), transactId,
		    QByteArray(1, '\0'),
		    TaskAuthenticateMessage::MSG_VODZ);
		QVERIFY(task != Q_NULLPTR);
		task->setAutoDelete(false);

		task->run();

		QVERIFY(task->m_result == TaskAuthenticateMessage::AUTH_ISDS_ERROR);

		delete task; task = Q_NULLPTR;
	}
}

void TestTaskVerifyMessage::loadCredentials(LoginCredentials &cred, int line)
{
	bool ret;

	/* Load credentials. */
	ret = cred.loadLoginCredentials(m_credFName, line);
	if (!ret) {
		QSKIP("Failed to load login credentials. Skipping remaining tests.");
	}
	QVERIFY(ret);
	QVERIFY(!cred.userName.isEmpty());
	QVERIFY(!cred.pwd.isEmpty());

	/* Log into ISDS. */
	Isds::Session *ctx =
	    GlobInstcs::isdsSessionsPtr->session(cred.userName);
	if (!GlobInstcs::isdsSessionsPtr->holdsSession(cred.userName)) {
		QVERIFY(ctx == Q_NULLPTR);
		ctx = GlobInstcs::isdsSessionsPtr->createCleanSession(
		    cred.userName,
		    PrefsSpecific::isdsDownloadTimeoutMs(*GlobInstcs::prefsPtr));
	}
	if (ctx == Q_NULLPTR) {
		QSKIP("Cannot obtain communication context.");
	}
	QVERIFY(ctx != Q_NULLPTR);
	Isds::Error err = Isds::Login::loginUserName(ctx, cred.userName,
	    cred.pwd, m_testing);
	if (err.code() != Isds::Type::ERR_SUCCESS) {
		QSKIP("Error connecting into ISDS.");
	}
	QVERIFY(err.code() == Isds::Type::ERR_SUCCESS);
}

QObject *newTestTaskVerifyMessage(void)
{
	return new (::std::nothrow) TestTaskVerifyMessage();
}

//QTEST_MAIN(TestTaskVerifyMessage)
#include "test_task_verify_message.moc"
