diff --git a/lib/handlers/subscribe.js b/lib/handlers/subscribe.js index 1cc77343..0dc801f2 100644 --- a/lib/handlers/subscribe.js +++ b/lib/handlers/subscribe.js @@ -38,20 +38,26 @@ function authorize (sub, done) { var client = this.client var topic = sub.topic var end = topic.length - 1 + var endMinus = end - 1 var err + var slashInPreEnd = endMinus > 0 && topic.charCodeAt(endMinus) !== 47 + if (topic.length === 0) { + return done(new Error('impossible to subscribe to an empty topic')) + } for (var i = 0; i < topic.length; i++) { switch (topic.charCodeAt(i)) { case 35: - if (i !== end) { + var notAtTheEnd = i !== end + if (notAtTheEnd || slashInPreEnd) { err = new Error('# is only allowed in SUBSCRIBE in the last position') - client.emit('error', err) return done(err) } break case 43: - if (i < end - 1 && topic.charCodeAt(i + 1) !== 47) { + var pastChar = i < end - 1 && topic.charCodeAt(i + 1) !== 47 + var preChar = i > 1 && topic.charCodeAt(i - 1) !== 47 + if (pastChar || preChar) { err = new Error('+ is only allowed in SUBSCRIBE between /') - client.emit('error', err) return done(err) } break diff --git a/test/basic.js b/test/basic.js index 2982f94d..6105141e 100644 --- a/test/basic.js +++ b/test/basic.js @@ -525,8 +525,7 @@ test('publish invalid topic with #', function (t) { }) }) - eos(s.conn, function () { - t.equal(s.broker.connectedClients, 0, 'no connected clients') + s.broker.on('clientError', function () { t.end() }) }) @@ -546,16 +545,19 @@ test('publish invalid topic with +', function (t) { }) }) - eos(s.conn, function () { - t.equal(s.broker.connectedClients, 0, 'no connected clients') + s.broker.on('clientError', function () { t.end() }) }) -;['base/#/sub', 'base/#sub', 'base/+xyz/sub', ''].forEach(function (topic) { +;['base/#/sub', 'base/#sub', 'base/sub#', 'base/xyz+/sub', 'base/+xyz/sub'].forEach(function (topic) { test('subscribe to invalid topic with "' + topic + '"', function (t) { var s = connect(setup()) + s.broker.on('clientError', function () { + t.end() + }) + s.inStream.write({ cmd: 'subscribe', messageId: 24, @@ -564,10 +566,5 @@ test('publish invalid topic with +', function (t) { qos: 0 }] }) - - eos(s.conn, function () { - t.equal(s.broker.connectedClients, 0, 'no connected clients') - t.end() - }) }) })