Skip to content

Commit

Permalink
fix: improved parsing of requested scopes
Browse files Browse the repository at this point in the history
  • Loading branch information
jankapunkt committed Nov 27, 2023
1 parent fcb567b commit 77d00b2
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 6 deletions.
19 changes: 13 additions & 6 deletions lib/utils/scope-util.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
const isFormat = require('@node-oauth/formats');
const InvalidScopeError = require('../errors/invalid-scope-error');
const whiteSpace = /\s+/g;

module.exports = {
parseScope: function (requestedScope) {
// XXX: isFormat.nqschar will trat Arrays of strings like String,
// thus we additionally check, whether incoming scopes are Arrays
if (!isFormat.nqschar(requestedScope) || Array.isArray(requestedScope)) {
if (requestedScope == null) {
return undefined;
}

if (typeof requestedScope !== 'string') {
throw new InvalidScopeError('Invalid parameter: `scope`');
}

if (requestedScope == null) {
return undefined;
// XXX: this prevents spaced-only strings to become
// treated as valid nqchar by making them empty strings
requestedScope = requestedScope.trim();

if(!isFormat.nqschar(requestedScope)) {
throw new InvalidScopeError('Invalid parameter: `scope`');
}

return requestedScope.split(' ');
return requestedScope.split(whiteSpace);
}
};
45 changes: 45 additions & 0 deletions test/unit/utils/scope-util_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const { parseScope } = require('../../../lib/utils/scope-util');
const should = require('chai').should();

describe(parseScope.name, () => {
it('should return undefined on nullish values', () => {
const values = [undefined, null];
values.forEach(str => {
const compare = parseScope(str) === undefined;
compare.should.equal(true);
});
});
it('should throw on non-string values', () => {
const invalid = [1, -1, true, false, {}, ['foo'], [], () => {}, Symbol('foo')];
invalid.forEach(str => {
try {
parseScope(str);
should.fail();
} catch (e) {
e.message.should.eql('Invalid parameter: `scope`');
}
});
});
it('should throw on empty strings', () => {
const invalid = ['', ' ', ' ', '\n', '\t', '\r'];
invalid.forEach(str => {
try {
parseScope(str);
should.fail();
} catch (e) {
e.message.should.eql('Invalid parameter: `scope`');
}
});
});
it('should split space-delimited strings into arrays', () => {
const values = [
['foo', ['foo']],
['foo bar', ['foo', 'bar']],
['foo bar', ['foo', 'bar']],
];
values.forEach(([str, compare]) => {
const parsed = parseScope(str);
parsed.should.deep.equal(compare);
});
});
});

0 comments on commit 77d00b2

Please sign in to comment.