Wan Chap
Wan Chap

Reputation: 931

How to catch "access error" when publish inaccessible topic in mqtt.js?

I am creating a project using node.js with mqtt.js and mosquitto broker. In mosquitto config file, I have setup a pwfile, aclfile to control which topic can be accessed by which user.

Everything works fine, if the username, password, publish topic and subscribe topic are correct.

But if I change the publish topic to an inaccessible topic, it seems successfully publish the topic without any error in mqtt.js, but the message is never been publish.

Is there anyway to catch error when publish or subscribe to inaccessible topic?

https://github.com/mqttjs/MQTT.js/blob/master/README.md#publish

I try to catch the error in callback function with qos=1, but it seems the mosquitto broker acknowledge the client without any error. Of cause, the message didn't publish to the topic, since that client don't have the access right to that topic.

client.publish('inaccessible_topic', 'hello world', {qos: 1}, (err) => {
  if (err) console.log('error occur: ', err);
  else console.log('message successfully publish');
});

I expect mosquitto will return some sort of error (error occur: <error message>) when publish to the inaccessible topic, but it didn't (message sucessfully publish).

I wonder if it is even possible to catch such error. Does mosquitto handle such error, if so, how do I catch such error using mqtt.js?

Upvotes: 1

Views: 1732

Answers (2)

dude
dude

Reputation: 180

With MQTT 5 it can be done. Mosquitto sends the needed response code in the PUBACK and PUBREC packets. All you need to do is to set your mqttjs-clients protocol to mqtt 5 and choose a qos of 1 or 2 (I tested it with qos=2).

const mqtt = require('mqtt');
const mqttClient = mqtt.connect('mqtt://insertyouradresshere.org', {
  protocolId: 'MQTT',
  protocolVersion: 5,
  username: 'myusername',
  password: 'mypassword',
});

If the publish fails then your callback will be called with an error.

Upvotes: 0

hardillb
hardillb

Reputation: 59638

You don't.

The broker will not tell the client if it tried to publish to a topic it doesn't have access to, it will just silently just drop the message.

This would be a security vulnerability in that it would expose what topics are available.

Upvotes: 2

Related Questions