Secure Connections¶
The QGroundControl.SecureConnections module lets a plugin talk to an external server and, over TLS, present a client certificate the operator imported into AMC. Its three clients, for HTTPS, gRPC and MQTT, connect the same way: a url, an optional certificate, full TLS verification, and a state you can show to the operator.
Requires AMC 2.5.2+.
Use it when a server needs a client certificate or a private CA, or speaks gRPC or MQTT. For a public HTTPS API, XMLHttpRequest is enough.
Clients¶
| Client | Talks to | You use | url example |
|---|---|---|---|
HttpsClient |
One HTTP server, such as a REST API | request(), which returns an HttpsReply |
https://dispatch.example.com/api/ |
GrpcClient |
One gRPC server: unary calls and streams in either direction. Messages are JS objects, defined by a descriptor set your plugin ships. | call(), which returns a GrpcOperation |
https://dispatch.example.com:8443 |
MqttClient |
One MQTT 3.1.1 broker. Connects only while active is true. |
subscriptions, messageReceived, publish() |
mqtts://broker.example.com:8883 |
The module also has LinkState, the state values the three clients share, and CertificateStore and CertificateComboBox for the operator's certificates. This page covers what the clients have in common. Their own properties, methods and signals are on their pages.
Certificates¶
The operator imports certificates once, in Settings → Certificates. A plugin refers to an entry by its id and never reads a key or a passphrase.
Importing¶
Import on that page asks for:
| Field | What it takes |
|---|---|
| Name | Optional. The certificate's common name when left empty. |
| Client certificate | A PEM file, with or without its private key, a DER file, or a PKCS#12 file (.p12, .pfx). Other certificates in the file are sent with it as its chain; they are not trusted. |
| Private key | The PEM key file that belongs to the certificate, for a DER certificate or a PEM file without its key. RSA, EC or DSA. Not asked for with PKCS#12. |
| CA certificates | PEM or DER. Connections that use the entry trust these instead of the system CAs. |
| Passphrase | Only when the key or the PKCS#12 file is protected. |
- An entry holds a client certificate, CA certificates, or both. Each file can be at most 1 MiB, and a client certificate can be imported only once.
- The passphrase goes to the system keychain, never to a file. If the keychain cannot store it, the import fails.
- After AMC restarts, it reads the passphrase back the first time a connection uses the entry. The OS may ask the operator to allow that.
- A CA inside a PKCS#12 file is only sent along with the client certificate. To trust a private CA, import it as CA certificates.
Deleting an entry also deletes its files and its passphrase. Entries are shared by all plugins, so this affects every connection that uses the entry. Each one closes at once: running requests end with "The client certificate was deleted.", and state becomes ConfigError with "The selected certificate no longer exists." until the plugin sets another certificateId.
Using an entry¶
- Set a client's
certificateIdto the entry'sid. - Store the id, not the name. Names need not be unique, while the id stays the same for the life of the entry. Importing the same certificate again after deleting it gives a new id.
- Let the operator choose in your settings panel with
CertificateComboBox, and keep the id withSettingsfromQtCore(see Data Singleton).
CertificateStore¶
Import: import QGroundControl.SecureConnections
A singleton with the entries the operator imported.
Properties¶
| Property | Type | Writable | Description |
|---|---|---|---|
certificates |
QList<CertificateEntry*> |
No | One CertificateEntry per entry, with the properties below |
importing |
bool |
No | true while an import waits for the system keychain to store its passphrase |
Each item in certificates is a CertificateEntry object, created by the store, with these read-only properties:
| Property | Type | Description |
|---|---|---|
id |
string |
The entry's id, for certificateId |
name |
string |
Display name |
subject |
string |
Common name of the client certificate. For an entry with only CA certificates, of the CA certificate that expires first. |
issuer |
string |
Common name of that certificate's issuer |
notAfter |
date |
When that certificate expires |
daysUntilExpiry |
int |
Calendar days (UTC) until notAfter: 0 on that day, negative after it |
status |
Status |
CertificateEntry.Valid, CertificateEntry.ExpiringSoon (under 30 days left), CertificateEntry.Expired or CertificateEntry.NotYetValid |
hasClientCertificate |
bool |
false for an entry with only CA certificates |
caCount |
int |
How many CA certificates the entry trusts instead of the system ones |
fingerprint |
string |
SHA-256 fingerprint of that certificate, as colon-separated upper-case hex |
status and daysUntilExpiry are recomputed every hour. When either changes, the entry emits statusChanged(), so bindings on them stay current.
Methods¶
| Method | Parameters | Returns | Description |
|---|---|---|---|
importCertificate(name, certificateFile, keyFile, caFile, passphrase) |
QString, QUrl, QUrl, QUrl, QString |
bool |
Adds an entry from files, like the Certificates page. Pass "" for a file you leave out. Reports through importFinished, which can fire before the call returns. false, without reporting anything, while another import is still running (importing is true). |
removeCertificate(id) |
QString |
bool |
Deletes the entry, its files and its keychain passphrase. false if no entry has this id. |
Importing and deleting are normally the operator's job, on the Certificates page.
Signals¶
| Signal | Parameters | Description |
|---|---|---|
certificatesChanged() |
-- | An entry was added or removed. |
certificateRemoved(id) |
QString id |
The entry with this id was deleted. |
importingChanged() |
-- | importing changed |
importFinished(result) |
QVariantMap result |
An import ended. result.id is the new entry's id, or result.error says why it failed. |
Example: warn before the certificate expires¶
DispatchData is the data singleton from the example at the end of this page.
import QtQuick
import QGroundControl.Controls
import QGroundControl.Palette
import QGroundControl.Plugin
import QGroundControl.SecureConnections
QGCLabel {
readonly property var certificate: CertificateStore.certificates.find(entry => entry.id === DispatchData.certificateId)
visible: !!certificate && certificate.status !== CertificateEntry.Valid
color: qgcPal.colorOrange
text: !certificate ? ""
: certificate.status === CertificateEntry.Expired ? qsTr("%1 has expired").arg(certificate.name)
: certificate.status === CertificateEntry.NotYetValid ? qsTr("%1 is not valid yet").arg(certificate.name)
: qsTr("%1 expires in %2 days").arg(certificate.name).arg(certificate.daysUntilExpiry)
}
CertificateComboBox¶
Import: import QGroundControl.SecureConnections
A combo box that lists "None" and every entry by name. It looks and behaves like QGCComboBox, but fills its own list from CertificateStore, so don't set model, textRole, valueRole, currentValue, currentIndex or alternateText.
| Property | Type | Writable | Description |
|---|---|---|---|
certificateId |
QString |
Yes | The chosen entry's id; "" for None. The box sets it when the operator picks an entry. |
- An expired entry is listed as "Name (expired)".
- An id that matches no entry, such as a deleted one, shows "Missing certificate" rather than None.
Picking an entry assigns certificateId, which replaces a binding you put on it. Write the choice back in onCertificateIdChanged:
CertificateComboBox {
certificateId: DispatchData.certificateId
onCertificateIdChanged: DispatchData.certificateId = certificateId
}
Connection rules¶
These rules hold for all three clients.
Shared properties and signals¶
| Property | Type | Writable | Description |
|---|---|---|---|
url |
QUrl |
Yes | The server; see url |
certificateId |
QString |
Yes | A CertificateStore entry id; see certificateId |
expectedHostName |
QString |
Yes | HttpsClient and MqttClient only; see expectedHostName |
state |
LinkState |
No | How the link stands; see LinkState |
errorString |
QString |
No | Explains state; empty while Connecting or Connected. See errorString. |
| Signal | Description |
|---|---|
configurationChanged() |
url, certificateId or expectedHostName changed; on MqttClient, also clientId or keepAlive. It is the notify signal of all of them, so a handler such as onUrlChanged runs when any of them changes. There is no urlChanged signal to connect() to. |
stateChanged() |
state changed |
errorStringChanged() |
errorString changed |
url¶
| Client | With TLS | Without TLS |
|---|---|---|
HttpsClient |
https://host:port/path/ (path optional) |
http:// |
GrpcClient |
https://host:port |
http:// |
MqttClient |
mqtts://host:port |
mqtt:// |
- The port is optional. It defaults to 443 for
https://, 80 forhttp://, 8883 formqtts://and 1883 formqtt://. - An empty
urlleaves the clientOff, with "No server is set." - Any other scheme, a url without a host or with port 0, or a malformed url is a
ConfigError: "The server URL must look like https://host:port or http://host:port." The message names the client's own schemes. - Credentials in the url, such as
https://user:secret@dispatch.example.com, are aConfigErrortoo: "The server URL must not contain credentials." Send credentials the way the client's page describes, such as an HTTP header or gRPC metadata.
certificateId¶
- Empty: no client certificate, and the server is checked against the system CAs.
- An entry's id: the client presents the entry's client certificate, if it has one. If the entry has CA certificates, the client trusts those instead of the system CAs.
- The client loads the entry when it sets up, not for each request. If the entry no longer exists,
stateisConfigErrorwith "The selected certificate no longer exists." If it cannot be loaded,stateisTlsErroranderrorStringsays why; see Retry after a certificate or keychain failure. - Without TLS it is ignored.
expectedHostName¶
HttpsClient and MqttClient check the server's certificate against the url's host. When you reach the server by another name, such as an IP address, set expectedHostName to the name its certificate carries. Empty checks the url's host. Without TLS it is ignored.
GrpcClient has no expectedHostName, because Qt GRPC cannot check a name other than the url's host. Use a url whose host the server's certificate names.
TLS verification¶
With TLS, the client always verifies the server: the certificate chain must lead to a trusted CA, and the certificate must name the host. Nothing turns either check off. TLS 1.2 is the minimum. A failed check is a TlsError.
To trust a private CA, the operator imports it as CA certificates, and your client uses that entry.
When a setting changes¶
Changing url, certificateId or expectedHostName sets the client up again. On an MqttClient, so does changing active, clientId or keepAlive.
- From the moment of the change,
HttpsClientandGrpcClientrequests wait for the new setup, andMqttClient.publish()returnsfalse. Nothing goes out under the old settings. - Changes made together, such as in one function or one binding update, cause a single setup. It starts once your code returns to the event loop.
- The old connection closes,
statebecomesConnecting(Offfor an inactiveMqttClient) anderrorStringis cleared. Then requests already sent end with "The connection settings changed." (GrpcClient: status CANCELLED). - The new settings are checked and the certificate loaded. Then the waiting requests go out, or end with the setup's
errorString.
Other properties, such as headers (HTTPS), metadata, descriptorSet and keepaliveInterval (gRPC), subscriptions (MQTT) or the timeouts, take effect without a new setup. Assigning a property the value it already has does nothing. A client first sets up once its QML component is complete, so its initial values cause a single setup.
Client certificate validity¶
Each time a client sets up with an entry that holds a client certificate, AMC compares the certificate's dates with the current time before it connects:
- Not valid yet:
TlsError, "The client certificate is not valid until date." - Expired:
TlsError, "The client certificate expired on date."
The client then does not connect at all. A server would refuse the certificate anyway, but under TLS 1.3 only after the handshake, where the refusal can look like a network error.
The check covers the client certificate, not CA certificates, and runs only at setup. A certificate that expires while a client is set up is caught at its next setup. To warn the operator earlier, read status and daysUntilExpiry from CertificateStore.certificates.
Retry after a certificate or keychain failure¶
When a setup cannot use the certificate entry, state is TlsError and the client has no connection. The causes include a keychain that cannot be reached, a key that cannot be decrypted, or a client certificate that is not valid now. Unlike a bad url or a deleted entry, this can pass without a setting change, for example once the keychain service is running or the certificate becomes valid. So the client tries the setup again, at most once a minute, because each attempt can make the OS prompt the operator:
HttpsClientandGrpcClient: the first request you send a minute or more after the failure sets the client up again and waits for it. A request sent sooner ends at once with the sameerrorString(GrpcClient: status UNAVAILABLE).- An active
MqttClienttries again from its reconnect timer.
After the operator refused the keychain prompt, or with the passphrase gone from the keychain, the client does not ask again by itself. It stays in TlsError until a setting changes, such as url or, on an MqttClient, active. If another client loads the entry in the meantime, the next request or MQTT reconnect sets the client up again, without a prompt.
Changing a setting sets the client up again at once. A server that rejects the handshake is not a setup failure, so the one-minute limit does not apply: the next request, or the next MQTT reconnect, tries again.
When your plugin is removed¶
AMC can't unload a plugin's data singleton while it is running. When the operator deletes a plugin that has one, AMC tells them to restart AMC to finish removing it. Until then the data singleton keeps running, and so do the clients in it: their connections stay open, and your timers can still send requests.
LinkState¶
state holds one of these values. Compare it with them, as in client.state === LinkState.Connected.
| Value | When | What to do |
|---|---|---|
LinkState.Off |
No url is set, or an MqttClient is not active. |
Nothing is sent. Set url, and active on an MqttClient, to connect. |
LinkState.Connecting |
A setup is under way. HttpsClient and GrpcClient learn how the link stands only from requests, so they also stay here until a request they send is answered or fails. On an MqttClient, a connection attempt is under way. |
HttpsClient, GrpcClient: send anyway; requests wait for the setup. MqttClient: wait for Connected. |
LinkState.Connected |
MqttClient: the broker accepted the session. HttpsClient, GrpcClient: the last request got an answer, other than those listed under Unreachable and AuthError. |
Carry on. An answer can still be an error, such as HTTP 404, so check each reply. |
LinkState.Unreachable |
No answer: no connection, a timeout, or a server that reported itself unavailable, such as HTTP 502, 503 or 504, or gRPC UNAVAILABLE. Under TLS 1.3, a server that refuses the client certificate can also end up here. | Show errorString. MqttClient reconnects by itself, with a growing delay. HttpsClient and GrpcClient don't resend; your next request tries again. |
LinkState.TlsError |
The TLS handshake failed, or the entry cannot be loaded, or its client certificate is not valid now. | Show errorString. The operator usually has to act, for example by importing the right CA or renewing the certificate. A setup that could not use the entry is retried at most once a minute; after a refused keychain prompt, only once another client has loaded the entry. |
LinkState.AuthError |
The server refused this client: HTTP 401 or 403, gRPC UNAUTHENTICATED or PERMISSION_DENIED, or an MQTT broker that rejected the client or one of its subscriptions. A refused subscription leaves the MQTT session up, and state returns to Connected once no listed filter is refused. |
Check the credentials you send and the client certificate. Sending the same request again won't help. |
LinkState.ConfigError |
The settings cannot work, such as a malformed url or a deleted certificate entry. On a GrpcClient, also while its descriptor set is missing or cannot be loaded. On an MqttClient, also a broker that does not accept MQTT 3.1.1. |
Fix what errorString names. Until then, HttpsClient and GrpcClient requests end at once, and MqttClient does not try to connect. |
When to send
HttpsClient and GrpcClient requests made during a setup wait for it, then go out. Send them whenever state is not Off or ConfigError. Don't wait for Connected: only an answered request gets there.
MqttClient publishes only while it is connected. Otherwise publish() returns false and nothing is queued. While active, it reconnects by itself after any failure except a ConfigError, waiting longer each time; see Reconnecting.
errorString¶
errorStringexplains every state other thanConnectingandConnected, during which it is empty.MqttClientalso leaves it empty while it is notactive.- It is meant for the operator, so show it as it is. It may be translated, or be Qt's or the server's own text: decide what to do from
state, never by comparing the text. - Bind to it rather than reading it in
onStateChanged: it can change whilestatestays the same, such as HTTP 401 then 403, bothAuthError. Whenstatechanges,errorStringalready explains the new state. - A request that ends because of the client's state carries the same text as its error.
- While a
GrpcClientcannot load its descriptor set,stateisConfigErroranderrorStringsays why, whatever the link is doing. - AMC already writes each new
errorStringto its log.
Example¶
A data singleton that keeps the server and the certificate in Settings, shows the link state, and polls an HTTPS API for work orders. It only sends while the state allows it.
pragma Singleton
import QtQuick
import QtCore
import QGroundControl.Plugin
import QGroundControl.SecureConnections
Item {
id: root
property string serverUrl: ""
property string certificateId: ""
property var workOrders: []
readonly property bool canSend: dispatch.state !== LinkState.Off
&& dispatch.state !== LinkState.ConfigError
readonly property string linkText: {
switch (dispatch.state) {
case LinkState.Connecting:
return qsTr("Connecting")
case LinkState.Connected:
return qsTr("Connected")
default:
return dispatch.errorString
}
}
function refresh() {
if (!canSend) {
return
}
const reply = dispatch.request("GET", "work-orders")
reply.finished.connect((status, error) => {
if (error === "" && status === 200) {
workOrders = reply.json()
}
})
}
Settings {
category: "Dispatch"
property alias serverUrl: root.serverUrl
property alias certificateId: root.certificateId
}
HttpsClient {
id: dispatch
url: root.serverUrl
certificateId: root.certificateId
}
Timer {
interval: 30000
running: true
repeat: true
triggeredOnStart: true
onTriggered: root.refresh()
}
}
Saved as DispatchData.qml, it is the DispatchData type. In the plugin's settings panel, below the standard header (see Settings), the operator sets the server and picks the certificate:
import QtQuick
import QtQuick.Layouts
import QGroundControl.Controls
import QGroundControl.Plugin
import QGroundControl.SecureConnections
GridLayout {
columns: 2
QGCLabel { text: qsTr("Server") }
QGCTextField {
Layout.fillWidth: true
text: DispatchData.serverUrl
placeholderText: "https://dispatch.example.com/api/"
onEditingFinished: DispatchData.serverUrl = text
}
QGCLabel { text: qsTr("Certificate") }
CertificateComboBox {
Layout.fillWidth: true
certificateId: DispatchData.certificateId
onCertificateIdChanged: DispatchData.certificateId = certificateId
}
QGCLabel { text: qsTr("Status") }
QGCLabel {
Layout.fillWidth: true
text: DispatchData.linkText
wrapMode: Text.WordWrap
}
}
A plugin that receives work over one of these clients can offer it to the operator as a mission; see Mission Requests.