// Unit tests for PluginPackage: the .fwspacm format, and the bookkeeping that // decides what an uninstall is allowed to delete. // // The archives are built here (both a stored and a deflated entry, so both // compression methods are exercised), every file operation runs in a temporary // directory, and the settings go to a temporary INI: no network, no real // plugin, nothing of the user's is touched. #include "plugin-package.h" #include #include #include #include #include #include #include #include #include namespace { // --- Building archives ----------------------------------------------------- void writeU16(QByteArray* out, quint16 value) { out->append(static_cast(value & 0xff)); out->append(static_cast((value >> 8) & 0xff)); } void writeU32(QByteArray* out, quint32 value) { out->append(static_cast(value & 0xff)); out->append(static_cast((value >> 8) & 0xff)); out->append(static_cast((value >> 16) & 0xff)); out->append(static_cast((value >> 24) & 0xff)); } // A minimal ZIP writer, so the reader is tested against bytes rather than // against a library that would agree with it by construction. `stored` writes // the payload uncompressed (method 0), otherwise a deflate stream is required // from the caller and written as-is (method 8). class ZipBuilder { public: void addFile(const QString& name, const QByteArray& payload, bool stored) { m_entries.append({name, payload, stored}); } // Adds a directory entry, which a reader has to skip rather than treat as a // file. void addDirectory(const QString& name) { m_entries.append({name, QByteArray(), true, true}); } QByteArray build() const { QByteArray out; QList offsets; for (const auto& entry : m_entries) { offsets.append(out.size()); const QByteArray name = entry.name.toUtf8(); const QByteArray payload = entry.directory ? QByteArray() : entry.payload; writeU32(&out, 0x04034b50); writeU16(&out, 20); // version needed writeU16(&out, 0); // flags writeU16(&out, entry.directory ? 0 : (entry.stored ? 0 : 8)); writeU16(&out, 0); // mod time writeU16(&out, 0); // mod date writeU32(&out, 0); // crc (not verified on read) writeU32(&out, static_cast(payload.size())); writeU32(&out, static_cast(entry.rawSize())); writeU16(&out, static_cast(name.size())); writeU16(&out, 0); // extra out.append(name); if (entry.stored || entry.directory) { out.append(payload); } else { out.append(entry.deflated); } } const int directoryOffset = out.size(); for (int i = 0; i < m_entries.size(); ++i) { const auto& entry = m_entries[i]; const QByteArray name = entry.name.toUtf8(); const QByteArray payload = entry.directory ? QByteArray() : entry.payload; const int compressedSize = entry.directory ? 0 : (entry.stored ? payload.size() : entry.deflated.size()); writeU32(&out, 0x02014b50); writeU16(&out, 20); // version made by writeU16(&out, 20); // version needed writeU16(&out, 0); // flags writeU16(&out, entry.directory ? 0 : (entry.stored ? 0 : 8)); writeU16(&out, 0); writeU16(&out, 0); writeU32(&out, 0); // crc writeU32(&out, static_cast(compressedSize)); writeU32(&out, static_cast(entry.directory ? 0 : payload.size())); writeU16(&out, static_cast(name.size())); writeU16(&out, 0); // extra writeU16(&out, 0); // comment writeU16(&out, 0); // disk writeU16(&out, 0); // internal attributes writeU32(&out, 0); // external attributes writeU32(&out, static_cast(offsets[i])); out.append(name); } const int directorySize = out.size() - directoryOffset; writeU32(&out, 0x06054b50); writeU16(&out, 0); writeU16(&out, 0); writeU16(&out, static_cast(m_entries.size())); writeU16(&out, static_cast(m_entries.size())); writeU32(&out, static_cast(directorySize)); writeU32(&out, static_cast(directoryOffset)); writeU16(&out, 0); // comment return out; } // A deflate stream for a payload, produced by zlib the same way a real ZIP // writer would. Raw deflate, not the zlib-wrapped stream compress2() emits: // a ZIP entry has no zlib header and no trailing checksum, which is why the // reader in zip-archive.cpp calls inflateInit2() with a negative window. static QByteArray rawDeflate(const QByteArray& payload) { z_stream stream{}; if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY) != Z_OK) { return {}; } stream.next_in = const_cast(reinterpret_cast(payload.constData())); stream.avail_in = static_cast(payload.size()); QByteArray out; char buffer[16384]; int status = Z_OK; do { stream.next_out = reinterpret_cast(buffer); stream.avail_out = sizeof(buffer); status = deflate(&stream, Z_FINISH); assert(status == Z_OK || status == Z_STREAM_END); out.append(buffer, static_cast(sizeof(buffer)) - static_cast(stream.avail_out)); } while (status != Z_STREAM_END); deflateEnd(&stream); return out; } private: struct Entry { QString name; QByteArray payload; bool stored = true; bool directory = false; QByteArray deflated; Entry() = default; Entry(QString entryName, QByteArray entryPayload, bool isStored) : name(std::move(entryName)), payload(std::move(entryPayload)), stored(isStored) { if (!stored) deflated = rawDeflate(payload); } Entry(QString entryName, QByteArray, bool, bool isDirectory) : name(std::move(entryName)), stored(true), directory(isDirectory) {} int rawSize() const { return static_cast(payload.size()); } }; QList m_entries; }; QByteArray sha256Of(const QByteArray& payload) { return QCryptographicHash::hash(payload, QCryptographicHash::Sha256).toHex(); } // Writes an archive and closes it, so the file is complete on disk before any // test reads it back. QString writeArchive(const QString& path, const ZipBuilder& zip) { QFile file(path); assert(file.open(QIODevice::WriteOnly)); file.write(zip.build()); file.close(); return path; } // A package with a manifest and a library, written to `path`. QString writePackage(const QString& path, const QByteArray& library, const QByteArray& manifest, bool deflated = true) { ZipBuilder zip; zip.addFile(QStringLiteral("plugin.json"), manifest, false); zip.addFile(QStringLiteral("libsample.so"), library, !deflated); return writeArchive(path, zip); } QByteArray manifestJson(const QByteArray& library, bool withChecksum = true) { QByteArray json = "{\"format\": 1, \"id\": \"sample\", \"name\": \"Sample\", " "\"kind\": \"provider\", \"version\": \"1.0.0\", " "\"library\": \"libsample.so\""; if (withChecksum) { json += ", \"sha256\": \"" + sha256Of(library) + "\""; } json += "}"; return json; } const QByteArray kLibrary = QByteArray("\x7f" "ELF-fake-shared-library-payload"); // --- Tests ----------------------------------------------------------------- // A well-formed package is read whole: manifest fields, library bytes, and the // name the library is written under. static void testPackageIsRead() { QTemporaryDir dir; const QString path = writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifestJson(kLibrary)); QString error; const PluginPackage::Contents contents = PluginPackage::read(path, &error); assert(error.isEmpty()); assert(contents.manifest.id == QStringLiteral("sample")); assert(contents.manifest.name == QStringLiteral("Sample")); assert(contents.manifest.version == QStringLiteral("1.0.0")); assert(contents.manifest.kind == QStringLiteral("provider")); assert(contents.library == kLibrary); assert(contents.libraryName == QStringLiteral("libsample.so")); } // A deflated entry and a stored one must give the same bytes back: the format // allows both, and a plugin author picks whichever their zip tool defaults to. static void testBothCompressionMethodsAreRead() { QTemporaryDir dir; QString error; const PluginPackage::Contents deflated = PluginPackage::read( writePackage(dir.path() + "/deflated.fwspacm", kLibrary, manifestJson(kLibrary), true), &error); assert(error.isEmpty()); assert(deflated.library == kLibrary); const PluginPackage::Contents stored = PluginPackage::read( writePackage(dir.path() + "/stored.fwspacm", kLibrary, manifestJson(kLibrary), false), &error); assert(error.isEmpty()); assert(stored.library == kLibrary); } // A library whose bytes do not match the announced checksum never reaches the // plugin directory: that check is the only guarantee about *which* code runs. static void testChecksumMismatchIsRefused() { QTemporaryDir dir; // The manifest announces the checksum of other bytes than the ones zipped. const QByteArray other = QByteArray("some other library"); QByteArray manifest = "{\"format\": 1, \"id\": \"sample\", " "\"library\": \"libsample.so\", \"sha256\": \"" + sha256Of(other) + "\"}"; QString error; const PluginPackage::Contents contents = PluginPackage::read( writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifest), &error); assert(contents.library.isEmpty()); assert(error.contains(QStringLiteral("Somme de contrôle"))); } // Without a checksum the package still installs: the manifest is free to omit // it, and refusing would make the format unusable for a local build. static void testChecksumIsOptional() { QTemporaryDir dir; QString error; const PluginPackage::Contents contents = PluginPackage::read( writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifestJson(kLibrary, false)), &error); assert(error.isEmpty()); assert(contents.library == kLibrary); } // Every way a package can be unusable must be refused with a reason, and never // half-installed. static void testInvalidPackagesAreRefused() { QTemporaryDir dir; QString error; // Not a ZIP at all. const QString plain = dir.path() + "/plain.fwspacm"; { QFile file(plain); assert(file.open(QIODevice::WriteOnly)); file.write("this is not an archive"); file.close(); } assert(PluginPackage::read(plain, &error).library.isEmpty()); assert(!error.isEmpty()); // A ZIP with no manifest: the library is right there, and it is still // refused, because a package without a manifest says nothing about what it // would install. { ZipBuilder zip; zip.addFile(QStringLiteral("libsample.so"), kLibrary, true); const QString path = writeArchive(dir.path() + "/nomanifest.fwspacm", zip); assert(PluginPackage::read(path, &error).library.isEmpty()); assert(error.contains(QStringLiteral("plugin.json"))); } // A manifest that is not JSON, and one that is JSON but not an object. assert(PluginPackage::read( writePackage(dir.path() + "/badjson.fwspacm", kLibrary, "{ not json"), &error).library.isEmpty()); assert(!error.isEmpty()); assert(PluginPackage::read( writePackage(dir.path() + "/array.fwspacm", kLibrary, "[]"), &error) .library.isEmpty()); assert(!error.isEmpty()); // A manifest of another version: read as-is would mean reading a package as // something it is not. assert(PluginPackage::read( writePackage(dir.path() + "/format2.fwspacm", kLibrary, "{\"format\": 2, \"id\": \"sample\", " "\"library\": \"libsample.so\"}"), &error).library.isEmpty()); assert(error.contains(QStringLiteral("Format de paquet"))); // A manifest with no id. assert(PluginPackage::read( writePackage(dir.path() + "/noid.fwspacm", kLibrary, "{\"format\": 1, \"library\": \"libsample.so\"}"), &error).library.isEmpty()); assert(error.contains(QStringLiteral("id"))); // An id holding a slash would need quoting as a settings key. assert(PluginPackage::read( writePackage(dir.path() + "/badid.fwspacm", kLibrary, "{\"format\": 1, \"id\": \"a/b\", " "\"library\": \"libsample.so\"}"), &error).library.isEmpty()); assert(error.contains(QStringLiteral("Identifiant refusé"))); // A manifest naming a library the archive does not contain. assert(PluginPackage::read( writePackage(dir.path() + "/nolib.fwspacm", kLibrary, "{\"format\": 1, \"id\": \"sample\", " "\"library\": \"libabsent.so\"}"), &error).library.isEmpty()); assert(!error.isEmpty()); // A manifest naming a path instead of a file name: the package would be // writing outside the directory it is installed into. assert(PluginPackage::read( writePackage(dir.path() + "/escape.fwspacm", kLibrary, "{\"format\": 1, \"id\": \"sample\", " "\"library\": \"../libsample.so\"}"), &error).library.isEmpty()); assert(!error.isEmpty()); // An archive with no shared library at all. The manifest names none, so the // reader has to find it by suffix and finds nothing. { ZipBuilder zip; zip.addFile(QStringLiteral("plugin.json"), "{\"format\": 1, \"id\": \"sample\", \"name\": \"Sample\"}", false); zip.addFile(QStringLiteral("readme.txt"), "nothing to load", true); const QString path = writeArchive(dir.path() + "/nolibrary.fwspacm", zip); assert(PluginPackage::read(path, &error).library.isEmpty()); assert(error.contains(QStringLiteral("bibliothèque partagée"))); } // An empty library is refused: writing a zero-byte file into the scanned // directory would fail later, at load time, with a worse message. assert(PluginPackage::read( writePackage(dir.path() + "/emptylib.fwspacm", QByteArray(), manifestJson(QByteArray(), false)), &error).library.isEmpty()); assert(error.contains(QStringLiteral("vide"))); } // With no "library" in the manifest, the archive's single shared library is // the one to install; with several, the package has to say which, because // picking one silently is how the wrong file gets installed. static void testLibraryIsFoundBySuffix() { ZipArchive archive; QString error; assert(archive.openData( [] { ZipBuilder zip; zip.addFile(QStringLiteral("readme.txt"), "docs", true); zip.addFile(QStringLiteral("libonly.so"), kLibrary, true); return zip.build(); }(), &error)); assert(error.isEmpty()); PluginPackage::Manifest manifest; manifest.id = QStringLiteral("sample"); const QString found = PluginPackage::targetFileName(manifest, archive, &error); assert(error.isEmpty()); assert(found == QStringLiteral("libonly.so")); // Two candidates: refused rather than guessed. ZipArchive ambiguous; assert(ambiguous.openData( [] { ZipBuilder zip; zip.addFile(QStringLiteral("libone.so"), kLibrary, true); zip.addFile(QStringLiteral("libtwo.so"), kLibrary, true); return zip.build(); }(), &error)); assert(PluginPackage::targetFileName(manifest, ambiguous, &error).isEmpty()); assert(error.contains(QStringLiteral("library"))); // A directory entry is not a library, whatever it is called. ZipArchive onlyDir; assert(onlyDir.openData( [] { ZipBuilder zip; zip.addDirectory(QStringLiteral("libdir.so/")); return zip.build(); }(), &error)); assert(PluginPackage::targetFileName(manifest, onlyDir, &error).isEmpty()); assert(!error.isEmpty()); } // Entry names that would escape the directory they are written to. static void testUnsafeEntryNamesAreRefused() { assert(ZipArchive::isSafeEntryName(QStringLiteral("libsample.so"))); assert(ZipArchive::isSafeEntryName(QStringLiteral("subdir/libsample.so"))); assert(!ZipArchive::isSafeEntryName(QString())); assert(!ZipArchive::isSafeEntryName(QStringLiteral("/etc/passwd"))); assert(!ZipArchive::isSafeEntryName(QStringLiteral("../escape.so"))); assert(!ZipArchive::isSafeEntryName(QStringLiteral("subdir/../../escape.so"))); assert(!ZipArchive::isSafeEntryName(QStringLiteral("\\windows\\system32"))); assert(!ZipArchive::isSafeEntryName(QStringLiteral("C:/windows"))); } // Installing writes the library in the install directory and records it; // removing takes back exactly that file, and refuses anything else. static void testInstallAndRemove() { QTemporaryDir dir; PluginPackage packages; const QString pluginsDir = dir.path() + "/plugins"; packages.setInstallDirectory(pluginsDir); const QString path = writePackage(dir.path() + "/sample.fwspacm", kLibrary, manifestJson(kLibrary)); QString id; bool success = false; QObject::connect(&packages, &PluginPackage::installFinished, &packages, [&](const QString& installedId, bool ok, const QString&) { id = installedId; success = ok; }); // Nothing installed yet: a removal must fail rather than delete anything. // A separate flag, since removeFinished is the signal a removal reports on. bool removed = true; QObject::connect(&packages, &PluginPackage::removeFinished, &packages, [&](const QString&, bool ok, const QString&) { removed = ok; }); packages.remove(QStringLiteral("sample")); assert(!removed); packages.install(path); assert(success); assert(id == QStringLiteral("sample")); assert(packages.isInstalled(QStringLiteral("sample"))); const QString written = pluginsDir + "/libsample.so"; assert(packages.installedPath(QStringLiteral("sample")) == written); QFile file(written); assert(file.open(QIODevice::ReadOnly)); assert(file.readAll() == kLibrary); file.close(); // The id shows up in the list the page renders. assert(packages.installedIds() == QStringList{QStringLiteral("sample")}); success = false; removed = false; packages.remove(QStringLiteral("sample")); assert(removed); assert(!QFile::exists(written)); assert(!packages.isInstalled(QStringLiteral("sample"))); assert(packages.installedIds().isEmpty()); } // A file the user copied in by hand is not the installer's to delete. static void testUninstallOnlyRemovesWhatItInstalled() { QTemporaryDir dir; PluginPackage packages; packages.setInstallDirectory(dir.path() + "/plugins"); assert(QDir().mkpath(dir.path() + "/plugins")); // A library present in the directory, with no install recorded for it. const QString handPlaced = dir.path() + "/plugins/libmanual.so"; QFile manual(handPlaced); assert(manual.open(QIODevice::WriteOnly)); manual.write(kLibrary); manual.close(); bool success = true; QObject::connect(&packages, &PluginPackage::removeFinished, &packages, [&](const QString&, bool ok, const QString&) { success = ok; }); packages.remove(QStringLiteral("manual")); assert(!success); assert(QFile::exists(handPlaced)); } // A file deleted behind the installer's back is not installed any more, even // though the setting still names it: the state follows the disk. static void testMissingFileCountsAsNotInstalled() { QTemporaryDir dir; PluginPackage packages; packages.setInstallDirectory(dir.path() + "/plugins"); QSettings settings; settings.setValue("packages/installed/gone", dir.path() + "/plugins/libgone.so"); settings.sync(); assert(!packages.isInstalled(QStringLiteral("gone"))); assert(packages.installedPath(QStringLiteral("gone")).isEmpty()); // A recorded but missing library is not listed either, so the page never // offers to remove something that is not there. assert(!packages.installedIds().contains(QStringLiteral("gone"))); } // Reinstalling a package overwrites the previous library, in place. static void testReinstallOverwrites() { QTemporaryDir dir; PluginPackage packages; packages.setInstallDirectory(dir.path() + "/plugins"); bool success = false; QObject::connect(&packages, &PluginPackage::installFinished, &packages, [&](const QString&, bool ok, const QString&) { success = ok; }); packages.install(writePackage(dir.path() + "/v1.fwspacm", kLibrary, manifestJson(kLibrary))); assert(success); const QByteArray newer = kLibrary + "-v2"; packages.install(writePackage(dir.path() + "/v2.fwspacm", newer, manifestJson(newer))); assert(success); QFile file(dir.path() + "/plugins/libsample.so"); assert(file.open(QIODevice::ReadOnly)); assert(file.readAll() == newer); } // A file that is not a package is refused before it is even opened. static void testNonPackageIsRefused() { assert(PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.fwspacm"))); assert(PluginPackage::isPackagePath(QStringLiteral("/tmp/SAMPLE.FWSPACM"))); assert(!PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.fwspacm.zip"))); assert(!PluginPackage::isPackagePath(QStringLiteral("/tmp/sample.so"))); assert(!PluginPackage::isPackagePath(QString())); QTemporaryDir dir; PluginPackage packages; packages.setInstallDirectory(dir.path() + "/plugins"); bool success = true; QString message; QObject::connect(&packages, &PluginPackage::installFinished, &packages, [&](const QString&, bool ok, const QString& detail) { success = ok; message = detail; }); // Written under a .fwspacm name, so the extension is not what refuses it: // the content is. const QString path = writePackage(dir.path() + "/bogus.fwspacm", kLibrary, QByteArray("{\"format\": 9, \"id\": \"x\"}")); packages.install(path); assert(!success); assert(!message.isEmpty()); assert(!packages.installedIds().contains(QStringLiteral("x"))); } } // namespace int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); app.setOrganizationName(QStringLiteral("PacManagerTests")); app.setApplicationName(QStringLiteral("plugin-package-test")); // Settings and the install directory go to a temporary INI, so the recorded // installs of these tests never reach the user's real configuration. QTemporaryDir settingsDir; QSettings::setDefaultFormat(QSettings::IniFormat); QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsDir.path()); testPackageIsRead(); testBothCompressionMethodsAreRead(); testChecksumMismatchIsRefused(); testChecksumIsOptional(); testInvalidPackagesAreRefused(); testLibraryIsFoundBySuffix(); testUnsafeEntryNamesAreRefused(); testInstallAndRemove(); testUninstallOnlyRemovesWhatItInstalled(); testMissingFileCountsAsNotInstalled(); testReinstallOverwrites(); testNonPackageIsRefused(); QTextStream(stdout) << "All plugin-package tests passed." << Qt::endl; return 0; }