Skip to content

Commit

Permalink
update tests to reflect new 1p rules
Browse files Browse the repository at this point in the history
  • Loading branch information
antonok-edm committed Jan 17, 2020
1 parent e243cfb commit a9e9213
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,11 @@ export const generateClassIdStylesheet = (tabId: number, classes: string[], ids:
}
}

export const cosmeticFilterRuleExceptions = (tabId: number, exceptions: string[], randomizedClassName: string) => {
export const cosmeticFilterRuleExceptions = (tabId: number, exceptions: string[]) => {
return {
type: types.COSMETIC_FILTER_RULE_EXCEPTIONS,
tabId,
exceptions,
randomizedClassName
exceptions
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

const uuidv4 = require('uuid/v4')

import shieldsPanelActions from '../actions/shieldsPanelActions'

const informTabOfCosmeticRulesToConsider = (tabId: number, hideRules: string[], customStyleRules: any) => {
if (hideRules.length !== 0 || (customStyleRules && customStyleRules !== {})) {
const informTabOfCosmeticRulesToConsider = (tabId: number, hideRules: string[]) => {
if (hideRules.length !== 0) {
const message = {
type: 'cosmeticFilterConsiderNewRules',
hideRules,
customStyleRules
hideRules
}
const options = {
frameId: 0
Expand All @@ -23,7 +20,7 @@ const informTabOfCosmeticRulesToConsider = (tabId: number, hideRules: string[],
export const injectClassIdStylesheet = (tabId: number, classes: string[], ids: string[], exceptions: string[]) => {
chrome.braveShields.hiddenClassIdSelectors(classes, ids, exceptions, (jsonSelectors) => {
const hideSelectors = JSON.parse(jsonSelectors)
informTabOfCosmeticRulesToConsider(tabId, hideSelectors, null)
informTabOfCosmeticRulesToConsider(tabId, hideSelectors)
})
}

Expand All @@ -34,7 +31,17 @@ export const applyAdblockCosmeticFilters = (tabId: number, hostname: string) =>
return
}

informTabOfCosmeticRulesToConsider(tabId, resources.hide_selectors, resources.style_selectors)
informTabOfCosmeticRulesToConsider(tabId, resources.hide_selectors)

let styledStylesheet = ''
for (const selector in resources.style_selectors) {
styledStylesheet += selector + '{' + resources.style_selectors[selector].join(';') + ';}\n'
}
chrome.tabs.insertCSS(tabId, {
code: styledStylesheet,
cssOrigin: 'user',
runAt: 'document_start'
})

if (resources.injected_script) {
chrome.tabs.executeScript(tabId, {
Expand All @@ -43,15 +50,7 @@ export const applyAdblockCosmeticFilters = (tabId: number, hostname: string) =>
})
}

const randomizedClassName = 'b' + uuidv4().split('-').slice(0, 2).join('')

chrome.tabs.insertCSS(tabId, {
code: `.${randomizedClassName} {display: none !important;}`,
cssOrigin: 'user',
runAt: 'document_start'
})

shieldsPanelActions.cosmeticFilterRuleExceptions(tabId, resources.exceptions, randomizedClassName)
shieldsPanelActions.cosmeticFilterRuleExceptions(tabId, resources.exceptions)
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,8 +368,7 @@ export default function shieldsPanelReducer (
}
state = shieldsPanelState.saveCosmeticFilterRuleExceptions(state, action.tabId, action.exceptions)
chrome.tabs.sendMessage(action.tabId, {
type: 'cosmeticFilterGenericExceptions',
randomizedClassName: action.randomizedClassName
type: 'cosmeticFilteringBackgroundReady'
})
break
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,56 +16,78 @@ const queriedClasses = new Set()
let notYetQueriedClasses: string[] = []
let notYetQueriedIds: string[] = []

let randomizedClassName: string | undefined = undefined
let backgroundReady: boolean = false

const fetchNewClassIdRules = function () {
// Only let the backend know that we've found new classes and id attributes
// if the back end has told us its ready to go and we have at least one new
// class or id to query for.
if (backgroundReady) {
if (notYetQueriedClasses.length !== 0 || notYetQueriedIds.length !== 0) {
chrome.runtime.sendMessage({
type: 'hiddenClassIdSelectors',
classes: notYetQueriedClasses,
ids: notYetQueriedIds
})
notYetQueriedClasses = []
notYetQueriedIds = []
}
} else {
setTimeout(fetchNewClassIdRules, 100)
}
}

const handleMutations = function (mutations: any[]) {
for (const aMutation of mutations) {
if (aMutation.type !== 'attributes') {
continue
}
if (aMutation.type === 'attribute') {
// Since we're filtering for attribute modifications, we can be certain
// that the targets are always HTMLElements, and never TextNode.
const changedElm = aMutation.target
switch (aMutation.attributeName) {
case 'class':
for (const aClassName of changedElm.classList.values()) {
if (queriedClasses.has(aClassName) === false) {
notYetQueriedClasses.push(aClassName)
queriedClasses.add(aClassName)
}
}
break

// Since we're filtering for attribute modifications, we can be certain
// that the targets are always HTMLElements, and never TextNode.
const changedElm = aMutation.target
switch (aMutation.attributeName) {
case 'class':
for (const aClassName of changedElm.classList.values()) {
if (queriedClasses.has(aClassName) === false) {
notYetQueriedClasses.push(aClassName)
queriedClasses.add(aClassName)
case 'id':
const mutatedId = changedElm.id
if (queriedIds.has(mutatedId) === false) {
notYetQueriedIds.push(mutatedId)
queriedIds.add(mutatedId)
}
break
}
} else if (aMutation.addedNodes.length > 0) {
for (const element of aMutation.addedNodes) {
const id = element.id
if (id && !queriedIds.has(id)) {
notYetQueriedIds.push(id)
queriedIds.add(id)
}
break

case 'id':
const mutatedId = changedElm.id
if (queriedIds.has(mutatedId) === false) {
notYetQueriedIds.push(mutatedId)
queriedIds.add(mutatedId)
const classList: any = element.classList
if (classList) {
for (const className of classList.values()) {
if (className && !queriedClasses.has(className)) {
notYetQueriedClasses.push(className)
queriedClasses.add(className)
}
}
}
break
}
}
}

// Only let the backend know that we've found new classes and id attributes
// if (1) the back end has told us its ready to go
// (e.g. randomizedClassName has been set) and we have at least one
// new class or id to query for.
if (randomizedClassName !== undefined &&
(notYetQueriedClasses.length !== 0 || notYetQueriedIds.length !== 0)) {
chrome.runtime.sendMessage({
type: 'hiddenClassIdSelectors',
classes: notYetQueriedClasses,
ids: notYetQueriedIds
})
notYetQueriedClasses = []
notYetQueriedIds = []
}
fetchNewClassIdRules()
}

const cosmeticObserver = new MutationObserver(handleMutations)
let observerConfig = {
subtree: true,
childList: true,
attributeFilter: ['id', 'class']
}
cosmeticObserver.observe(document.documentElement, observerConfig)
Expand Down Expand Up @@ -210,18 +232,6 @@ const isSubTreeFirstParty = (elm: Element, possibleQueryResult?: IsFirstPartyQue
)
}

const hideSubtree = (elm: HTMLElement) => {
if (elm.classList) {
if (randomizedClassName) {
elm.classList.add(randomizedClassName)
} else {
console.error('Random class name was not initialized yet')
}
} else if (elm.parentNode) {
(elm.parentNode as HTMLElement).removeChild(elm)
}
}

const hideSelectors = (selectors: string[]) => {
if (selectors.length === 0) {
return
Expand Down Expand Up @@ -304,9 +314,8 @@ const pumpCosmeticFilterQueues = () => {
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const action = typeof msg === 'string' ? msg : msg.type
switch (action) {
case 'cosmeticFilterGenericExceptions': {
randomizedClassName = msg.randomizedClassName
sendResponse(null)
case 'cosmeticFilteringBackgroundReady': {
backgroundReady = true
break
}

Expand All @@ -320,6 +329,7 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
firstRunQueue.add(aHideRule)
}
pumpCosmeticFilterQueues()
break
}
}
})
22 changes: 22 additions & 0 deletions components/brave_shields/browser/ad_block_service_browsertest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,28 @@ IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest, CosmeticFilteringSimple) {
EXPECT_TRUE(as_expected);
}

// Test cosmetic filtering ignores content determined to be 1st party
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest,
CosmeticFilteringProtect1p) {
UpdateAdBlockInstanceWithRules("b.com##.fpsponsored\n");

WaitForBraveExtensionShieldsDataReady();

GURL tab_url = embedded_test_server()->GetURL("b.com",
"/cosmetic_filtering.html");
ui_test_utils::NavigateToURL(browser(), tab_url);

content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();

bool as_expected = false;
ASSERT_TRUE(ExecuteScriptAndExtractBool(
contents,
"checkSelector('.fpsponsored', 'display', 'block')",
&as_expected));
EXPECT_TRUE(as_expected);
}

// Test cosmetic filtering on elements added dynamically
IN_PROC_BROWSER_TEST_F(CosmeticFilteringEnabledTest, CosmeticFilteringDynamic) {
UpdateAdBlockInstanceWithRules("##.blockme");
Expand Down
Loading

0 comments on commit a9e9213

Please sign in to comment.