Azure / azure-iot-sdk-node

A Node.js SDK for connecting devices to Microsoft Azure IoT services
https://docs.microsoft.com/en-us/azure/iot-hub/
Other
261 stars 226 forks source link

ModuleClient.setOptions overwrites the previous options #1214

Open hiroyha1 opened 4 months ago

hiroyha1 commented 4 months ago

Context

Description of the issue

The ca option is set in _fromEnvironmentEdge function.

const methodClient = new MethodClient(authenticationProvider);
methodClient.setOptions({ ca });

However, MqttBase.setOptions does not merge _options, so calling setOptions method in the callback of ModuleClient.fromEnvironment will overwrite the ca option, resulting in a certificate error.

  setOptions(options: any): void {
    this._options = options;
  }

Code sample exhibiting the issue

'use strict';

var Transport = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').ModuleClient;

Client.fromEnvironment(Transport, function (err, client) {
  if (err) {
    console.error(err.toString());
    process.exit(-1);
  } else {
    let options = {};
    client.setOptions(options);
    client.open(function (err) {
      if (err) {
        console.error(err.toString());
        process.exit(-1);        
      }
      console.log('IoT Hub module client initialized');
    });
  }
});

Console log of the issue

$ nodejs app.js
UnauthorizedError: mqtt.js returned Failure on first connection (Not authorized): self-signed certificate error

Workaround

Get the current options from client._methodClient._options (there is not getOptions method!) and merge them by yourself.

    let options = client._methodClient._options;
    options.tokenRenewal = {
      tokenValidTimeInSeconds: 3600,
      tokenRenewalMarginInSeconds: 900
    };
    client.setOptions(options);