0
0
mirror of https://github.com/twbs/bootstrap.git synced 2024-11-29 11:24:18 +01:00

Prevent getSelector from returning URLs as selector (#32586)

* added checks to getSelector in util to prevent returning hrefs that are invalid selectors

* restored compatibility for the class selector and added test cases for keeping urls from being returned as a selector

Co-authored-by: XhmikosR <xhmikosr@gmail.com>
This commit is contained in:
Florian Vick 2021-02-03 20:58:54 +01:00 committed by GitHub
parent 3770b7b9e3
commit 2a9d72133d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 1 deletions

View File

@ -36,7 +36,20 @@ const getSelector = element => {
let selector = element.getAttribute('data-bs-target') let selector = element.getAttribute('data-bs-target')
if (!selector || selector === '#') { if (!selector || selector === '#') {
const hrefAttr = element.getAttribute('href') let hrefAttr = element.getAttribute('href')
// The only valid content that could double as a selector are IDs or classes,
// so everything starting with `#` or `.`. If a "real" URL is used as the selector,
// `document.querySelector` will rightfully complain it is invalid.
// See https://github.com/twbs/bootstrap/issues/32273
if (!hrefAttr || (!hrefAttr.includes('#') && !hrefAttr.startsWith('.'))) {
return null
}
// Just in case some CMS puts out a full URL with the anchor appended
if (hrefAttr.includes('#') && !hrefAttr.startsWith('#')) {
hrefAttr = '#' + hrefAttr.split('#')[1]
}
selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null
} }

View File

@ -57,6 +57,28 @@ describe('Util', () => {
expect(Util.getSelectorFromElement(testEl)).toEqual('.target') expect(Util.getSelectorFromElement(testEl)).toEqual('.target')
}) })
it('should return null if a selector from a href is a url without an anchor', () => {
fixtureEl.innerHTML = [
'<a id="test" data-bs-target="#" href="foo/bar.html"></a>',
'<div class="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toBeNull()
})
it('should return the anchor if a selector from a href is a url', () => {
fixtureEl.innerHTML = [
'<a id="test" data-bs-target="#" href="foo/bar.html#target"></a>',
'<div id="target"></div>'
].join('')
const testEl = fixtureEl.querySelector('#test')
expect(Util.getSelectorFromElement(testEl)).toEqual('#target')
})
it('should return null if selector not found', () => { it('should return null if selector not found', () => {
fixtureEl.innerHTML = '<a id="test" href=".target"></a>' fixtureEl.innerHTML = '<a id="test" href=".target"></a>'