diff --git a/lib/parser.js b/lib/parser.js index 2bae3ae..21d2ec7 100644 --- a/lib/parser.js +++ b/lib/parser.js @@ -17,18 +17,42 @@ function getter(getFn) { }; } -function cloneNsMatrix(nsMatrix) { - var clone = Object.create(null), key; - for (key in nsMatrix) { - clone[key] = nsMatrix[key]; +/** + * Set a namespace matrix entry, recording the previous + * value on the given change log for later restoration. + * + * @param {Object} nsMatrix + * @param {Object} changes + * @param {string} key + * @param {string} value + */ +function setNsEntry(nsMatrix, changes, key, value) { + if (!(key in changes)) { + changes[key] = key in nsMatrix ? nsMatrix[key] : null; } - return clone; + + nsMatrix[key] = value; } -// per-matrix element name cache; stored under a symbol so it is -// invisible to the `for (key in nsMatrix)` clone above and gets -// collected together with the matrix it belongs to -var NAME_CACHE = Symbol('nameCache'); +/** + * Restore a namespace matrix, applying the given change log. + * + * @param {Object} nsMatrix + * @param {Object} changes + */ +function restoreNsMatrix(nsMatrix, changes) { + var key, value; + + for (key in changes) { + value = changes[key]; + + if (value === null) { + delete nsMatrix[key]; + } else { + nsMatrix[key] = value; + } + } +} function uriPrefix(prefix) { return prefix + '$uri'; @@ -141,7 +165,7 @@ export default function Parser(options) { /** * Namespace + node state shared across (streamed) parse runs. */ - var nsMatrixStack, + var nsChangesStack, nsMatrix, nodeStack; @@ -259,7 +283,7 @@ export default function Parser(options) { * Reset the parser state before a (streamed) parse run. */ function resetState() { - nsMatrixStack = isNamespace ? [] : null; + nsChangesStack = isNamespace ? [] : null; nsMatrix = isNamespace ? buildNsMatrix(nsUriToPrefix) : null; nodeStack = []; @@ -376,10 +400,10 @@ export default function Parser(options) { */ function parse(xml, streaming = false) { - var elNameCache = null, - elNameCacheMatrix = null; + var elNameCache = null; - var _nsMatrix, + var nsChanges, + nsSnapshot, anonymousNsCount = 0, tagStart = false, tagEnd = false, @@ -446,7 +470,6 @@ export default function Parser(options) { i = attrsStart, s = attrsString, l = s.length, - hasNewMatrix, newalias, value, alias, @@ -647,18 +670,25 @@ export default function Parser(options) { } if (nsMatrix[newalias] !== alias) { - if (!hasNewMatrix) { - nsMatrix = cloneNsMatrix(nsMatrix); - hasNewMatrix = true; + + // mutate matrix in place, tracking changes + // for restoration once the element closes; + // null prototype guards against special keys + if (!nsChanges) { + nsChanges = Object.create(null); } - nsMatrix[newalias] = alias; + // invalidate cached element names + ns snapshot + elNameCache = null; + nsSnapshot = null; + + setNsEntry(nsMatrix, nsChanges, newalias, alias); if (newalias === 'xmlns') { - nsMatrix[uriPrefix(alias)] = nsUri; + setNsEntry(nsMatrix, nsChanges, uriPrefix(alias), nsUri); defaultAlias = alias; } - nsMatrix[nsUriPrefix] = nsUri; + setNsEntry(nsMatrix, nsChanges, nsUriPrefix, nsUri); } // expose xmlns(:asd)="..." in attributes @@ -781,7 +811,14 @@ export default function Parser(options) { }), 'attrs': getter(getAttrs), 'ns': getter(function() { - return nsMatrix; + + // expose a stable snapshot of the current namespace + // matrix, cached until the matrix changes + if (!nsSnapshot) { + nsSnapshot = Object.assign(Object.create(null), nsMatrix); + } + + return nsSnapshot; }) }); } @@ -1038,15 +1075,11 @@ export default function Parser(options) { if (isNamespace) { - _nsMatrix = nsMatrix; - if (tagStart) { - // remember old namespace - // unless we're self-closing - if (!tagEnd) { - nsMatrixStack.push(_nsMatrix); - } + // track namespace changes on this element + // for later restoration + nsChanges = null; if (cachedAttrs === null) { @@ -1062,18 +1095,21 @@ export default function Parser(options) { maybeNS = false; } } + + // remember changes made by this element + // unless we're self-closing + if (!tagEnd) { + nsChangesStack.push(nsChanges); + } } _elementName = elementName; - // memoize normalized names per namespace matrix; tag names + // memoize normalized names per namespace state; tag names // typically repeat heavily and the matrix rarely changes. - if (elNameCacheMatrix !== nsMatrix) { - elNameCache = nsMatrix[NAME_CACHE]; - if (elNameCache === undefined) { - elNameCache = nsMatrix[NAME_CACHE] = Object.create(null); - } - elNameCacheMatrix = nsMatrix; + // the cache is rebuilt whenever the matrix changed. + if (elNameCache === null) { + elNameCache = Object.create(null); } var _cachedName = elNameCache[elementName]; @@ -1144,9 +1180,16 @@ export default function Parser(options) { // restore old namespace if (isNamespace) { if (!tagStart) { - nsMatrix = nsMatrixStack.pop(); - } else { - nsMatrix = _nsMatrix; + nsChanges = nsChangesStack.pop(); + } + + if (nsChanges) { + restoreNsMatrix(nsMatrix, nsChanges); + nsChanges = null; + + // invalidate cached element names + ns snapshot + elNameCache = null; + nsSnapshot = null; } } } diff --git a/test/elements.js b/test/elements.js index cbfd57e..30c7f14 100644 --- a/test/elements.js +++ b/test/elements.js @@ -1,3 +1,7 @@ +import assert from 'node:assert'; + +import { Parser } from 'saxen'; + import { test } from './helper.js'; // // default ns: @@ -1643,4 +1647,109 @@ describe('elements', function() { ], }); + + // nested prefix shadowing, restored after close + test({ + xml: ( + '' + + '' + + '' + + '' + + '' + + '' + ), + ns: true, + expect: [ + [ 'openTag', 'root' ], + [ 'openTag', 'rss:x' ], + [ 'openTag', 'rss:y' ], + [ 'closeTag', 'rss:y' ], + [ 'closeTag', 'rss:x' ], + [ 'openTag', 'atom:z' ], + [ 'closeTag', 'atom:z' ], + [ 'closeTag', 'root' ], + ], + }); + + // repeated tag name across shadowed scope boundary + test({ + xml: ( + '' + + '' + + '' + + '' + + '' + + '' + ), + ns: true, + expect: [ + [ 'openTag', 'root' ], + [ 'openTag', 'rss:x' ], + [ 'openTag', 'rss:y' ], + [ 'closeTag', 'rss:y' ], + [ 'closeTag', 'rss:x' ], + [ 'openTag', 'atom:y' ], + [ 'closeTag', 'atom:y' ], + [ 'closeTag', 'root' ], + ], + }); + + // self-closed element declarations, restored after close + test({ + xml: ( + '' + + '' + + '' + + '' + ), + ns: true, + expect: [ + [ 'openTag', 'root' ], + [ 'openTag', 'atom:x' ], + [ 'closeTag', 'atom:x' ], + [ 'error', 'missing namespace on ' ], + ], + }); + + + describe('namespace declaration scoping', function() { + + // verify deeply nested declarations scale linearly + // cf. https://github.com/nikku/saxen/security/advisories/GHSA-6w8c-5m3c-g2m8 + it('should handle deeply nested namespace declarations', function() { + + // given + var depth = 3000; + + var open = '', close = ''; + for (var i = 0; i < depth; i++) { + open += ''; + close = '' + close; + } + + var xml = '' + open + close + ''; + + var parser = new Parser({ proxy: true }); + + parser.ns({}); + + var count = 0; + var lastName; + + parser.on('openTag', function(el) { + count++; + lastName = el.name; + }); + + // when + var err = parser.parse(xml); + + // then + assert.ifError(err); + assert.equal(count, depth + 1); + assert.equal(lastName, 'p' + (depth - 1) + ':e'); + }); + + }); + }); \ No newline at end of file diff --git a/test/modes.js b/test/modes.js index 402afe1..cce8047 100644 --- a/test/modes.js +++ b/test/modes.js @@ -87,6 +87,52 @@ describe('modes', function() { assert.ok(counter === 1, 'parsed one node'); }); + + it('exposing stable ns snapshots', function() { + + // given + var parser = new Parser({ proxy: true }); + + parser.ns({ + 'urn:1': 'one', + 'urn:2': 'two' + }); + + var captured, capturedAgain; + + parser.on('openTag', function(el) { + if (el.originalName === 'a:x') { + captured = el.ns; + capturedAgain = el.ns; + } + }); + + // when + parser.parse( + '' + + '' + + '' + + '' + + '' + ); + + // then + // snapshot is cached while matrix is unchanged + assert.strictEqual(captured, capturedAgain); + + // captured snapshot remains valid after parse moved on + assert.deepEqual(captured, { + 'one': 'one', + 'one$uri': 'urn:1', + 'two': 'two', + 'two$uri': 'urn:2', + 'a': 'one', + 'a$uri': 'urn:1', + 'b': 'two', + 'b$uri': 'urn:2' + }); + }); + });