summaryrefslogtreecommitdiffstats
path: root/tests/manual/gds/tst_gds.cpp
blob: 9e572382148fa1d92c1865689b10fdd65293537e (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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt OPC UA module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt 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 http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtOpcUa/QOpcUaProvider>
#include <QtOpcUa/QOpcUaGdsClient>
#include <QtOpcUa/QOpcUaApplicationIdentity>
#include <QtOpcUa/QOpcUaPkiConfiguration>
#include <QtOpcUa/QOpcUaAuthenticationInformation>
#include <QtOpcUa/QOpcUaEndpointDescription>
#include <QtOpcUa/QOpcUaApplicationRecordDataType>
#include <QtOpcUa/QOpcUaClient>
#include <QtOpcUa/QOpcUaX509DistinguishedName>

#include <QtCore/QCoreApplication>
#include <QtCore/QScopedPointer>
#include <QHostInfo>

#include <QtTest/QSignalSpy>
#include <QtTest/QtTest>

#define defineDataMethod(name) void name()\
{\
    QTest::addColumn<QString>("backend");\
    for (auto backend : m_backends) {\
        const QString rowName = QString("%1").arg(backend); \
        QTest::newRow(rowName.toLatin1().constData()) << backend ; \
        QVERIFY(!backend.isEmpty()); \
    }\
}

static QOpcUaPkiConfiguration getPkiConfig()
{
    QOpcUaPkiConfiguration pkiConfig;
    const QString pkiDir = QCoreApplication::applicationDirPath() + "/pki";

    pkiConfig.setClientCertificateFile(pkiDir + "/own/certs/application.der");
    pkiConfig.setPrivateKeyFile(pkiDir + "/own/private/application.pem");
    pkiConfig.setTrustListDirectory(pkiDir + "/trusted/certs");
    pkiConfig.setRevocationListDirectory(pkiDir + "/trusted/crl");
    pkiConfig.setIssuerListDirectory(pkiDir + "/issuers/certs");
    pkiConfig.setIssuerRevocationListDirectory(pkiDir + "/issuers/crl");
    return pkiConfig;
}

static QOpcUaApplicationIdentity getAppIdentity()
{
    QOpcUaApplicationIdentity identity;

    const QString applicationUri = QStringLiteral("urn:%1:%2:%3")
            .arg(QHostInfo::localHostName())
            .arg(QCoreApplication::organizationName())
            .arg(QCoreApplication::applicationName());
    const QString productUri = QStringLiteral("urn:%1:%2")
            .arg(QCoreApplication::organizationName())
            .arg(QCoreApplication::applicationName());

    identity.setProductUri(productUri);
    identity.setApplicationUri(applicationUri);
    identity.setApplicationName(QCoreApplication::applicationName());
    identity.setApplicationType(QOpcUaApplicationDescription::Client);
    return identity;
}

static bool removeSettingsFile()
{
    QSettings settings;
    QFile file(settings.fileName());
    if (file.exists())
        return file.remove();
    return true;
}

static void provideCredentials(QOpcUaAuthenticationInformation &authInfo)
{
    qDebug() << "Authentication credentials provided";
    authInfo.setUsernameAuthentication("root", "secret");
}

static void commonGdsClientSetup(QOpcUaGdsClient &gc, const QString &backend, const QOpcUaEndpointDescription endpoint)
{
    QObject::connect(&gc, &QOpcUaGdsClient::authenticationRequired, provideCredentials);

    gc.setBackend(backend);
    gc.setEndpoint(endpoint);
    gc.setApplicationIdentity(getAppIdentity());
    gc.setPkiConfiguration(getPkiConfig());

    QOpcUaApplicationRecordDataType ar = gc.applicationRecord();
    ar.setApplicationNames(QVector<QOpcUaLocalizedText>{QOpcUaLocalizedText("en",  gc.applicationIdentity().applicationName())});
    ar.setApplicationType(gc.applicationIdentity().applicationType());
    ar.setApplicationUri(gc.applicationIdentity().applicationUri());
    ar.setProductUri(gc.applicationIdentity().productUri());
    ar.setDiscoveryUrls(QVector<QString>{QLatin1String("opc.tcp://localhost")});
    gc.setApplicationRecord(ar);

    QOpcUaX509DistinguishedName dn;
    dn.setEntry(QOpcUaX509DistinguishedName::Type::CountryName, QLatin1String("DE"));
    dn.setEntry(QOpcUaX509DistinguishedName::Type::LocalityName, QLatin1String("Berlin"));
    dn.setEntry(QOpcUaX509DistinguishedName::Type::StateOrProvinceName, QLatin1String("Berlin"));
    dn.setEntry(QOpcUaX509DistinguishedName::Type::OrganizationName, QLatin1String("The Qt Company"));
    gc.setCertificateSigningRequestPresets(dn, QLatin1String("foo.com"));
}

// The tests have are depending on each other and have to be executed in order.

class Tst_QOpcUaGds: public QObject
{
    Q_OBJECT

public:
    Tst_QOpcUaGds();

private slots:
    void initTestCase();
    void cleanupTestCase();

    defineDataMethod(registerApplication_data)
    void registerApplication();
    defineDataMethod(reuseApplicationId_data)
    void reuseApplicationId();
    defineDataMethod(reuseRegisteredUri_data)
    void reuseRegisteredUri();
    defineDataMethod(serverForgotRegistration_data)
    void serverForgotRegistration();
private:
    QStringList m_backends;
    QOpcUaEndpointDescription m_endpoint;
};

Tst_QOpcUaGds::Tst_QOpcUaGds()
{
    m_backends = QOpcUaProvider::availableBackends();
}

void Tst_QOpcUaGds::initTestCase()
{
    QOpcUaEndpointDescription endpoint;
    QOpcUaProvider provider;

    QScopedPointer<QOpcUaClient> client(provider.createClient("open62541"));
    QVERIFY(!client.isNull());
    QSignalSpy endpointSpy(client.data(), &QOpcUaClient::endpointsRequestFinished);
    client->requestEndpoints(QUrl("opc.tcp://172.17.0.1:48060"));
    endpointSpy.wait(2000);
    QCOMPARE(endpointSpy.size(), 1);

    const QVector<QOpcUaEndpointDescription> desc = endpointSpy.at(0).at(0).value<QVector<QOpcUaEndpointDescription>>();
    QVERIFY(desc.size() > 0);

    for (const auto &i : qAsConst(desc)) {
        if (i.securityPolicy().endsWith("#Basic256Sha256")
            && i.securityMode() == QOpcUaEndpointDescription::MessageSecurityMode::SignAndEncrypt)
            m_endpoint = i;
    }

    QVERIFY(m_endpoint.securityPolicy().endsWith("#Basic256Sha256"));
}

void Tst_QOpcUaGds::registerApplication()
{
    QFETCH(QString, backend);
    if (backend == "open62541")
        QSKIP("Skipping open62541");

    QVERIFY(removeSettingsFile());

    QOpcUaGdsClient gc;
    commonGdsClientSetup(gc, backend, m_endpoint);

    QSignalSpy registeredSpy(&gc, &QOpcUaGdsClient::applicationRegistered);
    QSignalSpy certificateGroupsSpy(&gc, &QOpcUaGdsClient::certificateGroupsReceived);
    QSignalSpy certificateStatusSpy(&gc, &QOpcUaGdsClient::certificateUpdateRequired);
    QSignalSpy certificateUpdatedSpy(&gc, &QOpcUaGdsClient::certificateUpdated);
    QSignalSpy trustListUpdatedSpy(&gc, &QOpcUaGdsClient::trustListUpdated);

    gc.start();

    QVERIFY(certificateGroupsSpy.wait());
    QVERIFY(!certificateGroupsSpy.at(0).at(0).value<QStringList>().isEmpty());
    QVERIFY(registeredSpy.wait());

    if (certificateStatusSpy.isEmpty())
        certificateStatusSpy.wait();

    if (certificateUpdatedSpy.isEmpty())
        certificateUpdatedSpy.wait();

    if (trustListUpdatedSpy.isEmpty())
        trustListUpdatedSpy.wait();

    QVERIFY(!certificateStatusSpy.isEmpty());
    QVERIFY(!certificateUpdatedSpy.isEmpty());
    QVERIFY(!trustListUpdatedSpy.isEmpty());
}

void Tst_QOpcUaGds::reuseApplicationId()
{
    QFETCH(QString, backend);
    if (backend == "open62541")
        QSKIP("Skipping open62541");

    // Keep settings file in order to reuse the existing registration

    QOpcUaGdsClient gc;
    commonGdsClientSetup(gc, backend, m_endpoint);

    QSignalSpy registeredSpy(&gc, &QOpcUaGdsClient::applicationRegistered);
    QSignalSpy certificateGroupsSpy(&gc, &QOpcUaGdsClient::certificateGroupsReceived);

    gc.start();

    QVERIFY(certificateGroupsSpy.wait());
    QVERIFY(!certificateGroupsSpy.at(0).at(0).value<QStringList>().isEmpty());
    QVERIFY(registeredSpy.wait());
}

void Tst_QOpcUaGds::reuseRegisteredUri()
{
    // This test assumes that a registratin at the server is still present.
    // It will remove the information locally and has to reuse the
    // registration from the server.

    QFETCH(QString, backend);
    if (backend == "open62541")
        QSKIP("Skipping open62541");

    // Remove the registration data locally; the server will keep it.
    QSettings settings("Unknown Organization", "tst_gds");

    QString applicationId = settings.value(QLatin1String("gds/applicationId")).toString();
    settings.remove(QLatin1String("gds/applicationId"));
    settings.sync();

    QVERIFY(removeSettingsFile());

    QOpcUaGdsClient gc;
    commonGdsClientSetup(gc, backend, m_endpoint);

    QSignalSpy registeredSpy(&gc, &QOpcUaGdsClient::applicationRegistered);
    QSignalSpy certificateGroupsSpy(&gc, &QOpcUaGdsClient::certificateGroupsReceived);

    gc.start();

    QVERIFY(certificateGroupsSpy.wait());
    QVERIFY(!certificateGroupsSpy.at(0).at(0).value<QStringList>().isEmpty());
    QVERIFY(registeredSpy.wait());
    QVERIFY(gc.applicationId().size() > 10);
    if (!applicationId.isEmpty())
        QVERIFY(gc.applicationId() == applicationId);
}

void Tst_QOpcUaGds::serverForgotRegistration()
{
    QFETCH(QString, backend);
    if (backend == "open62541")
        QSKIP("Skipping open62541");

    // Setting an invalid application ID simulates a previous registration which has been
    // forgotten by the server
    QSettings settings("Unknown Organization", "tst_gds");
    settings.setValue(QLatin1String("gds/applicationId"), "ns=42;i=1111111");
    settings.sync();

    QOpcUaGdsClient gc;
    commonGdsClientSetup(gc, backend, m_endpoint);

    QSignalSpy registeredSpy(&gc, &QOpcUaGdsClient::applicationRegistered);
    QSignalSpy certificateGroupsSpy(&gc, &QOpcUaGdsClient::certificateGroupsReceived);

    gc.start();

    QVERIFY(certificateGroupsSpy.wait());
    QVERIFY(!certificateGroupsSpy.at(0).at(0).value<QStringList>().isEmpty());
    QVERIFY(registeredSpy.wait());
}

void Tst_QOpcUaGds::cleanupTestCase()
{
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTEST_SET_MAIN_SOURCE_PATH

    if (QOpcUaProvider::availableBackends().empty()) {
        qDebug("No OPCUA backends found, skipping tests.");
        return EXIT_SUCCESS;
    }

    Tst_QOpcUaGds tc;
    return QTest::qExec(&tc, argc, argv);
}

#include "tst_gds.moc"