summaryrefslogtreecommitdiffstats
path: root/tests/packager-tool/tst_packager-tool.cpp
blob: 0b6949beb6cdb0a7ab17da1848934b0e5326a1cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Luxoft Application Manager.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest>
#include <QCoreApplication>

#include "global.h"
#include "installationlocation.h"
#include "applicationmanager.h"
#include "application.h"
#include "qtyaml.h"
#include "exception.h"
#include "packagingjob.h"
#include "applicationinstaller.h"
#include "qmlinprocessruntime.h"
#include "runtimefactory.h"
#include "utilities.h"

#include "../error-checking.h"

QT_USE_NAMESPACE_AM

static int spyTimeout = 5000; // shorthand for specifying QSignalSpy timeouts

class tst_PackagerTool : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void initTestCase();
    void cleanup();

    void test();
    void brokenMetadata_data();
    void brokenMetadata();
    void iconFileName();

private:
    QString pathTo(const char *file)
    {
        return QDir(m_workDir.path()).absoluteFilePath(QLatin1String(file));
    }

    bool createInfoYaml(QTemporaryDir &tmp, const QString &changeField = QString(), const QVariant &toValue = QVariant());
    bool createIconPng(QTemporaryDir &tmp);
    bool createCode(QTemporaryDir &tmp);
    void createDummyFile(QTemporaryDir &tmp, const QString &fileName, const char *data);

    void installPackage(const QString &filePath);

    ApplicationInstaller *m_ai = nullptr;
    QTemporaryDir m_workDir;

    QString m_devPassword;
    QString m_devCertificate;
    QString m_storePassword;
    QString m_storeCertificate;
    QStringList m_caFiles;
    QString m_hardwareId;
};

void tst_PackagerTool::initTestCase()
{
    if (!QDir(qL1S(AM_TESTDATA_DIR "/packages")).exists())
        QSKIP("No test packages available in the data/ directory");

    spyTimeout *= timeoutFactor();

    QVERIFY(m_workDir.isValid());

    QVERIFY(QDir::root().mkpath(pathTo("manifests")));
    QVERIFY(QDir::root().mkpath(pathTo("image-mounts")));
    QVERIFY(QDir::root().mkpath(pathTo("internal-0")));
    QVERIFY(QDir::root().mkpath(pathTo("documents-0")));

    m_hardwareId = "foobar";

    QVariantMap internalLocation {
        { "id", "internal-0" },
        { "installationPath", pathTo("internal-0") },
        { "documentPath", pathTo("documents-0") },
    };
    QVector<InstallationLocation> locations = InstallationLocation::parseInstallationLocations({ internalLocation }, m_hardwareId);

    QString errorString;
    m_ai = ApplicationInstaller::createInstance(locations, pathTo("manifests"), pathTo("image-mounts"), m_hardwareId, &errorString);
    QVERIFY2(m_ai, qPrintable(errorString));

    QVERIFY(ApplicationManager::createInstance(true));


    // crypto stuff - we need to load the root CA and developer CA certificates

    QFile devcaFile(qL1S(AM_TESTDATA_DIR "certificates/devca.crt"));
    QFile caFile(qL1S(AM_TESTDATA_DIR "certificates/ca.crt"));
    QVERIFY2(devcaFile.open(QIODevice::ReadOnly), qPrintable(devcaFile.errorString()));
    QVERIFY2(caFile.open(QIODevice::ReadOnly), qPrintable(devcaFile.errorString()));

    QList<QByteArray> chainOfTrust;
    chainOfTrust << devcaFile.readAll() << caFile.readAll();
    QVERIFY(!chainOfTrust.at(0).isEmpty());
    QVERIFY(!chainOfTrust.at(1).isEmpty());
    m_ai->setCACertificates(chainOfTrust);

    m_caFiles << devcaFile.fileName() << caFile.fileName();

    m_devPassword = qSL("password");
    m_devCertificate = qL1S(AM_TESTDATA_DIR "certificates/dev1.p12");
    m_storePassword = qSL("password");
    m_storeCertificate = qL1S(AM_TESTDATA_DIR "certificates/store.p12");

    RuntimeFactory::instance()->registerRuntime(new QmlInProcessRuntimeManager(qSL("qml")));
}

void tst_PackagerTool::cleanup()
{
    recursiveOperation(pathTo("manifests"), safeRemove);
    recursiveOperation(pathTo("image-mounts"), safeRemove);
    recursiveOperation(pathTo("internal-0"), safeRemove);
    recursiveOperation(pathTo("documents-0"), safeRemove);

    QDir dir(m_workDir.path());
    QStringList fileNames = dir.entryList(QDir::Files);
    for (auto fileName : fileNames)
        dir.remove(fileName);
}

// exceptions are nice -- just not for unit testing :)
static bool packagerCheck(PackagingJob *p, QString &errorString)
{
    bool result = false;
    try {
        p->execute();
        errorString.clear();
        result = (p->resultCode() == 0);
        if (!result)
            errorString = p->output();
    } catch (const Exception &e) { \
        errorString = e.errorString();
    }
    delete p;
    return result;
}

void tst_PackagerTool::test()
{
    QTemporaryDir tmp;
    QString errorString;

    // no valid destination
    QVERIFY(!packagerCheck(PackagingJob::create(pathTo("test.appkg"), pathTo("test.appkg")), errorString));
    QVERIFY2(errorString.contains(qL1S("not a directory")), qPrintable(errorString));

    // no valid info.yaml
    QVERIFY(!packagerCheck(PackagingJob::create(pathTo("test.appkg"), tmp.path()), errorString));
    QVERIFY2(errorString.contains(qL1S("could not open file for reading")), qPrintable(errorString));

    // add an info.yaml file
    createInfoYaml(tmp);

    // no icon
    QVERIFY(!packagerCheck(PackagingJob::create(pathTo("test.appkg"), tmp.path()), errorString));
    QVERIFY2(errorString.contains(qL1S("missing the file referenced by the 'icon' field")), qPrintable(errorString));

    // add an icon
    createIconPng(tmp);

    // no valid code
    QVERIFY(!packagerCheck(PackagingJob::create(pathTo("test.appkg"), tmp.path()), errorString));
    QVERIFY2(errorString.contains(qL1S("missing the file referenced by the 'code' field")), qPrintable(errorString));

    // add a code file
    createCode(tmp);

    // invalid destination
    QVERIFY(!packagerCheck(PackagingJob::create(tmp.path(), tmp.path()), errorString));
    QVERIFY2(errorString.contains(qL1S("could not create package file")), qPrintable(errorString));

    // now everything is correct - try again
    QVERIFY2(packagerCheck(PackagingJob::create(pathTo("test.appkg"), tmp.path()), errorString), qPrintable(errorString));

    // invalid source package
    QVERIFY(!packagerCheck(PackagingJob::developerSign(
                               pathTo("no-such-file"),
                               pathTo("test.dev-signed.appkg"),
                               m_devCertificate,
                               m_devPassword), errorString));
    QVERIFY2(errorString.contains(qL1S("does not exist")), qPrintable(errorString));

    // invalid destination package
    QVERIFY(!packagerCheck(PackagingJob::developerSign(
                               pathTo("test.appkg"),
                               pathTo("."),
                               m_devCertificate,
                               m_devPassword), errorString));
    QVERIFY2(errorString.contains(qL1S("could not create package file")), qPrintable(errorString));


    // invalid dev key
    QVERIFY(!packagerCheck(PackagingJob::developerSign(
                               pathTo("test.appkg"),
                               pathTo("test.dev-signed.appkg"),
                               m_devCertificate,
                               qSL("wrong-password")), errorString));
    QVERIFY2(errorString.contains(qL1S("could not create signature")), qPrintable(errorString));

    // invalid store key
    QVERIFY(!packagerCheck(PackagingJob::storeSign(
                               pathTo("test.appkg"),
                               pathTo("test.store-signed.appkg"),
                               m_storeCertificate,
                               qSL("wrong-password"),
                               m_hardwareId), errorString));
    QVERIFY2(errorString.contains(qL1S("could not create signature")), qPrintable(errorString));

    // sign
    QVERIFY2(packagerCheck(PackagingJob::developerSign(
                               pathTo("test.appkg"),
                               pathTo("test.dev-signed.appkg"),
                               m_devCertificate,
                               m_devPassword), errorString), qPrintable(errorString));

    QVERIFY2(packagerCheck(PackagingJob::storeSign(
                               pathTo("test.appkg"),
                               pathTo("test.store-signed.appkg"),
                               m_storeCertificate,
                               m_storePassword,
                               m_hardwareId), errorString), qPrintable(errorString));

    // verify
    QVERIFY2(packagerCheck(PackagingJob::developerVerify(
                               pathTo("test.dev-signed.appkg"),
                               m_caFiles), errorString), qPrintable(errorString));

    QVERIFY2(packagerCheck(PackagingJob::storeVerify(
                               pathTo("test.store-signed.appkg"),
                               m_caFiles,
                               m_hardwareId), errorString), qPrintable(errorString));

    // now that we have it, see if the package actually installs correctly

    installPackage(pathTo("test.dev-signed.appkg"));

    QDir checkDir(pathTo("internal-0"));
    QVERIFY(checkDir.cd(qSL("com.pelagicore.test")));

    for (const QString &file : { qSL("info.yaml"), qSL("icon.png"), qSL("test.qml") }) {
        QVERIFY(checkDir.exists(file));
        QFile src(QDir(tmp.path()).absoluteFilePath(file));
        QVERIFY(src.open(QFile::ReadOnly));
        QFile dst(checkDir.absoluteFilePath(file));
        QVERIFY(dst.open(QFile::ReadOnly));
        QCOMPARE(src.readAll(), dst.readAll());
    }
}

void tst_PackagerTool::brokenMetadata_data()
{
    QTest::addColumn<QString>("yamlField");
    QTest::addColumn<QVariant>("yamlValue");
    QTest::addColumn<QString>("errorString");

    QTest::newRow("missing-name")       << "name"    << QVariant("") << "~.*the 'name' field must not be empty";
    QTest::newRow("missing-runtime")    << "runtime" << QVariant("") << "~.*the 'runtimeName' field must not be empty";
    QTest::newRow("missing-identifier") << "id"      << QVariant("") << "~.*the identifier \\(\\) is not a valid application-id: must not be empty";
    QTest::newRow("missing-code")       << "code"    << QVariant("") << "~.*the 'code' field must not be empty";
}

void tst_PackagerTool::brokenMetadata()
{
    QFETCH(QString, yamlField);
    QFETCH(QVariant, yamlValue);
    QFETCH(QString, errorString);

    QTemporaryDir tmp;

    createCode(tmp);
    createIconPng(tmp);
    createInfoYaml(tmp, yamlField, yamlValue);

    // check if packaging actually fails with the expected error

    QString error;
    QVERIFY(!packagerCheck(PackagingJob::create(pathTo("test.appkg"), tmp.path()), error));
    AM_CHECK_ERRORSTRING(error, errorString);
}

/*
    Specify an icon whose name is different from "icon.png".
    Packaging should work fine
 */
void tst_PackagerTool::iconFileName()
{
    QTemporaryDir tmp;
    QString errorString;

    createInfoYaml(tmp, "icon", "foo.bar");
    createCode(tmp);
    createDummyFile(tmp, "foo.bar", "this-is-a-dummy-icon-file");

    QVERIFY2(packagerCheck(PackagingJob::create(pathTo("test-foobar-icon.appkg"), tmp.path()), errorString),
            qPrintable(errorString));

    // see if the package installs correctly

    m_ai->setAllowInstallationOfUnsignedPackages(true);
    installPackage(pathTo("test-foobar-icon.appkg"));
    m_ai->setAllowInstallationOfUnsignedPackages(false);

    QDir checkDir(pathTo("internal-0"));
    QVERIFY(checkDir.cd(qSL("com.pelagicore.test")));

    for (const QString &file : { qSL("info.yaml"), qSL("foo.bar"), qSL("test.qml") }) {
        QVERIFY(checkDir.exists(file));
        QFile src(QDir(tmp.path()).absoluteFilePath(file));
        QVERIFY(src.open(QFile::ReadOnly));
        QFile dst(checkDir.absoluteFilePath(file));
        QVERIFY(dst.open(QFile::ReadOnly));
        QCOMPARE(src.readAll(), dst.readAll());
    }
}


bool tst_PackagerTool::createInfoYaml(QTemporaryDir &tmp, const QString &changeField, const QVariant &toValue)
{
    QByteArray yaml =
            "formatVersion: 1\n"
            "formatType: am-application\n"
            "---\n"
            "id: com.pelagicore.test\n"
            "name: { en_US: 'test' }\n"
            "icon: icon.png\n"
            "code: test.qml\n"
            "runtime: qml\n";

    if (!changeField.isEmpty()) {
        QVector<QVariant> docs = QtYaml::variantDocumentsFromYaml(yaml);
        QVariantMap map = docs.at(1).toMap();
        map[changeField] = toValue;
        yaml = QtYaml::yamlFromVariantDocuments({ docs.at(0), map });
    }

    QFile infoYaml(QDir(tmp.path()).absoluteFilePath(qSL("info.yaml")));
    return infoYaml.open(QFile::WriteOnly) && infoYaml.write(yaml) == yaml.size();
}

bool tst_PackagerTool::createIconPng(QTemporaryDir &tmp)
{
    QFile iconPng(QDir(tmp.path()).absoluteFilePath(qSL("icon.png")));
    return iconPng.open(QFile::WriteOnly) && iconPng.write("\x89PNG") == 4;
}

bool tst_PackagerTool::createCode(QTemporaryDir &tmp)
{
    QFile code(QDir(tmp.path()).absoluteFilePath(qSL("test.qml")));
    return code.open(QFile::WriteOnly) && code.write("// test") == 7LL;
}

void tst_PackagerTool::createDummyFile(QTemporaryDir &tmp, const QString &fileName, const char *data)
{
    QFile code(QDir(tmp.path()).absoluteFilePath(fileName));
    QVERIFY(code.open(QFile::WriteOnly));

    auto written = code.write(data);

    QCOMPARE(written, (qint64)strlen(data));
}

void tst_PackagerTool::installPackage(const QString &filePath)
{
    QSignalSpy finishedSpy(m_ai, &ApplicationInstaller::taskFinished);

    m_ai->setDevelopmentMode(true); // allow packages without store signature

    QString taskId = m_ai->startPackageInstallation(qSL("internal-0"),
            QUrl::fromLocalFile(filePath));
    m_ai->acknowledgePackageInstallation(taskId);

    QVERIFY(finishedSpy.wait(2 * spyTimeout));
    QCOMPARE(finishedSpy.first()[0].toString(), taskId);

    m_ai->setDevelopmentMode(false);
}

QTEST_GUILESS_MAIN(tst_PackagerTool)

#include "tst_packager-tool.moc"