Skip to content

Commit

Permalink
Correct validations.
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Jul 20, 2017
1 parent 9f6d351 commit dcaf4f7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
14 changes: 10 additions & 4 deletions lib/handlers/subscribe.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 7 additions & 10 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
Expand All @@ -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,
Expand All @@ -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()
})
})
})

0 comments on commit dcaf4f7

Please sign in to comment.